public void StoreSignedPreKey(uint signedPreKeyId, SignedPreKeyRecord record)
 {
     if (this.OnStoreSignedPreKey != null)
     {
         this.OnStoreSignedPreKey(signedPreKeyId, record);
     }
 }
Example #2
0
        public static void RefreshPreKeys(SignalServiceAccountManager accountManager) //TODO wrap in extra lock? enforce reload?
        {
            List <PreKeyRecord> oneTimePreKeys     = GeneratePreKeys();
            SignedPreKeyRecord  signedPreKeyRecord = generateSignedPreKey(GetIdentityKeyPair());

            accountManager.setPreKeys(GetIdentityKeyPair().getPublicKey(), signedPreKeyRecord, oneTimePreKeys);
        }
Example #3
0
 public void StoreSignedPreKey(uint signedPreKeyId, SignedPreKeyRecord record)
 {
     conn.Insert(new SignedPreKeyRecordI()
     {
         SignedPreyKeyId = signedPreKeyId, Record = record.serialize()
     });
 }
        protected override async Task <string> ExecuteAsync()
        {
            //if (!TextSecurePreferences.isPushRegistered()) return;

            int availableKeys = await App.Current.accountManager.getPreKeysCount();

            if (availableKeys >= PREKEY_MINIMUM && TextSecurePreferences.isSignedPreKeyRegistered())
            {
                Debug.WriteLine("Available keys sufficient: " + availableKeys);
                return("");
            }

            List <PreKeyRecord> preKeyRecords = await PreKeyUtil.generatePreKeys(/*context, masterSecret*/);

            PreKeyRecord lastResortKeyRecord = await PreKeyUtil.generateLastResortKey(/*context, masterSecret*/);

            IdentityKeyPair    identityKey        = IdentityKeyUtil.GetIdentityKeyPair(/*context, masterSecret*/);
            SignedPreKeyRecord signedPreKeyRecord = PreKeyUtil.generateSignedPreKey(/*context, masterSecret, */ identityKey);

            Debug.WriteLine("Registering new prekeys...");

            await App.Current.accountManager.setPreKeys(identityKey.getPublicKey(), lastResortKeyRecord, signedPreKeyRecord, preKeyRecords);

            TextSecurePreferences.setSignedPreKeyRegistered(true);

            //App.Current.Worker.AddTaskActivities(new CleanPreKeysTask());

            return("");
        }
Example #5
0
        public void Test_OmemoBundleInformation_2()
        {
            IdentityKeyPair      aliceIdentKey     = CryptoUtils.generateOmemoIdentityKeyPair();
            IList <PreKeyRecord> alicePreKeys      = CryptoUtils.generateOmemoPreKeys();
            SignedPreKeyRecord   aliceSignedPreKey = CryptoUtils.generateOmemoSignedPreKey(aliceIdentKey);
            string bundleInfo = getBundleInfoMsg(aliceIdentKey, aliceSignedPreKey, alicePreKeys);

            MessageParser2         parser   = new MessageParser2();
            List <AbstractMessage> messages = parser.parseMessages(ref bundleInfo);

            // Check if message parsed successfully:
            Assert.IsTrue(messages.Count == 1);
            Assert.IsInstanceOfType(messages[0], typeof(OmemoBundleInformationResultMessage));

            OmemoBundleInformationResultMessage bundleInfoMsg = messages[0] as OmemoBundleInformationResultMessage;

            // Check if keys match:
            Assert.IsTrue(bundleInfoMsg.BUNDLE_INFO.PUBLIC_IDENTITY_KEY.serialize().SequenceEqual(aliceIdentKey.getPublicKey().serialize()));
            Assert.IsTrue(bundleInfoMsg.BUNDLE_INFO.PUBLIC_SIGNED_PRE_KEY.serialize().SequenceEqual(aliceSignedPreKey.getKeyPair().getPublicKey().serialize()));
            Assert.IsTrue(bundleInfoMsg.BUNDLE_INFO.SIGNED_PRE_KEY_ID == aliceSignedPreKey.getId());
            Assert.IsTrue(bundleInfoMsg.BUNDLE_INFO.SIGNED_PRE_KEY_SIGNATURE.SequenceEqual(aliceSignedPreKey.getSignature()));

            Assert.IsTrue(bundleInfoMsg.BUNDLE_INFO.PUBLIC_PRE_KEYS.Count == alicePreKeys.Count);
            foreach (PreKeyRecord key in alicePreKeys)
            {
                IEnumerable <Tuple <uint, ECPublicKey> > matches = bundleInfoMsg.BUNDLE_INFO.PUBLIC_PRE_KEYS.Where(x => x.Item1 == key.getId());
                Assert.IsTrue(matches.Count() == 1);
                byte[] a = matches.First().Item2.serialize();
                byte[] b = key.getKeyPair().getPublicKey().serialize();
                Assert.IsTrue(a.SequenceEqual(b));
            }
        }
Example #6
0
 public void StoreSignedPreKey(UInt32 signedPreKeyId, SignedPreKeyRecord record)
 {
     if (this.OnstoreSignedPreKey != null)
     {
         this.OnstoreSignedPreKey(signedPreKeyId, record.serialize());
     }
 }
        public bool registerPreKeys(IdentityKey identityKey,
                                    PreKeyRecord lastResortKey,
                                    SignedPreKeyRecord signedPreKey,
                                    IList <PreKeyRecord> records)
        //throws IOException
        {
            List <PreKeyEntity> entities = new List <PreKeyEntity>();

            foreach (PreKeyRecord record in records)
            {
                PreKeyEntity entity = new PreKeyEntity(record.getId(),
                                                       record.getKeyPair().getPublicKey());

                entities.Add(entity);
            }

            PreKeyEntity lastResortEntity = new PreKeyEntity(lastResortKey.getId(),
                                                             lastResortKey.getKeyPair().getPublicKey());

            SignedPreKeyEntity signedPreKeyEntity = new SignedPreKeyEntity(signedPreKey.getId(),
                                                                           signedPreKey.getKeyPair().getPublicKey(),
                                                                           signedPreKey.getSignature());

            makeRequest(string.Format(PREKEY_PATH, ""), "PUT",
                        JsonUtil.toJson(new PreKeyState(entities, lastResortEntity,
                                                        signedPreKeyEntity, identityKey)));
            return(true);
        }
Example #8
0
        /// <summary>
        /// Generate the keysets for ourself
        /// </summary>
        /// <returns></returns>
        public bool sendSetPreKeys(bool isnew = false)
        {
            uint registrationId = 0;

            if (!isnew)
            {
                registrationId = (uint)this.GetLocalRegistrationId();
            }
            else
            {
                registrationId = libaxolotl.util.KeyHelper.generateRegistrationId(true);
            }
            Random          random          = new Random();
            uint            randomid        = (uint)libaxolotl.util.KeyHelper.getRandomSequence(65536);
            IdentityKeyPair identityKeyPair = libaxolotl.util.KeyHelper.generateIdentityKeyPair();

            byte[] privateKey                  = identityKeyPair.getPrivateKey().serialize();
            byte[] publicKey                   = identityKeyPair.getPublicKey().serialize();
            IList <PreKeyRecord> preKeys       = libaxolotl.util.KeyHelper.generatePreKeys((uint)random.Next(), 200);
            SignedPreKeyRecord   signedPreKey  = libaxolotl.util.KeyHelper.generateSignedPreKey(identityKeyPair, randomid);
            PreKeyRecord         lastResortKey = libaxolotl.util.KeyHelper.generateLastResortPreKey();

            this.StorePreKeys(preKeys);
            this.StoreLocalData(registrationId, identityKeyPair.getPublicKey().serialize(), identityKeyPair.getPrivateKey().serialize());
            this.StoreSignedPreKey(signedPreKey.getId(), signedPreKey);

            List <ProtocolTreeNode> preKeyNodes = new List <ProtocolTreeNode>();

            for (int i = 0; i < 200; i++)
            {
                byte[]           prekeyId  = adjustId(preKeys[i].getId().ToString());
                byte[]           prekey    = preKeys[i].getKeyPair().getPublicKey().serialize().Skip(1).ToArray();
                ProtocolTreeNode NodeId    = new ProtocolTreeNode("id", null, null, prekeyId);
                ProtocolTreeNode NodeValue = new ProtocolTreeNode("value", null, null, prekey);
                preKeyNodes.Add(new ProtocolTreeNode("key", null, new[] { NodeId, NodeValue }, null));
            }

            ProtocolTreeNode registration = new ProtocolTreeNode("registration", null, null, adjustId(registrationId.ToString()));
            ProtocolTreeNode identity     = new ProtocolTreeNode("identity", null, null, publicKey.Skip(1).ToArray());
            ProtocolTreeNode type         = new ProtocolTreeNode("type", null, null, new byte[] { Curve.DJB_TYPE });
            ProtocolTreeNode list         = new ProtocolTreeNode("list", null, preKeyNodes.ToArray(), null);
            ProtocolTreeNode sid          = new ProtocolTreeNode("id", null, null, adjustId(signedPreKey.getId().ToString()));
            ProtocolTreeNode value        = new ProtocolTreeNode("value", null, null, signedPreKey.getKeyPair().getPublicKey().serialize().Skip(1).ToArray());
            ProtocolTreeNode signature    = new ProtocolTreeNode("signature", null, null, signedPreKey.getSignature());
            ProtocolTreeNode secretKey    = new ProtocolTreeNode("skey", null, new[] { sid, value, signature }, null);

            String id = TicketManager.GenerateId();

            Helper.DebugAdapter.Instance.fireOnPrintDebug(string.Format("axolotl id = {0}", id));

            ProtocolTreeNode Node = new ProtocolTreeNode("iq", new[] {
                new KeyValue("id", id),
                new KeyValue("xmlns", "encrypt"),
                new KeyValue("type", "set"),
                new KeyValue("to", "s.whatsapp.net")
            }, new ProtocolTreeNode[] { identity, registration, type, list, secretKey }, null);

            this.SendNode(Node);
            return(true);
        }
        /// <summary>
        /// Register an identity key, last resort key, signed prekey, and list of one time prekeys
        /// with the server.
        /// </summary>
        /// <param name="identityKey">The client's long-term identity keypair.</param>
        /// <param name="lastResortKey">The client's "last resort" prekey.</param>
        /// <param name="signedPreKey">The client's signed prekey.</param>
        /// <param name="oneTimePreKeys">The client's list of one-time prekeys.</param>
        /// <returns></returns>
        public async Task <bool> setPreKeys(IdentityKey identityKey, PreKeyRecord lastResortKey,
                                            SignedPreKeyRecord signedPreKey, IList <PreKeyRecord> oneTimePreKeys)//throws IOException
        {
            await this.pushServiceSocket.registerPreKeys(identityKey, lastResortKey, signedPreKey, oneTimePreKeys);

            return(true);
        }
 public void storeSignedPreKey(uint signedPreKeyId, SignedPreKeyRecord record)
 {
     if (store.ContainsKey(signedPreKeyId)) // mimic Java HashMap
     {
         store.Remove(signedPreKeyId);
     }
     store.Add(signedPreKeyId, record.serialize());
 }
Example #11
0
 public void storeSignedPreKey(uint signedPreKeyId, SignedPreKeyRecord record)
 {
     if (store.ContainsKey(signedPreKeyId)) // mimic Java HashMap
     {
         store.Remove(signedPreKeyId);
     }
     store.Add(signedPreKeyId, record.serialize());
 }
Example #12
0
 /// <summary>
 /// Generates a new omemoIdentityKeyPair, omemoSignedPreKeyPair, omemoPreKeys.
 /// Sets omemoDeviceId to 0.
 /// Sets omemoBundleInfoAnnounced to false.
 /// </summary>
 public void generateOmemoKeys()
 {
     omemoDeviceId            = 0;
     omemoBundleInfoAnnounced = false;
     omemoIdentityKeyPair     = CryptoUtils.generateOmemoIdentityKeyPair();
     omemoPreKeys             = CryptoUtils.generateOmemoPreKeys();
     omemoSignedPreKeyPair    = CryptoUtils.generateOmemoSignedPreKey(omemoIdentityKeyPair);
     omemoSignedPreKeyId      = omemoSignedPreKeyPair.getId();
 }
        public bool setCurrentSignedPreKey(SignedPreKeyRecord signedPreKey)// throws IOException
        {
            SignedPreKeyEntity signedPreKeyEntity = new SignedPreKeyEntity(signedPreKey.getId(),
                                                                           signedPreKey.getKeyPair().getPublicKey(),
                                                                           signedPreKey.getSignature());

            makeRequest(SIGNED_PREKEY_PATH, "PUT", JsonUtil.toJson(signedPreKeyEntity));
            return(true);
        }
Example #14
0
        /// <summary>
        /// Set the client's signed prekey.
        /// </summary>
        /// <param name="signedPreKey">The client's new signed prekey.</param>
        /// <param name="token">The cancellation token</param>
        /// <exception cref="IOException"></exception>
        public async Task SetSignedPreKeyAsync(SignedPreKeyRecord signedPreKey, CancellationToken?token = null)
        {
            if (token == null)
            {
                token = CancellationToken.None;
            }

            await pushServiceSocket.SetCurrentSignedPreKeyAsync(signedPreKey, token);
        }
Example #15
0
 public void setSignedPreKey(uint signedPreKeyId, SignedPreKeyRecord signedPreKey, string accountId)
 {
     dB.InsertOrReplace(new SignedPreKeyTable()
     {
         id             = SignedPreKeyTable.generateId(signedPreKeyId, accountId),
         signedPreKeyId = signedPreKeyId,
         accountId      = accountId,
         signedPreKey   = signedPreKey.serialize()
     });
 }
Example #16
0
        public SignedPreKeyRecord LoadSignedPreKey(uint signedPreKeyId)
        {
            SignedPreKeyRecord signedPreKeyRecord = OmemoSignalKeyDBManager.INSTANCE.getSignedPreKey(signedPreKeyId, ACCOUNT.getBareJid());

            if (signedPreKeyRecord is null)
            {
                Logger.Error("OmemoStore: No such signed pre key: " + signedPreKeyId);
            }
            return(signedPreKeyRecord);
        }
Example #17
0
        public SignedPreKeyRecord LoadSignedPreKey(uint signedPreKeyId)
        {
            SignedPreKeyRecord signedPreKeyRecord = OmemoSignalKeyDBManager.INSTANCE.getSignedPreKey(signedPreKeyId, ACCOUNT.getBareJid());

            if (signedPreKeyRecord is null)
            {
                throw new InvalidKeyIdException("No such key: " + signedPreKeyId);
            }
            return(signedPreKeyRecord);
        }
        public SignedPreKeyRecord LoadSignedPreKey(uint signedPreKeyId)
        {
            SignedPreKeyRecord signedPreKeyRecord = SignalKeyDBManager.INSTANCE.getSignedPreKey(signedPreKeyId, ACCOUNT.getIdAndDomain());

            if (signedPreKeyRecord == null)
            {
                throw new InvalidKeyIdException("No such key: " + signedPreKeyId);
            }
            return(signedPreKeyRecord);
        }
Example #19
0
        public async Task <bool> SetCurrentSignedPreKey(CancellationToken token, SignedPreKeyRecord signedPreKey)// throws IOException
        {
            SignedPreKeyEntity signedPreKeyEntity = new SignedPreKeyEntity(signedPreKey.getId(),
                                                                           signedPreKey.getKeyPair().getPublicKey(),
                                                                           signedPreKey.getSignature());

            await MakeServiceRequestAsync(token, SIGNED_PREKEY_PATH, "PUT", JsonUtil.ToJson(signedPreKeyEntity));

            return(true);
        }
Example #20
0
        private static Task <SignedPreKeyRecord> generateSignedPreKey(IdentityKeyPair identityKeyPair, uint signedPreKeyId)
        {
            return(Task.Run(() =>
            {
                ECKeyPair keyPair = Curve.generateKeyPair();
                byte[] signature = Curve.calculateSignature(identityKeyPair.getPrivateKey(), keyPair.getPublicKey().serialize());
                SignedPreKeyRecord record = new SignedPreKeyRecord(signedPreKeyId, KeyHelper.getTime(), keyPair, signature);

                return record;
            }));
        }
Example #21
0
        /// <summary>
        /// Register an identity key, signed prekey, and list of one time prekeys
        /// with the server.
        /// </summary>
        /// <param name="identityKey">The client's long-term identity keypair.</param>
        /// <param name="signedPreKey">The client's signed prekey.</param>
        /// <param name="oneTimePreKeys">The client's list of one-time prekeys.</param>
        /// <param name="token">The cancellation token</param>
        /// <returns></returns>
        /// <exception cref="IOException"></exception>
        public async Task <bool> SetPreKeysAsync(IdentityKey identityKey, SignedPreKeyRecord signedPreKey, IList <PreKeyRecord> oneTimePreKeys, CancellationToken?token = null)
        {
            if (token == null)
            {
                token = CancellationToken.None;
            }

            await pushServiceSocket.RegisterPreKeysAsync(identityKey, signedPreKey, oneTimePreKeys, token);

            return(true);
        }
Example #22
0
        private static SignedPreKeyRecord generateSignedPreKey(IdentityKeyPair identityKeyPair, uint signedPreKeyId)
        {
            //return Task.Run(() =>
            //{
            ECKeyPair keyPair = Curve.generateKeyPair();

            byte[]             signature = Curve.calculateSignature(identityKeyPair.getPrivateKey(), keyPair.getPublicKey().serialize());
            SignedPreKeyRecord record    = new SignedPreKeyRecord(signedPreKeyId, (ulong)TimeUtil.GetUnixTimestampMillis(), keyPair, signature);

            return(record);
            // });
        }
Example #23
0
        private async Task <bool> handleRegistration(string receivedSmsVerificationCode)
        {
            try
            {
                var registrationId = KeyHelper.generateRegistrationId(false);
                TextSecurePreferences.setLocalRegistrationId((int)registrationId);

                await App.Current.accountManager.verifyAccountWithCode(receivedSmsVerificationCode, signalingKey, registrationId, false);

                //await PushHelper.getInstance().OpenChannelAndUpload(); // also updates push channel id

                Recipient self = DatabaseFactory.getRecipientDatabase().GetSelfRecipient(number);
                IdentityKeyUtil.generateIdentityKeys();
                IdentityKeyPair     identityKey = IdentityKeyUtil.GetIdentityKeyPair();
                List <PreKeyRecord> records     = await PreKeyUtil.generatePreKeys();

                PreKeyRecord lastResort = await PreKeyUtil.generateLastResortKey();

                SignedPreKeyRecord signedPreKey = await PreKeyUtil.generateSignedPreKey(identityKey);

                await App.Current.accountManager.setPreKeys(identityKey.getPublicKey(), lastResort, signedPreKey, records);

                DatabaseFactory.getIdentityDatabase().SaveIdentity(self.getRecipientId(), identityKey.getPublicKey());

                //await DirectoryHelper.refreshDirectory(App.Current.accountManager, TextSecurePreferences.getLocalNumber());


                markAsVerified(number, password, signalingKey);
            }
            catch (RateLimitException ex)
            {
                return(false);
            }
            catch (AuthorizationFailedException ex)
            {
                return(false);
            }
            catch (PushNetworkException ex)
            {
                return(false);
            }
            catch (NonSuccessfulResponseCodeException ex)
            {
                return(false);
            }
            catch (Exception ex)
            {
                return(false);
                //throw new Exception(ex.Message);
            }

            return(true);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="signedPreKeyId"></param>
        /// <param name="signedPreKeyRecord"></param>
        public void StoreSignedPreKey(uint signedPreKeyId, SignedPreKeyRecord signedPreKeyRecord)
        {
            if (SignedPreKeysObjectDic.ContainsKey(signedPreKeyId))
            {
                SignedPreKeysObjectDic.Remove(signedPreKeyId);
            }

            SignedPreKeysObjectDic.Add(signedPreKeyId, new SignedPreKeysObject()
            {
                PreKeyId = signedPreKeyId,
                Record   = signedPreKeyRecord.Serialize()
            });
        }
        public SignedPreKeyRecord LoadSignedPreKey(uint signedPreKeyId)
        {
            SignedPreKeysRepository preKeysRepository = new SignedPreKeysRepository();
            List <SignedPreKeys>    signedPreKeys     = preKeysRepository.GetSignedPreKeys(Convert.ToString(signedPreKeyId));

            if (signedPreKeys != null && signedPreKeys.Count > 0)
            {
                SignedPreKeyRecord signedPreKeyRecord = new SignedPreKeyRecord(signedPreKeys.First().Record);
                return(signedPreKeyRecord);
            }

            return(null);
        }
        // Implement OnLogin method
        public void OnRegister(object sender, EventArgs e)
        {
            IdentityKeyPair     identityKeyPair = KeyHelper.generateIdentityKeyPair();
            uint                registrationId  = KeyHelper.generateRegistrationId(false);
            List <PreKeyRecord> preKeys         = KeyHelper.generatePreKeys(registrationId, 100).ToList();
            Random              random          = new Random();
            SignedPreKeyRecord  signedPreKey    = KeyHelper.generateSignedPreKey(identityKeyPair, Convert.ToUInt32(random.Next()));

            InMemorySessionStore SessionStore = new InMemorySessionStore();
            //SessionStore.StoreSession(new SignalProtocolAddress("1234", 1), new SessionRecord());
            PreKeyStore              PreKeyStore       = new InMemoryPreKeyStore();
            SignedPreKeyStore        SignedPreKeyStore = new InMemorySignedPreKeyStore();
            InMemoryIdentityKeyStore IdentityStore     = new InMemoryIdentityKeyStore(identityKeyPair, registrationId);

            // Store preKeys in PreKeyStore.
            foreach (PreKeyRecord preKey in preKeys)
            {
                PreKeyStore.StorePreKey(preKey.getId(), preKey);
            }

            // Store signed prekey in SignedPreKeyStore.
            SignedPreKeyStore.StoreSignedPreKey(signedPreKey.getId(), signedPreKey);

            // Save stores in local Database
            ISharedPreferences       sharedprefs = PreferenceManager.GetDefaultSharedPreferences(this);
            ISharedPreferencesEditor editor      = sharedprefs.Edit();

            editor.PutString("PreKeyStore", JsonConvert.SerializeObject(PreKeyStore));
            editor.PutString("SignedPreKeyStore", JsonConvert.SerializeObject(SignedPreKeyStore));
            List <Session> AllSessions = SessionStore.GetAllSessions();

            editor.PutString("AllSessions", JsonConvert.SerializeObject(AllSessions));
            editor.PutString("SessionStore", JsonConvert.SerializeObject(SessionStore));
            editor.PutString("IdentityStore", JsonConvert.SerializeObject(IdentityStore));
            List <TrustedKey> AllTrustedKeys = IdentityStore.GetAllTrustedKeys();

            editor.PutString("AllTrustedKeys", JsonConvert.SerializeObject(AllTrustedKeys));
            editor.Apply();

            //var sessionStore = JsonConvert.DeserializeObject<InMemorySessionStore>(sharedprefs.GetString("SessionStore", string.Empty));
            //var allSessions = JsonConvert.DeserializeObject<List<Session>>(sharedprefs.GetString("AllSessions", string.Empty));
            //foreach (Session item in allSessions)
            //{
            //    sessionStore.StoreSession(item.Name, item.DeviceID, item.array);
            //}

            // method to regidter in database
            RequestRegister(registrationId, identityKeyPair, signedPreKey, preKeys);
            StartActivity(typeof(FriendsActivity));
        }
        private void InitializeSessions(TestInMemorySignalProtocolStore aliceStore, TestInMemorySignalProtocolStore bobStore)
        {
            ECKeyPair          bobPreKey       = Curve.generateKeyPair();
            IdentityKeyPair    bobIdentityKey  = bobStore.GetIdentityKeyPair();
            SignedPreKeyRecord bobSignedPreKey = KeyHelper.generateSignedPreKey(bobIdentityKey, 2);

            PreKeyBundle   bobBundle           = new PreKeyBundle(1, 1, 1, bobPreKey.getPublicKey(), 2, bobSignedPreKey.getKeyPair().getPublicKey(), bobSignedPreKey.getSignature(), bobIdentityKey.getPublicKey());
            SessionBuilder aliceSessionBuilder = new SessionBuilder(aliceStore, new SignalProtocolAddress("+14152222222", 1));

            aliceSessionBuilder.process(bobBundle);

            bobStore.StoreSignedPreKey(2, bobSignedPreKey);
            bobStore.StorePreKey(1, new PreKeyRecord(1, bobPreKey));
        }
Example #28
0
 public static void StoreSignedPreKey(uint signedPreKeyId, SignedPreKeyRecord record)
 {
     lock (DBLock)
     {
         using (var ctx = new LibsignalDBContext())
         {
             ctx.SignedPreKeys.Add(new SignalSignedPreKey()
             {
                 Id  = signedPreKeyId,
                 Key = Base64.encodeBytes(record.serialize())
             });
             ctx.SaveChanges();
         }
     }
 }
        public void StoreSignedPreKey(uint signedPreKeyId, SignedPreKeyRecord record)
        {
            if (ContainsSignedPreKey(signedPreKeyId))
            {
                RemovePreKey(signedPreKeyId);
            }

            SignedPreKeysRepository signedPreKeysRepository = new SignedPreKeysRepository();
            SignedPreKeys           signedPreKey            = new SignedPreKeys()
            {
                PreKeyId = Convert.ToString(signedPreKeyId),
                Record   = record.Serialize()
            };
            bool result = signedPreKeysRepository.Save(signedPreKey);
        }
Example #30
0
        private May <uint> ProcessV3(SessionRecord sessionRecord, PreKeyWhisperMessage message)
        {
            if (sessionRecord.HasSessionState(message.GetMessageVersion(), message.GetBaseKey().Serialize()))
            {
                return(May <uint> .NoValue);
            }

            SignedPreKeyRecord signedPreKeyRecord = signedPreKeyStore.LoadSignedPreKey(message.GetSignedPreKeyId());
            ECKeyPair          ourSignedPreKey    = signedPreKeyRecord.GetKeyPair();

            BobAxolotlParameters.Builder parameters = BobAxolotlParameters.NewBuilder();

            parameters.SetTheirBaseKey(message.GetBaseKey())
            .SetTheirIdentityKey(message.GetIdentityKey())
            .SetOurIdentityKey(identityKeyStore.GetIdentityKeyPair())
            .SetOurSignedPreKey(ourSignedPreKey)
            .SetOurRatchetKey(ourSignedPreKey);

            if (message.GetPreKeyId().HasValue)
            {
                parameters.SetOurOneTimePreKey(new May <ECKeyPair>(preKeyStore.LoadPreKey(message.GetPreKeyId().ForceGetValue()).GetKeyPair()));
            }
            else
            {
                parameters.SetOurOneTimePreKey(May <ECKeyPair> .NoValue);
            }

            if (!sessionRecord.IsFresh())
            {
                sessionRecord.ArchiveCurrentState();
            }

            RatchetingSession.InitializeSession(sessionRecord.GetSessionState(), message.GetMessageVersion(), parameters.Create());

            sessionRecord.GetSessionState().SetLocalRegistrationId(identityKeyStore.GetLocalRegistrationId());
            sessionRecord.GetSessionState().SetRemoteRegistrationId(message.GetRegistrationId());
            sessionRecord.GetSessionState().SetAliceBaseKey(message.GetBaseKey().Serialize());

            if (message.GetPreKeyId().HasValue&& message.GetPreKeyId().ForceGetValue() != Medium.MAX_VALUE)
            {
                return(message.GetPreKeyId());
            }
            else
            {
                return(May <uint> .NoValue);
            }
        }
Example #31
0
        private static SignedPreKeyRecord generateSignedPreKey(IdentityKeyPair identityKeyPair)
        {
            try
            {
                ECKeyPair          keyPair   = Curve.generateKeyPair();
                byte[]             signature = Curve.calculateSignature(identityKeyPair.getPrivateKey(), keyPair.getPublicKey().serialize());
                SignedPreKeyRecord record    = new SignedPreKeyRecord(App.Store.NextSignedPreKeyId, (ulong)DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond, keyPair, signature);

                StoreSignedPreKey(App.Store.NextSignedPreKeyId, record);
                UpdateNextSignedPreKeyId((App.Store.NextSignedPreKeyId + 1) % Medium.MAX_VALUE);
                return(record);
            }
            catch (InvalidKeyException e)
            {
                throw e;
            }
        }
		public void StoreSignedPreKey(uint signedPreKeyId, SignedPreKeyRecord record)
		{
			store[signedPreKeyId] = record.serialize();
		}
 public void storeSignedPreKey(uint signedPreKeyId, SignedPreKeyRecord record)
 {
     signedPreKeyStore.storeSignedPreKey(signedPreKeyId, record);
 }