<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Muhammad Ahmed on Medium]]></title>
        <description><![CDATA[Stories by Muhammad Ahmed on Medium]]></description>
        <link>https://medium.com/@ahmedcs1995?source=rss-1fb3aebd8d62------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Ix7SIcjovLnvgqIL.</url>
            <title>Stories by Muhammad Ahmed on Medium</title>
            <link>https://medium.com/@ahmedcs1995?source=rss-1fb3aebd8d62------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 13:57:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ahmedcs1995/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Paging3 with Room Persistance]]></title>
            <link>https://medium.com/@ahmedcs1995/paging3-with-room-persistance-dc176542a0a6?source=rss-1fb3aebd8d62------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc176542a0a6</guid>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-developers]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Muhammad Ahmed]]></dc:creator>
            <pubDate>Sun, 06 Feb 2022 12:29:37 GMT</pubDate>
            <atom:updated>2022-02-06T12:29:37.733Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Be2LonPmzxiqqEYmKSBM9A.png" /></figure><p>I have been working on a chat application similar to Whatsapp where I need to put messages into a database and observer those database changes into fragments and refresh accordingly I was using Live data for refreshing the view. Later on, I was facing the performance issue since If we have lots of messages in a single conversation Live-data was not instantly refreshed it was taking lots of time to get the updated data.</p><p>So I did a little bit of research about how do I implement pagination with LiveData and I came across Google&#39;s official Paging Library.</p><p>So In this article, we will see how we can implement a paging library in our project so that we can provide a good user experience in our App so let’s get jump into it.</p><p>First, we need to add room for a persistence library in our android project. <br>In your build.gradle(app)</p><pre>implementation &quot;androidx.room:room-runtime:$room_version&quot;<br>kapt &quot;androidx.room:room-compiler:$room_version&quot;<br>implementation &quot;androidx.room:room-paging:$room_version&quot;<br>implementation &quot;androidx.room:room-ktx:$room_version&quot;</pre><p>Once you are done syncing your project. You need to create your <strong>AppDatabase</strong> abstract class, <strong>Dao</strong> abstract class/interface and setup Repository, and ViewModel. If you are too overwhelmed about these classes don’t worry I will add a link to the code at the end of the article.</p><p>In your <strong>Dao</strong></p><pre>@Query(“SELECT * FROM tbl_notes”)<br>fun getAll(): PagingSource&lt;Int, NoteItem&gt;</pre><p>After this, in our repository</p><pre>Pager(PagingConfig(PAGE_SIZE)) <strong>{<br>    </strong>mNotesDao.getAll()<br><strong>}</strong>.flow</pre><p>You can configure your <strong>PAGE_SIZE</strong> either In constants or in your repository.</p><p>Now we are done setting up <strong>Dao</strong> and <strong>repository</strong> classes. We need to make our custom PagingAdapter</p><pre>class PagingAdapter : PagingDataAdapter&lt;NoteItem, PagingAdapter.ViewHolder&gt;(DiffCallback()) {<br><br>    class ViewHolder(private val binding : NoteItemBinding) : RecyclerView.ViewHolder(binding.<em>root</em>) {<br>        fun onBind(item : NoteItem) {<br>            binding.title.<em>text </em>= item.name<br>            binding.description.<em>text </em>= item.description<br>        }<br>    }<br><br>    class DiffCallback : DiffUtil.ItemCallback&lt;NoteItem&gt;() {<br>        override fun areItemsTheSame(oldItem: NoteItem, newItem: NoteItem): Boolean {<br>            return oldItem.id == newItem.id<br>        }<br><br>        override fun areContentsTheSame(oldItem: NoteItem, newItem: NoteItem): Boolean {<br>            return oldItem == newItem<br>        }<br>    }<br><br>    override fun onBindViewHolder(holder: ViewHolder, position: Int) {<br>       val item = getItem(position) ?: return<br>        holder.onBind(item)<br>    }<br><br>    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {<br>        return ViewHolder(NoteItemBinding.inflate(LayoutInflater.from(parent.<em>context</em>),parent,false))<br>    }<br>}</pre><p>It looks similar to our traditional RecyclerViewAdapter except it needs <strong>DiffCallback</strong> to refresh the data smartly so that it does not create overhead.</p><p>Now we need to observe changes in your View(Activity/Fragment).</p><pre><em>lifecycleScope</em>.<em>launch </em><strong>{<br>   </strong>mViewModel.notes.collectLatest <strong>{<br>       </strong>mAdapter.submitData(<strong>it</strong>)<br>   <strong>}<br>}</strong></pre><p>Before this, we need to configure our Paging adapter with RecyclerView. Its quite simple</p><pre>val adapter = PagingAdapter().<em>also </em><strong>{ </strong>mAdapter = <strong>it }<br></strong>binding.recyclerView.<em>adapter </em>= adapter<br>binding.recyclerView.<em>layoutManager </em>= LinearLayoutManager(this)</pre><p>That’s it we have implemented Paging in our RecyclerView. It is quite easy and simple thanks to Android Jetpack.</p><p>Code Link: <a href="https://github.com/ahmedcs2600/RoomPaging3">https://github.com/ahmedcs2600/RoomPaging3</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc176542a0a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Signal Protocol Implementation In IOS (End — End Encryption)]]></title>
            <link>https://medium.com/@ahmedcs1995/signal-protocol-implementation-in-ios-end-end-encryption-edb02d11268d?source=rss-1fb3aebd8d62------2</link>
            <guid isPermaLink="false">https://medium.com/p/edb02d11268d</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios-apps]]></category>
            <dc:creator><![CDATA[Muhammad Ahmed]]></dc:creator>
            <pubDate>Sun, 10 Oct 2021 18:26:15 GMT</pubDate>
            <atom:updated>2021-10-10T18:26:15.560Z</atom:updated>
            <content:encoded><![CDATA[<h3>Signal Protocol Implementation In IOS (End — End Encryption)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*mijaX0NkttR-cYyaOEpplQ.png" /></figure><p>I have been working on end-end encryption using the Signal protocol. By that time I was working, I couldn’t find an example of how to integrate Signal Protocol(end-end encryption) on IOS.</p><p>For understanding the Logic and algorithm of signal protocol you can check out their documentation page because here we will be using their Library/SDK.<br><a href="https://signal.org/docs/">https://signal.org/docs/</a></p><p>We will be using their swift protocol available on GitHub. So let’s start implementing end-end encryption in IOS.<br><a href="https://github.com/signalapp/libsignal-client/tree/master/swift">https://github.com/signalapp/libsignal-client/tree/master/swift</a></p><p>Add ‘SignalClient’ and ‘SignalCoreKit’ as dependencies in your Podfile:</p><pre>pod &#39;SignalClient&#39;, git: &#39;https://github.com/signalapp/libsignal-client.git&#39;<br> pod &#39;SignalCoreKit&#39;, git: &#39;https://github.com/signalapp/SignalCoreKit.git&#39;</pre><p>Make sure you install the required Rust dependencies. You may be prompted to install Rust dependencies.</p><p>After you have installed and configure the Signal Protocol in your IOS project, then let&#39;s get into the code.</p><h3>Keys Registration At Install Time :</h3><p>At the install time, We need to generate IdentityKeyPair, registrationId, SignedPreKeyRecord &amp; SignedPreKeyRecord. Make sure you have imported SignalClient</p><h4>IdentityKeyPair:</h4><pre>static func generateIdentityKeyPair() -&gt; IdentityKeyPair {<br>        return IdentityKeyPair.generate()<br>}</pre><h4>RegistrationId:</h4><pre>static func generateRegistrationId() -&gt; UInt32 {<br>        return UInt32.random(in: 0...0x3FFF)<br>}</pre><h4>SignedPreKeyRecord:</h4><pre>static func generateSignedPreKey(identityKeyPair : IdentityKeyPair, signedPreKeyId : UInt32) throws -&gt; SignedPreKeyRecord {<br>        <br>        let privateKey = PrivateKey.generate()<br>        let signature = identityKeyPair.privateKey.generateSignature(message: privateKey.publicKey.serialize())<br>        return try SignedPreKeyRecord(id: signedPreKeyId, timestamp: UInt64(Date().currentTimeMillis()), privateKey: privateKey, signature: signature)<br>    }</pre><h4>PreKeys:</h4><pre>static func generatePreKeys(start : UInt32, count : UInt32) throws -&gt; [PreKeyRecord]  {<br>        var results = [PreKeyRecord]()<br>     <br>        for i in start..&lt;count {<br>            let id = ((start + i) % (maxVal-1)) + 1<br>            let privateKey = PrivateKey.generate()<br>            let publicKey = privateKey.publicKey<br>            results.append(try PreKeyRecord(id: UInt32(id), publicKey: publicKey, privateKey: privateKey))<br>        }<br>        <br>        return results<br>    }</pre><pre><strong>static</strong> <strong>let</strong> maxVal : UInt32 = 16777215</pre><pre>public static func generateKeys() throws -&gt; Registration {<br>        let identityKeyPair = generateIdentityKeyPair()<br>        let registrationId = generateRegistrationId()<br>        let signedPreKey = try generateSignedPreKey(identityKeyPair: identityKeyPair, signedPreKeyId: UInt32.random(in: 1...maxVal - 1))<br>        let start = UInt32.random(in: 1...maxVal - 101)<br>        let preKeys =  try generatePreKeys(start: start, count: 100)<br>         <br>        return Registration(identityKeyPair: identityKeyPair, registrationId: registrationId, preKeys: preKeys, signedPreKeyRecord: signedPreKey)<br>    }</pre><pre>struct Registration {<br>    <br>    init(identityKeyPair: IdentityKeyPair, registrationId: UInt32, preKeys: [PreKeyRecord], signedPreKeyRecord: SignedPreKeyRecord) {<br>        self.identityKeyPair = identityKeyPair<br>        self.registrationId = registrationId<br>        self.preKeys = preKeys<br>        self.signedPreKeyRecord = signedPreKeyRecord<br>    }<br>    <br>    // Mark: - String values are BASE64<br>    init(identityKeyPair: String, registrationId: UInt32, preKeys: [String], signedPreKeyRecord: String) throws {<br>        self.identityKeyPair = try IdentityKeyPair(bytes: identityKeyPair.toUInt8())<br>        self.registrationId = registrationId<br>        self.preKeys = try preKeys.map({ item in<br>            try PreKeyRecord(bytes: item.toUInt8())<br>        })<br>        self.signedPreKeyRecord = try SignedPreKeyRecord(bytes: signedPreKeyRecord.toUInt8())<br>    }<br>    <br>    let identityKeyPair : IdentityKeyPair<br>    let registrationId : UInt32<br>    let preKeys : [PreKeyRecord]<br>    let signedPreKeyRecord : SignedPreKeyRecord<br>    <br>    <br>    public func identityKeyPairBase64() -&gt; String {<br>        return identityKeyPair.serialize().toBase64()<br>    }<br>    <br>    public func identityKeyPublicBase64() -&gt; String {<br>        return identityKeyPair.publicKey.serialize().toBase64()<br>    }<br>    <br>    public func preKeyIdsBase64() -&gt; [String] {<br>        preKeys.map { preKeyRecord in<br>            preKeyRecord.serialize().toBase64()<br>        }<br>    }<br>    <br>    public func signedPreKeyRecordBase64() -&gt; String {<br>        return signedPreKeyRecord.serialize().toBase64()<br>    }<br>    <br>    public func publicIdentityKeyBase64() -&gt; String {<br>        return identityKeyPair.publicKey.serialize().toBase64()<br>    }<br>    <br>    public  func signedPreKeyPublicKeyBase64() -&gt; String {<br>        return signedPreKeyRecord.publicKey.serialize().toBase64()<br>    }<br>    <br>    public func signedPreKeyId() -&gt; UInt32 {<br>        return signedPreKeyRecord.id<br>    }<br>    <br>    public func signedPreKeyRecordSignatureBase64() -&gt; String {<br>        return signedPreKeyRecord.signature.toBase64()<br>    }<br>}</pre><p>We will be sending only the public part of identity key, Preys &amp; signed Prekey to the server and will be storing <em>private</em> + <em>public</em> part in your local storage.</p><pre>let keys = generateKeys()</pre><pre>//Sending Public Keys on server <br>let registrationId = keys.registrationId</pre><pre>let publicIdentityKey = keys.identityKeyPairBase64()<br>let signedPreKeyId<em> = </em>keys.signedPreKeyId()<br>let signedPreKeyPublicKey<em> = </em>keys.signedPreKeyPublicKeyBase64()<br>let <em>signedPreKeyRecordSignature = </em>keys.signedPreKeyRecordSignatureBase64()<br>let preKeys = keys.preKeys.map { preKeyRecord <strong>in</strong></pre><pre>(preKeyRecord.id,preKeyRecord.publicKey.serialize().toBase64())</pre><pre>}</pre><pre><br>//Private Keys needs to store in local storage</pre><pre>let identityKey = keys.identityKeyPairBase64()<br>let registrationId = keys.registrationId<br>let preKeysIds = keys.preKeys.map { preKeyRecord in <br>preKeyRecord.serialize().toBase64()</pre><pre>}<br>let signedPreKeyRecordString<em> = </em>keys.signedPreKeyRecordString</pre><h3>Sending Messages :</h3><p>Before sending messages we need to fetch the public keys of that user. You can ask from your server to sent the public keys of that particular user. Before moving forward we need to setup local user and remote user struct.</p><pre>struct RemoteUser {<br>    <br>    <br>    internal init(preKeyId: UInt32, preKeyPublicKey: PublicKey, signedPreKeyId: UInt32, signedPreKeyPublicKey: PublicKey, signedPreKeySignature: [UInt8], identityKeyPairPublicKey: IdentityKey,deviceId : UInt32, name : String,registrationId : UInt32) throws {<br>        self.preKeyId = preKeyId<br>        self.preKeyPublicKey = preKeyPublicKey<br>        self.signedPreKeyId = signedPreKeyId<br>        self.signedPreKeyPublicKey = signedPreKeyPublicKey<br>        self.signedPreKeySignature = signedPreKeySignature<br>        self.identityKeyPairPublicKey = identityKeyPairPublicKey<br>        self.protocolAddress = try ProtocolAddress(name: name, deviceId: deviceId)<br>        self.registrationId = registrationId<br>    }<br>    <br>    <br>    internal init(preKeyId: UInt32, preKeyPublicKey: [UInt8], signedPreKeyId: UInt32, signedPreKeyPublicKey: [UInt8], signedPreKeySignature: [UInt8], identityKeyPairPublicKey: [UInt8],deviceId : UInt32, name : String,registrationId : UInt32) throws {<br>        self.preKeyId = preKeyId<br>        self.preKeyPublicKey = try PublicKey(preKeyPublicKey)<br>        self.signedPreKeyId = signedPreKeyId<br>        self.signedPreKeyPublicKey = try PublicKey(signedPreKeyPublicKey)<br>        self.signedPreKeySignature = signedPreKeySignature<br>        self.identityKeyPairPublicKey = IdentityKey(publicKey: try PublicKey(identityKeyPairPublicKey))<br>        self.protocolAddress = try ProtocolAddress(name: name, deviceId: deviceId)<br>        self.registrationId = registrationId<br>        <br>    }</pre><pre>let preKeyId : UInt32<br>    let preKeyPublicKey : PublicKey<br>    let signedPreKeyId : UInt32<br>    let signedPreKeyPublicKey : PublicKey<br>    let signedPreKeySignature : [UInt8]<br>    let identityKeyPairPublicKey : IdentityKey<br>    let protocolAddress : ProtocolAddress<br>    let registrationId : UInt32<br>}</pre><pre>struct LocalUser {<br>    let identitykey : IdentityKeyPair<br>    let registrationId : UInt32<br>    let preKeys : [PreKeyRecord]<br>    let signedPreKey : SignedPreKeyRecord<br>    let address : ProtocolAddress<br>    <br>    public init(identitykey: IdentityKeyPair,<br>                  registrationId: UInt32,<br>                  preKeys: [PreKeyRecord],<br>                  signedPreKey: SignedPreKeyRecord,<br>                  deviceId : UInt32, // pass static deviceId from KeyHelper<br>                  name : String // pass user Id<br>    ) throws {<br>        self.identitykey = identitykey<br>        self.registrationId = registrationId<br>        self.preKeys = preKeys<br>        self.signedPreKey = signedPreKey<br>        self.address = try ProtocolAddress(name: name, deviceId: deviceId)<br>    }<br>    <br>    public init(identitykey: [UInt8],<br>                  registrationId: UInt32,<br>                  preKeys: [[UInt8]],<br>                  signedPreKey: [UInt8],<br>                  deviceId : UInt32, // pass static deviceId from KeyHelper<br>                  name : String // pass user Id<br>                  ) throws {<br>        self.identitykey = try IdentityKeyPair(bytes: identitykey)<br>        self.registrationId = registrationId<br>        self.preKeys = try preKeys.map({ bytes in<br>            try PreKeyRecord(bytes: bytes)<br>        })<br>        self.signedPreKey = try SignedPreKeyRecord(bytes: signedPreKey)<br>        self.address = try ProtocolAddress(name: name, deviceId: deviceId)<br>    }<br>}</pre><p>After you have done fetching your local user’s private keys and remote user’s public key then we are good to go for encryption messaging.</p><pre>let session = try EncryptedSession(localUser: localUser, remoteUser: remoteUser)</pre><p>Before Making an instance of EncryptedSession we need to setup <strong>EncryptedSession</strong> class</p><pre>class EncryptedSession {<br>    <br>    final let localUser : LocalUser<br>    final let remoteUser : RemoteUser?<br>    final let remoteUserProtocolAddress : ProtocolAddress<br>    <br>    private final let protocolStore : InMemorySignalProtocolStore<br>    <br>    init(localUser : LocalUser, remoteUser : RemoteUser) throws {<br>        self.localUser = localUser<br>        self.remoteUser = remoteUser<br>        self.remoteUserProtocolAddress = remoteUser.protocolAddress<br>        self.protocolStore = InMemorySignalProtocolStore(identity: localUser.identitykey, registrationId: localUser.registrationId)<br>        try initProtocolStore()<br>    }<br>    <br>    init(localUser : LocalUser,remoteUserProtocolAddress : ProtocolAddress) throws {<br>        remoteUser = nil<br>        self.localUser = localUser<br>        self.remoteUserProtocolAddress = remoteUserProtocolAddress<br>        self.protocolStore = InMemorySignalProtocolStore(identity: localUser.identitykey, registrationId: localUser.registrationId)<br>        try initProtocolStore()<br>    }<br>    <br>    <br>    public func encrypt(message : String) throws -&gt; String {<br>       let buf = [UInt8](message.utf8)<br>       let cipherTextMessage =  try signalEncrypt(message: buf, for: remoteUserProtocolAddress, sessionStore: protocolStore, identityStore: protocolStore, context: NullContext())<br>        let preSignalMessage = try PreKeySignalMessage(bytes: cipherTextMessage.serialize())<br>        return try preSignalMessage.serialize().toBase64()<br>    }<br>    <br>    public func decrypt(message : String) throws -&gt; String? {<br>        let bytes = try signalDecryptPreKey(message: PreKeySignalMessage(bytes: message.toUInt8()), from: remoteUserProtocolAddress, sessionStore: protocolStore, identityStore: protocolStore, preKeyStore: protocolStore, signedPreKeyStore: protocolStore, context: NullContext())<br>        <br>        return String(bytes: bytes, encoding: String.Encoding.utf8)<br>    }<br>    <br>    private func initProtocolStore() throws {<br>        <br>        for preKey in localUser.preKeys {<br>            try protocolStore.storePreKey(preKey, id: preKey.id, context: NullContext())<br>        }<br>        <br>        try protocolStore.storeSignedPreKey(localUser.signedPreKey, id: localUser.signedPreKey.id, context: NullContext())<br>        <br>        if let remoteUser = self.remoteUser {<br>            <br>            let preKeyBundle = try PreKeyBundle(registrationId: remoteUser.registrationId, deviceId: remoteUser.protocolAddress.deviceId, prekeyId: remoteUser.preKeyId, prekey: remoteUser.preKeyPublicKey, signedPrekeyId: remoteUser.signedPreKeyId, signedPrekey: remoteUser.signedPreKeyPublicKey, signedPrekeySignature: remoteUser.signedPreKeySignature, identity: remoteUser.identityKeyPairPublicKey)<br>            <br>            <br>            try processPreKeyBundle(preKeyBundle, for: remoteUser.protocolAddress, sessionStore: protocolStore, identityStore: protocolStore, context: NullContext())<br>            <br>        }<br>    }<br>}</pre><pre>enum Operation {<br>    case encrypt, decrypt<br>}</pre><p>When you have done setting up <strong>EncryptedSession</strong> class and instance of that class, simply call</p><pre>let message = try session.encrypt(message: &quot;Hello From IOS!&quot;)</pre><p>and sent the encrypted message to the server. Make sure to cache orginal message as it no way to decrypt our own message. When you received success response from server compare the message Id(temp Id) and update the other properties of message object except original(unencrypted message).</p><p>Similarly when you want to decrypt the encrypted message you just need to call <strong>session.decrypt </strong>on recipient device.</p><pre>let message = try session.decrypt(message: message_here!)</pre><h3>Decrypt Messaging From Notification :</h3><p>When you want to decrypt message from notification or when you don’t have other user’s public keys. Simply pass <strong>nil </strong>while making <strong>EncryptedSession </strong>class instance. Then do the decryption functionality.</p><pre>let session = try EncryptedSession(localUser: localUser, remoteUser: nil)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edb02d11268d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Signal Protocol End to End Group Chat Implementation In Android]]></title>
            <link>https://medium.com/@ahmedcs1995/signal-protocol-end-to-end-group-chat-implementation-in-android-e4e77c79e698?source=rss-1fb3aebd8d62------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4e77c79e698</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-apps]]></category>
            <category><![CDATA[android-developers]]></category>
            <dc:creator><![CDATA[Muhammad Ahmed]]></dc:creator>
            <pubDate>Sun, 12 Sep 2021 11:11:03 GMT</pubDate>
            <atom:updated>2022-12-16T00:32:37.989Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LORbFCuRavyRRLLkSkV7oQ.jpeg" /></figure><p>I had been working on a chat app having end-end encryption. At that time I didn’t find any article, demo code, and documentation so that I can integrate signal protocol in my App.</p><p>In this article, we will be only discussing Implementation Protocol and how to use Signal library functions. If you want to know more further about library functions and system architecture you can read their blog</p><p><a href="https://signal.org/blog/private-groups/">Private Group Messaging</a></p><p>So Let’s get started. First, you have to add a signal protocol library to your build.gralde(app-level) file</p><pre>implementation &#39;org.whispersystems:signal-protocol-android:2.2.0&#39;</pre><p>We have multiple users in the group and each user has a sender key. The sender will be generated while creating a group (in the case of admin) or when participants have successfully been added to the group. I will show via source code so don’t worry if you don’t get my point.</p><p>Before start working on group chat. We have to generate identityKeyPair, preKey &amp; signedPreKey at the install time so let’s generate that.</p><pre>public static RegistrationKeyModel generateKeys() throws InvalidKeyException, IOException {<br>    IdentityKeyPair identityKeyPair = KeyHelper.<em>generateIdentityKeyPair</em>();<br>    int registrationId = KeyHelper.<em>generateRegistrationId</em>(false);<br>    SignedPreKeyRecord signedPreKey = KeyHelper.<em>generateSignedPreKey</em>(identityKeyPair,new Random().nextInt(Medium.<em>MAX_VALUE </em>- 1));<br>    List&lt;PreKeyRecord&gt; preKeys = KeyHelper.<em>generatePreKeys</em>(new Random().nextInt(Medium.<em>MAX_VALUE </em>- 101), 100);<br>    return new RegistrationKeyModel(<br>            identityKeyPair,<br>            registrationId,<br>            preKeys,<br>            signedPreKey<br>    );<br>}</pre><pre>public class RegistrationKeyModel {<br>    IdentityKeyPair identityKeyPair;<br>    int registrationId;<br>    List&lt;PreKeyRecord&gt; preKeys;<br>    SignedPreKeyRecord signedPreKeyRecord;<br><br>    public RegistrationKeyModel(IdentityKeyPair identityKeyPair, int registrationId, List&lt;PreKeyRecord&gt; preKeys, SignedPreKeyRecord signedPreKeyRecord) {<br>        this.identityKeyPair = identityKeyPair;<br>        this.registrationId = registrationId;<br>        this.preKeys = preKeys;<br>        this.signedPreKeyRecord = signedPreKeyRecord;<br>    }<br><br>    public RegistrationKeyModel(String identityKeyPair, int registrationId, String[] preKeys, String signedPreKeyRecord) throws InvalidKeyException, IOException {<br>        this.identityKeyPair = new IdentityKeyPair(KeyUtils.<em>decodeToByteArray</em>(identityKeyPair));<br>        this.registrationId = registrationId;<br>        List&lt;PreKeyRecord&gt; preKeyRecords = new ArrayList&lt;&gt;();<br>        for(String item : preKeys) {<br>            preKeyRecords.add(new PreKeyRecord(KeyUtils.<em>decodeToByteArray</em>(item)));<br>        }<br>        this.preKeys = preKeyRecords;<br>        this.signedPreKeyRecord = new SignedPreKeyRecord(KeyUtils.<em>decodeToByteArray</em>(signedPreKeyRecord));<br>    }<br><br>    public IdentityKeyPair getIdentityKeyPair() {<br>        return identityKeyPair;<br>    }<br><br>    public String getIdentityKeyPairString() {<br>        return KeyUtils.<em>encodeToBase64</em>(identityKeyPair.serialize());<br>    }<br><br>    public String getIdentityKeyPublicString() {<br>        return KeyUtils.<em>encodeToBase64</em>(identityKeyPair.getPublicKey().serialize());<br>    }<br><br>    public void setIdentityKeyPair(IdentityKeyPair identityKey) {<br>        this.identityKeyPair = identityKey;<br>    }<br><br>    public int getRegistrationId() {<br>        return registrationId;<br>    }<br><br>    public void setRegistrationId(int registrationId) {<br>        this.registrationId = registrationId;<br>    }<br><br>    public List&lt;PreKeyRecord&gt; getPreKeys() {<br>        return preKeys;<br>    }<br><br>    public String getPreKeyIds() {<br>        List&lt;String&gt; preKeyList = new ArrayList&lt;&gt;();<br>        for (PreKeyRecord preKey : preKeys) {<br>            preKeyList.add(KeyUtils.<em>encodeToBase64</em>(preKey.serialize()));<br>        }<br>        return new Gson().toJson(preKeyList);<br>    }<br><br>    public SignedPreKeyRecord getSignedPreKeyRecord() {<br>        return signedPreKeyRecord;<br>    }<br><br>    public String getSignedPreKeyRecordString() {<br>        return KeyUtils.<em>encodeToBase64</em>(signedPreKeyRecord.serialize());<br>    }<br><br>    public void setSignedPreKeyRecord(SignedPreKeyRecord signedPreKeyRecord) {<br>        this.signedPreKeyRecord = signedPreKeyRecord;<br>    }<br><br>    public String getPublicIdentityKey() {<br>        return KeyUtils.<em>encodeToBase64</em>(identityKeyPair.getPublicKey().serialize());<br>    }<br><br>    public String getSignedPreKeyPublicKey() {<br>        return KeyUtils.<em>encodeToBase64</em>(signedPreKeyRecord.getKeyPair().getPublicKey().serialize());<br>    }<br><br>    public int getSignedPreKeyId() {<br>        return signedPreKeyRecord.getId();<br>    }<br><br>    public String getSignedPreKeyRecordSignature() {<br>        return KeyUtils.<em>encodeToBase64</em>(signedPreKeyRecord.getSignature());<br>    }<br>}</pre><pre>public static String encodeToBase64(byte[] value) {<br>    return Base64.<em>encodeToString</em>(value, Base64.<em>NO_WRAP</em>);<br>}<br><br>public static byte[] decodeToByteArray(String base64) {<br>    return Base64.<em>decode</em>(base64, Base64.<em>NO_WRAP</em>);<br>}</pre><p>When you have done generating the required keys. Store those keys in Shared Pref or SQLite Database. Let’s make a new Group.</p><p>Suppose we have four users Alice, Bob, Charlie, David. Alice is about to create the group.</p><p>Before calling create Group API. We will generate SenderKeyDistributionMessage(sender Key) and SenderKeyRecord.</p><pre>public static Pair&lt;String, String&gt; createGroup(EncryptedLocalUser localUser, String groupName) {<br>    return <em>createDistributionKey</em>(localUser, groupName);<br>}</pre><pre>public static Pair&lt;String, String&gt; createDistributionKey(EncryptedLocalUser localUser, String groupName) {<br>    SignalProtocolAddress address = localUser.getSignalProtocolAddress();<br><br>    InMemorySignalProtocolStore store = new InMemorySignalProtocolStore(localUser.getIdentityKeyPair(), localUser.getRegistrationId());<br>    store.storeSignedPreKey(localUser.getSignedPreKey().getId(), localUser.getSignedPreKey());<br><br>    for (PreKeyRecord record : localUser.getPreKeys()) {<br>        store.storePreKey(record.getId(), record);<br>    }<br><br><br>    InMemorySenderKeyStore senderStore = new InMemorySenderKeyStore();<br>    GroupSessionBuilder sessionBuilder = new GroupSessionBuilder(senderStore);<br><br><br>    SenderKeyName senderKeyName = new SenderKeyName(groupName, address);<br>    SenderKeyDistributionMessage senderDistributionMessage = sessionBuilder.create(senderKeyName);<br>    SenderKeyRecord senderKeyRecord = senderStore.loadSenderKey(senderKeyName);<br><br><br>    return new Pair&lt;&gt;(<br>            KeyUtils.<em>encodeToBase64</em>(senderDistributionMessage.serialize()),<br>            KeyUtils.<em>encodeToBase64</em>(senderKeyRecord.serialize())<br>    );<br>}</pre><pre>public class EncryptedLocalUser extends BaseEncryptedEntity {<br><br>    private final IdentityKeyPair identityKeyPair;<br>    private final List&lt;PreKeyRecord&gt; preKey;<br>    private final SignedPreKeyRecord signedPreKey;<br><br>    public EncryptedLocalUser(byte[] identityKeyPair,<br>                              int registrationId,<br>                              String name,<br>                              int deviceId,<br>                              List&lt;byte[]&gt; preKeys,<br>                              byte[] signedPreKey) throws InvalidKeyException, IOException {<br>        super(registrationId, new SignalProtocolAddress(name, deviceId));<br>        this.identityKeyPair = new IdentityKeyPair(identityKeyPair);<br>        preKey = new ArrayList&lt;&gt;();<br>        for (byte[] item : preKeys) {<br>            preKey.add(new PreKeyRecord(item));<br>        }<br>        this.signedPreKey = new SignedPreKeyRecord(signedPreKey);<br>    }<br><br><br>    public static PreKeyRecord toPreKeyRecord(byte[] bytes) throws IOException {<br>        return new PreKeyRecord(bytes);<br>    }<br><br>    public IdentityKeyPair getIdentityKeyPair() {<br>        return identityKeyPair;<br>    }<br><br>    public List&lt;PreKeyRecord&gt; getPreKeys() {<br>        return preKey;<br>    }<br><br>    public SignedPreKeyRecord getSignedPreKey() {<br>        return signedPreKey;<br>    }<br>}</pre><p>You can set <strong>DEVICE_ID</strong> static</p><p>public static final int DEFAULT_DEVICE_ID = 2;</p><pre>public class InMemorySenderKeyStore implements SenderKeyStore {<br><br>  private final Map&lt;SenderKeyName, SenderKeyRecord&gt; store = new HashMap&lt;&gt;();<br><br>  @Override<br>  public void storeSenderKey(SenderKeyName senderKeyName, SenderKeyRecord record) {<br>    store.put(senderKeyName, record);<br>  }<br><br>  @Override<br>  public SenderKeyRecord loadSenderKey(SenderKeyName senderKeyName) {<br>    try {<br>      SenderKeyRecord record = store.get(senderKeyName);<br><br>      if (record == null) {<br>        return new SenderKeyRecord();<br>      } else {<br>        return new SenderKeyRecord(record.serialize());<br>      }<br>    } catch (IOException e) {<br>      throw new AssertionError(e);<br>    }<br>  }<br><br>  public void removeSenderKey(SenderKeyName senderKeyName) {<br>    store.remove(senderKeyName);<br>  }<br>}</pre><p>When you have done generating <strong><em>SenderKeyDistributionMessage</em></strong> and <strong><em>SenderKeyRecord</em></strong>. Send the <strong><em>SenderKeyDistributionMessage</em></strong> to API. and save <strong><em>SenderKeyRecord</em></strong> in your local database.</p><p>When participants Receive notifications or they enter first time in a chat room they send their <strong><em>SenderKeyDistributionMessage </em></strong>to API.</p><p>use the <strong>createDistributionKey </strong>static function to generate keys and send the keys to the API &amp; store <strong>SenderKeyRecord</strong> in your local Database. So now every member has its sender Key.</p><p>Before starting encrypting and decrypting messages. You first have to create an encrypted session.</p><pre>public class SenderKeyDistributionModel {<br>    final String id;<br>    final String senderKeyDistributionMessage;<br><br>    public SenderKeyDistributionModel(String name, String senderKeyDistributionMessage) {<br>        this.id = name;<br>        this.senderKeyDistributionMessage = senderKeyDistributionMessage;<br>    }<br>}</pre><pre>public class ContactsModel {<br>    private final String id;<br><br>    public ContactsModel(String id) {<br>        this.id = id;<br>    }<br><br>    public String getId() {<br>        return id;<br>    }<br>}</pre><pre>public class EncryptedGroupClient {<br><br>    private final SignalProtocolAddress address;<br><br>    private final InMemorySenderKeyStore senderStore;<br>    private final GroupSessionBuilder sessionBuilder;<br><br>    private final Map&lt;String, GroupCipher&gt; decryptGroupCiphers;<br>    private final Map&lt;String, String&gt; senderKeyDistributionStore;<br>    private GroupCipher encryptGroupCipher;<br><br>    //Group Info<br>    private final List&lt;ContactsModel&gt; members;<br>    private final String groupName;<br><br>    public EncryptedGroupClient(EncryptedLocalUser localUser, String senderKeyRecord, String groupName, List&lt;ContactsModel&gt; contacts) throws IOException {<br>        this.address = localUser.getSignalProtocolAddress();<br>        this.members = contacts;<br>        this.groupName = groupName;<br><br><br>        senderStore = new InMemorySenderKeyStore();<br>        sessionBuilder = new GroupSessionBuilder(senderStore);<br>        decryptGroupCiphers = new HashMap&lt;&gt;();<br><br>        Timber.<em>e</em>(&quot;senderKeyRecord -&gt; &quot; + senderKeyRecord);<br>        if (senderKeyRecord != null &amp;&amp; !senderKeyRecord.isEmpty())<br>            senderStore.storeSenderKey(new SenderKeyName(groupName, this.address), new SenderKeyRecord(KeyUtils.<em>decodeToByteArray</em>(senderKeyRecord)));<br><br>        senderKeyDistributionStore = new HashMap&lt;&gt;();<br>    }<br><br>    public String getKeyRecord() {<br>        SenderKeyName senderKeyName = new SenderKeyName(this.groupName,this.address);<br>        return KeyUtils.<em>encodeToBase64</em>(senderStore.loadSenderKey(senderKeyName).serialize());<br>    }<br><br>    private void addDecryptGroupCiphers(String groupName, List&lt;SenderKeyDistributionModel&gt; keys) throws InvalidMessageException, LegacyMessageException {<br>        for (SenderKeyDistributionModel item : keys) {<br>            byte[] serializedSenderDistributionKey = KeyUtils.<em>decodeToByteArray</em>(item.senderKeyDistributionMessage);<br>            SenderKeyDistributionMessage senderKeyDistributionMessage = new SenderKeyDistributionMessage(serializedSenderDistributionKey);<br><br>            SignalProtocolAddress groupInitiator = null;<br><br>            for (ContactsModel contact : members) {<br>                if (Objects.<em>equals</em>(contact.getId(), item.id)) {<br>                    groupInitiator = new SignalProtocolAddress(item.id, KeyUtils.<em>DEFAULT_DEVICE_ID</em>);<br>                }<br>            }<br><br>            SenderKeyName senderKeyName = new SenderKeyName(groupName, groupInitiator);<br><br>            if (!decryptGroupCiphers.containsKey(item.id) || !Objects.<em>equals</em>(senderKeyDistributionStore.get(item.id), item.senderKeyDistributionMessage)) {<br><br>                senderStore.removeSenderKey(senderKeyName);<br>                senderKeyDistributionStore.remove(item.id);<br>                decryptGroupCiphers.remove(item.id);<br><br>                //Start the session for reading group originator<br>                sessionBuilder.process(senderKeyName, senderKeyDistributionMessage);<br><br>                //Save the decryption group cipher for that contact<br>                senderKeyDistributionStore.put(item.id, item.senderKeyDistributionMessage);<br>                decryptGroupCiphers.put(item.id, new GroupCipher(senderStore, senderKeyName));<br>            }<br>        }<br>    }<br><br>    public void createSession(List&lt;SenderKeyDistributionModel&gt; keys) throws InvalidMessageException, LegacyMessageException {<br>        addDecryptGroupCiphers(groupName, keys);<br>        if (encryptGroupCipher == null) {<br>            encryptGroupCipher = new GroupCipher(senderStore, new SenderKeyName(groupName, this.address));<br>        }<br>    }<br><br><br>    public String encryptMessage(String message) {<br>        try {<br>            byte[] encryptedMessage = encryptGroupCipher.encrypt(message.getBytes(StandardCharsets.<em>UTF_8</em>));<br>            Timber.<em>e</em>(this.address.getName() + &quot; -&gt; GROUP: &quot; + message);<br>            return KeyUtils.<em>encodeToBase64</em>(encryptedMessage);<br>        } catch (NoSessionException e) {<br>            e.printStackTrace();<br>        }<br>        return null;<br>    }<br><br>    public String decryptMessage(String encryptedMessage, String userId) {<br>        GroupCipher decryptGroupCipher = decryptGroupCiphers.get(userId);<br>        try {<br>            byte[] text = Objects.<em>requireNonNull</em>(decryptGroupCipher).decrypt(KeyUtils.<em>decodeToByteArray</em>(encryptedMessage));<br>            return new String(text, StandardCharsets.<em>UTF_8</em>);<br>        } catch (LegacyMessageException | DuplicateMessageException | InvalidMessageException | NoSessionException e) {<br>            return e.getMessage();<br>        }<br>    }<br><br>    public String decryptMessage(String encryptedMessage, String userId, String senderKey) {<br>        try {<br>            Timber.<em>e</em>(&quot;senderKey -&gt; &quot; + senderKey);<br>            Timber.<em>e</em>(&quot;userId -&gt; &quot; + userId);<br>            List&lt;SenderKeyDistributionModel&gt; mList = new ArrayList&lt;&gt;();<br>            mList.add(new SenderKeyDistributionModel(userId, senderKey));<br>            addDecryptGroupCiphers(this.groupName, mList);<br>            return decryptMessage(encryptedMessage, userId);<br>        } catch (LegacyMessageException | InvalidMessageException | NullPointerException e) {<br>            return e.getMessage();<br>        }<br>    }<br>}</pre><pre>val localUser = EncryptedLocalUser(.......)<br>client = EncryptedGroupClient(<br>    localUser,<br>    senderKeyRecord, // your saved sender Key Record corresponding to this group<br>    groupName, // group name from API<br>    users.<em>filter </em><strong>{ it</strong>.userId._id != MyUserId<strong>}</strong>.<em>map </em><strong>{ </strong>ContactsModel(<strong>it</strong>.userId._id) <strong>}<br></strong>)<br><br>client.createSession(<br>     users.<em>filter </em><strong>{ it</strong>.senderKey != null &amp;&amp; <strong>it</strong>.userId._id != MyUserId<strong>}</strong>.<em>map </em><strong>{<br>        </strong>SenderKeyDistributionModel(<strong>it</strong>.userId._id, <strong>it</strong>.senderKey)<br>    <strong>}<br></strong>)</pre><h3><strong>Encrypting the message:</strong></h3><pre>val message = client.encryptMessage(editTextMessage)</pre><h3><strong>Decrypting the message:</strong></h3><pre>val message = client.decryptMessage(<br>    message, // sender Message<br>    userId, //sender User Id<br>    user.senderKey // sender (SenderKey)<br>)</pre><p><strong>Note: </strong>You can’t decrypt your own message. So we have to store our raw message in SQLite Database and update properties(except message property) of that message object.</p><p>That’s it we have successfully integrated group chat End-End Encryption.</p><p><strong><em>Android Sample Code</em></strong></p><p><a href="https://github.com/ahmedcs2600/SignalProtocolExampleAndroid">https://github.com/ahmedcs2600/SignalProtocolExampleAndroid</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4e77c79e698" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Signal Protocol Implementation in Android]]></title>
            <link>https://medium.com/@ahmedcs1995/signal-protocol-implementation-in-android-70940c25c339?source=rss-1fb3aebd8d62------2</link>
            <guid isPermaLink="false">https://medium.com/p/70940c25c339</guid>
            <category><![CDATA[encryption]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[signal]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[chat]]></category>
            <dc:creator><![CDATA[Muhammad Ahmed]]></dc:creator>
            <pubDate>Sun, 05 Sep 2021 16:57:07 GMT</pubDate>
            <atom:updated>2022-12-16T00:26:23.063Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*mijaX0NkttR-cYyaOEpplQ.png" /></figure><p>I have been working on end-end encryption using the Signal protocol. By that time I was working, I couldn’t find an example of how to integrate Signal Protocol(end-end encryption) on Android.</p><p>For understanding the Logic and algorithm of signal protocol you can check out their documentation page because here we will be using their Library/SDK.<br><a href="https://signal.org/docs/">https://signal.org/docs/</a></p><p>We will be using their java protocol available on GitHub. So let&#39;s start implementing end-end encryption in Android.<br><a href="https://github.com/signalapp/libsignal-protocol-java">https://github.com/signalapp/libsignal-protocol-java</a></p><p>In build.gradle(app-level)</p><pre>implementation &#39;org.whispersystems:signal-protocol-android:2.2.0&#39;</pre><h3><strong>Keys Registration At Install Time :</strong></h3><p>At the install time, We need to generate IdentityKeyPair, registrationId, SignedPreKeyRecord &amp; SignedPreKeyRecord.</p><pre>public static RegistrationKeyModel generateKeys() throws InvalidKeyException, IOException {<br>    IdentityKeyPair identityKeyPair = KeyHelper.<em>generateIdentityKeyPair</em>();<br>    int registrationId = KeyHelper.<em>generateRegistrationId</em>(false);<br>    SignedPreKeyRecord signedPreKey = KeyHelper.<em>generateSignedPreKey</em>(identityKeyPair,new Random().nextInt(Medium.<em>MAX_VALUE </em>- 1));<br>    List&lt;PreKeyRecord&gt; preKeys = KeyHelper.<em>generatePreKeys</em>(new Random().nextInt(Medium.<em>MAX_VALUE </em>- 101), 100);<br>    return new RegistrationKeyModel(<br>            identityKeyPair,<br>            registrationId,<br>            preKeys,<br>            signedPreKey<br>    );<br>}</pre><pre>public class RegistrationKeyModel {<br>    IdentityKeyPair identityKeyPair;<br>    int registrationId;<br>    List&lt;PreKeyRecord&gt; preKeys;<br>    SignedPreKeyRecord signedPreKeyRecord;<br><br>    public RegistrationKeyModel(IdentityKeyPair identityKeyPair, int registrationId, List&lt;PreKeyRecord&gt; preKeys, SignedPreKeyRecord signedPreKeyRecord) {<br>        this.identityKeyPair = identityKeyPair;<br>        this.registrationId = registrationId;<br>        this.preKeys = preKeys;<br>        this.signedPreKeyRecord = signedPreKeyRecord;<br>    }<br><br>    public RegistrationKeyModel(String identityKeyPair, int registrationId, String[] preKeys, String signedPreKeyRecord) throws InvalidKeyException, IOException {<br>        this.identityKeyPair = new IdentityKeyPair(KeyUtils.<em>decodeToByteArray</em>(identityKeyPair));<br>        this.registrationId = registrationId;<br>        List&lt;PreKeyRecord&gt; preKeyRecords = new ArrayList&lt;&gt;();<br>        for(String item : preKeys) {<br>            preKeyRecords.add(new PreKeyRecord(KeyUtils.<em>decodeToByteArray</em>(item)));<br>        }<br>        this.preKeys = preKeyRecords;<br>        this.signedPreKeyRecord = new SignedPreKeyRecord(KeyUtils.<em>decodeToByteArray</em>(signedPreKeyRecord));<br>    }<br><br>    public IdentityKeyPair getIdentityKeyPair() {<br>        return identityKeyPair;<br>    }<br><br>    public String getIdentityKeyPairString() {<br>        return KeyUtils.<em>encodeToBase64</em>(identityKeyPair.serialize());<br>    }<br><br>    public String getIdentityKeyPublicString() {<br>        return KeyUtils.<em>encodeToBase64</em>(identityKeyPair.getPublicKey().serialize());<br>    }<br><br>    public void setIdentityKeyPair(IdentityKeyPair identityKey) {<br>        this.identityKeyPair = identityKey;<br>    }<br><br>    public int getRegistrationId() {<br>        return registrationId;<br>    }<br><br>    public void setRegistrationId(int registrationId) {<br>        this.registrationId = registrationId;<br>    }<br><br>    public List&lt;PreKeyRecord&gt; getPreKeys() {<br>        return preKeys;<br>    }<br><br>    public String getPreKeyIds() {<br>        List&lt;String&gt; preKeyList = new ArrayList&lt;&gt;();<br>        for (PreKeyRecord preKey : preKeys) {<br>            preKeyList.add(KeyUtils.<em>encodeToBase64</em>(preKey.serialize()));<br>        }<br>        return new Gson().toJson(preKeyList);<br>    }<br><br>    public SignedPreKeyRecord getSignedPreKeyRecord() {<br>        return signedPreKeyRecord;<br>    }<br><br>    public String getSignedPreKeyRecordString() {<br>        return KeyUtils.<em>encodeToBase64</em>(signedPreKeyRecord.serialize());<br>    }<br><br>    public void setSignedPreKeyRecord(SignedPreKeyRecord signedPreKeyRecord) {<br>        this.signedPreKeyRecord = signedPreKeyRecord;<br>    }<br><br>    public String getPublicIdentityKey() {<br>        return KeyUtils.<em>encodeToBase64</em>(identityKeyPair.getPublicKey().serialize());<br>    }<br><br>    public String getSignedPreKeyPublicKey() {<br>        return KeyUtils.<em>encodeToBase64</em>(signedPreKeyRecord.getKeyPair().getPublicKey().serialize());<br>    }<br><br>    public int getSignedPreKeyId() {<br>        return signedPreKeyRecord.getId();<br>    }<br><br>    public String getSignedPreKeyRecordSignature() {<br>        return KeyUtils.<em>encodeToBase64</em>(signedPreKeyRecord.getSignature());<br>    }<br>}</pre><p>When we have successfully generated identity keys, registration id, and prekeys, and signedPreKeyRecord we need to transmit the public part on our server &amp; save it in our local storage (Shared Preferences or Database).</p><p>We have all those public keys computed in our <strong>RegistrationKeyModel. </strong>So we just need to call their getter function and sent public keys(in my case I have converted keys into base64, you can send directly in byte[]).</p><pre>public String getIdentityKeyPairString() {<br>    return KeyUtils.<em>encodeToBase64</em>(identityKeyPair.serialize());<br>}</pre><pre>public String getPreKeyIds() {<br>    List&lt;String&gt; preKeyList = new ArrayList&lt;&gt;();<br>    for (PreKeyRecord preKey : preKeys) {<br>        preKeyList.add(KeyUtils.<em>encodeToBase64</em>(preKey.serialize()));<br>    }<br>    return new Gson().toJson(preKeyList);<br>}</pre><pre>public int getRegistrationId() {<br>    return registrationId;<br>}</pre><pre>public String getSignedPreKeyRecordString() {<br>    return KeyUtils.<em>encodeToBase64</em>(signedPreKeyRecord.serialize());<br>}</pre><h3>Building a Session :-</h3><p>Before you encrypt the message and send it, You have to build a session for that you need to get the public keys of that user by asking your server.</p><p>The server will send you the following things</p><p>1- Registration Id<br>2- userId/Name<br>3- random preKey <br>4- Signed PreKey (Id, public Key, signature)<br>5- identity Public Key.</p><p>You can set <strong>DEVICE_ID</strong> static</p><blockquote><em>public static final int DEFAULT_DEVICE_ID = 2;</em></blockquote><p>Before making an encrypted session we need to set up local user and remote user classes.</p><pre>import org.whispersystems.libsignal.SignalProtocolAddress;<br><br>public abstract class BaseEncryptedEntity {<br>    protected final int registrationId;<br>    protected final SignalProtocolAddress address;<br><br>    protected BaseEncryptedEntity(int registrationId, SignalProtocolAddress address) {<br>        this.registrationId = registrationId;<br>        this.address = address;<br>    }<br><br>    public int getRegistrationId() {<br>        return registrationId;<br>    }<br><br>    public SignalProtocolAddress getSignalProtocolAddress() {<br>        return address;<br>    }<br>}</pre><pre>public class EncryptedLocalUser extends BaseEncryptedEntity {<br><br>    private final IdentityKeyPair identityKeyPair;<br>    private final List&lt;PreKeyRecord&gt; preKey;<br>    private final SignedPreKeyRecord signedPreKey;<br><br>    public EncryptedLocalUser(byte[] identityKeyPair,<br>                              int registrationId,<br>                              String name,<br>                              int deviceId,<br>                              List&lt;byte[]&gt; preKeys,<br>                              byte[] signedPreKey) throws InvalidKeyException, IOException {<br>        super(registrationId, new SignalProtocolAddress(name, deviceId));<br>        this.identityKeyPair = new IdentityKeyPair(identityKeyPair);<br>        preKey = new ArrayList&lt;&gt;();<br>        for (byte[] item : preKeys) {<br>            preKey.add(new PreKeyRecord(item));<br>        }<br>        this.signedPreKey = new SignedPreKeyRecord(signedPreKey);<br>    }<br><br><br>    public static PreKeyRecord toPreKeyRecord(byte[] bytes) throws IOException {<br>        return new PreKeyRecord(bytes);<br>    }<br><br>    public IdentityKeyPair getIdentityKeyPair() {<br>        return identityKeyPair;<br>    }<br><br>    public List&lt;PreKeyRecord&gt; getPreKeys() {<br>        return preKey;<br>    }<br><br>    public SignedPreKeyRecord getSignedPreKey() {<br>        return signedPreKey;<br>    }<br>}</pre><pre>public class EncryptedRemoteUser extends BaseEncryptedEntity {<br><br>    private final int preKeyId;<br>    private final ECPublicKey preKeyPublicKey;<br><br>    private final int signedPreKeyId;<br>    private final ECPublicKey signedPreKeyPublicKey;<br><br>    private final byte[] signedPreKeySignature;<br>    private final IdentityKey identityKeyPairPublicKey;<br><br><br>    public EncryptedRemoteUser(<br>            int registrationId,<br>            String name,<br>            int deviceId,<br>            int preKeyId,<br>            byte[] preKeyPublicKey,<br>            int signedPreKeyId,<br>            byte[] signedPreKeyPublicKey,<br>            byte[] signedPreKeySignature,<br>            byte[] identityKeyPairPublicKey) throws InvalidKeyException {<br><br>        super(registrationId, new SignalProtocolAddress(name, deviceId));<br>        this.preKeyId = preKeyId;<br>        this.preKeyPublicKey = Curve.<em>decodePoint</em>(preKeyPublicKey, 0);<br>        this.signedPreKeyId = signedPreKeyId;<br>        this.signedPreKeyPublicKey = Curve.<em>decodePoint</em>(signedPreKeyPublicKey, 0);<br>        this.signedPreKeySignature = signedPreKeySignature;<br>        this.identityKeyPairPublicKey = new IdentityKey(identityKeyPairPublicKey, 0);<br>    }<br><br>    public int getPreKeyId() {<br>        return preKeyId;<br>    }<br><br>    public ECPublicKey getPreKeyPublicKey() {<br>        return preKeyPublicKey;<br>    }<br><br>    public int getSignedPreKeyId() {<br>        return signedPreKeyId;<br>    }<br><br>    public ECPublicKey getSignedPreKeyPublicKey() {<br>        return signedPreKeyPublicKey;<br>    }<br><br>    public byte[] getSignedPreKeySignature() {<br>        return signedPreKeySignature;<br>    }<br><br>    public IdentityKey getIdentityKeyPairPublicKey() {<br>        return identityKeyPairPublicKey;<br>    }<br>}</pre><p>Before performing encryption and decryption we need to make a PreKey bundle and pass the PreKey bundle to the session object.</p><pre>SessionBuilder sessionBuilder = new SessionBuilder(protocolStore, remoteUser.getSignalProtocolAddress());<br>PreKeyBundle preKeyBundle = new PreKeyBundle(<br>        remoteUser.getRegistrationId(),<br>        remoteUser.getSignalProtocolAddress().getDeviceId(),<br>        remoteUser.getPreKeyId(),<br>        remoteUser.getPreKeyPublicKey(),<br>        remoteUser.getSignedPreKeyId(),<br>        remoteUser.getSignedPreKeyPublicKey(),<br>        remoteUser.getSignedPreKeySignature(),<br>        remoteUser.getIdentityKeyPairPublicKey()<br>);<br><br>sessionBuilder.process(preKeyBundle);<br>SessionCipher mSessionCipher = new SessionCipher(protocolStore, protocolAddress);</pre><p>Here is the full code of the encrypted session class</p><pre>public class EncryptedSession {<br><br>    private enum Operation {<em>ENCRYPT</em>, <em>DECRYPT</em>}<br><br>    private SessionCipher mSessionCipher;<br><br>    private Operation lastOp;<br><br>    private final SignalProtocolAddress protocolAddress;<br><br>    private final EncryptedLocalUser localUser;<br>    private final EncryptedRemoteUser remoteUser;<br><br>    public EncryptedSession(EncryptedLocalUser localUser, EncryptedRemoteUser remoteUser) throws UntrustedIdentityException, InvalidKeyException {<br>        this.protocolAddress = remoteUser.getSignalProtocolAddress();<br>        this.localUser = localUser;<br>        this.remoteUser = remoteUser;<br>        //initSessionFromPreKey();<br>    }<br><br><br>    private void createSession(Operation operation) throws UntrustedIdentityException, InvalidKeyException {<br>        if (operation == lastOp) {<br>            return;<br>        }<br><br>        lastOp = operation;<br><br>        InMemorySignalProtocolStore protocolStore = new InMemorySignalProtocolStore(localUser.getIdentityKeyPair(), localUser.getRegistrationId());<br><br>        for (PreKeyRecord record : localUser.getPreKeys()) {<br>            protocolStore.storePreKey(record.getId(), record);<br>        }<br><br>        protocolStore.storeSignedPreKey(localUser.getSignedPreKey().getId(), localUser.getSignedPreKey());<br><br>        //Session<br>        SessionBuilder sessionBuilder = new SessionBuilder(protocolStore, remoteUser.getSignalProtocolAddress());<br>        PreKeyBundle preKeyBundle = new PreKeyBundle(<br>                remoteUser.getRegistrationId(),<br>                remoteUser.getSignalProtocolAddress().getDeviceId(),<br>                remoteUser.getPreKeyId(),<br>                remoteUser.getPreKeyPublicKey(),<br>                remoteUser.getSignedPreKeyId(),<br>                remoteUser.getSignedPreKeyPublicKey(),<br>                remoteUser.getSignedPreKeySignature(),<br>                remoteUser.getIdentityKeyPairPublicKey()<br>        );<br><br>        sessionBuilder.process(preKeyBundle);<br>        mSessionCipher = new SessionCipher(protocolStore, protocolAddress);<br>    }<br><br>    public String encrypt(String message) {<br>        try {<br>            createSession(Operation.<em>ENCRYPT</em>);<br>            CiphertextMessage ciphertextMessage = mSessionCipher.encrypt(message.getBytes());<br>            PreKeySignalMessage preKeySignalMessage = new PreKeySignalMessage(ciphertextMessage.serialize());<br>            return KeyUtils.<em>encodeToBase64</em>(preKeySignalMessage.serialize());<br>        } catch (UntrustedIdentityException | InvalidKeyException | InvalidVersionException | InvalidMessageException e) {<br>            return e.getMessage();<br>        }<br>    }<br><br>    public String decrypt(String message) {<br>        try {<br>            createSession(Operation.<em>DECRYPT</em>);<br>            byte[] bytes = KeyUtils.<em>decodeToByteArray</em>(message);<br>            byte[] decryptedMessage = mSessionCipher.decrypt(new PreKeySignalMessage(bytes));<br>            return new String(decryptedMessage, StandardCharsets.<em>UTF_8</em>);<br>        } catch (UntrustedIdentityException | InvalidKeyException | DuplicateMessageException | InvalidMessageException | InvalidKeyIdException | InvalidVersionException | LegacyMessageException e) {<br>            return e.getMessage();<br>        }<br>    }<br>}</pre><p><strong><em>Note:- </em></strong>You can’t decrypt your own message so keep your local message in your database and update other properties when you received success response from API/Socket.</p><p>The Receiver can now decrypt your message using the above classes and your end-end encryption logic will work using the signal protocol.</p><h3>Decrypting Message From Push Notifications:-</h3><p>As in the Signal Protocol documentation, you can build a session from PreKeySignalMessages. You will receive PreKeySignalMessages in base64 in the notifications payload. So you can easily decrypt the message.</p><p><em>e.g</em></p><pre>public EncryptedSession(EncryptedLocalUser localUser,<br>                        SignalProtocolAddress remotePersonProtocolAddress) {<br>    this.protocolAddress = remotePersonProtocolAddress;<br>    this.localUser = localUser;<br>}</pre><pre>private void initSession() {<br>    InMemorySignalProtocolStore protocolStore = new InMemorySignalProtocolStore(localUser.getIdentityKeyPair(), localUser.getRegistrationId());<br><br>    for (PreKeyRecord record : localUser.getPreKeys()) {<br>        protocolStore.storePreKey(record.getId(), record);<br>    }<br><br>    protocolStore.storeSignedPreKey(localUser.getSignedPreKey().getId(), localUser.getSignedPreKey());<br>    mSessionCipher = new SessionCipher(protocolStore, protocolAddress);<br>}</pre><p>Then you can call in your <strong>FirebaseMessagingService</strong></p><pre>val mEncryptedSession =<br>    EncryptedSession(<br>        mLocalUser,<br>        SignalProtocolAddress(userName/UserId, <em>DEFAULT_DEVICE_ID</em>)<br>    )<br>val message = mEncryptedSession.decrypt(encryptedMessage)</pre><p>For sample codes, you can checkout</p><ul><li><a href="https://github.com/abdularis/Signal-Protocol-Example/blob/master/app/src/test/java/com/aar/app/signalprotocolexample/Learn1.java">Signal-Protocol-Example/Learn1.java at master · abdularis/Signal-Protocol-Example</a></li><li><a href="https://github.com/lvijay/DemoSignal">GitHub - lvijay/DemoSignal: Simple demonstration of libsignal-protocol-java for a chat</a></li></ul><p><strong>System Architecture</strong></p><p><a href="https://github.com/abdularis/learn-signal-protocol">GitHub - abdularis/learn-signal-protocol: Signal Protocol Explained</a></p><p><strong>Android Sample</strong></p><p><a href="https://github.com/ahmedcs2600/SignalProtocolExampleAndroid">https://github.com/ahmedcs2600/SignalProtocolExampleAndroid</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70940c25c339" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>