Esempio n. 1
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);
        }
Esempio n. 3
0
 public void StorePreKey(uint preKeyId, PreKeyRecord record)
 {
     if (this.OnstorePreKey != null)
     {
         this.OnstorePreKey(preKeyId, record.serialize());
     }
 }
Esempio n. 4
0
 public void StorePreKey(uint preKeyId, PreKeyRecord record)
 {
     conn.Insert(new PreKeyRecordI()
     {
         PreKeyId = preKeyId, Record = record.serialize()
     });
 }
Esempio n. 5
0
        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("");
        }
        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);
        }
Esempio n. 7
0
        public static Task <PreKeyRecord> generateLastResortKey()
        {
            return(Task.Run(() =>
            {
                PreKeyStore preKeyStore = new TextSecurePreKeyStore(conn);

                if (preKeyStore.ContainsPreKey(Medium.MAX_VALUE))
                {
                    try
                    {
                        //return preKeyStore.loadPreKey(Medium.MAX_VALUE);
                        return preKeyStore.LoadPreKey(Medium.MAX_VALUE);
                    }
                    catch (InvalidKeyIdException e)
                    {
                        //Log.w("PreKeyUtil", e);
                        preKeyStore.RemovePreKey(Medium.MAX_VALUE);
                    }
                }

                ECKeyPair keyPair = Curve.generateKeyPair();
                PreKeyRecord record = new PreKeyRecord(Medium.MAX_VALUE, keyPair);

                preKeyStore.StorePreKey(Medium.MAX_VALUE, record);

                return record;
            }));
        }
Esempio n. 8
0
 public void StorePreKey(uint preKeyId, PreKeyRecord record)
 {
     if (this.OnStorePreKey != null)
     {
         this.OnStorePreKey(preKeyId, record);
     }
 }
Esempio n. 9
0
 public void storePreKey(uint preKeyId, PreKeyRecord record)
 {
     if (store.ContainsKey(preKeyId)) // mimic Java HashMap
     {
         store.Remove(preKeyId);
     }
     store.Add(preKeyId, record.serialize()); // put
 }
Esempio n. 10
0
        public static void RefreshPreKeys(SignalServiceAccountManager accountManager) //TODO wrap in extra lock? enforce reload?
        {
            List <PreKeyRecord> oneTimePreKeys     = GeneratePreKeys();
            PreKeyRecord        lastResortKey      = getOrGenerateLastResortPreKey();
            SignedPreKeyRecord  signedPreKeyRecord = generateSignedPreKey(GetIdentityKeyPair());

            accountManager.setPreKeys(GetIdentityKeyPair().getPublicKey(), lastResortKey, signedPreKeyRecord, oneTimePreKeys);
        }
Esempio n. 11
0
 public void storePreKey(uint preKeyId, PreKeyRecord record)
 {
     if (store.ContainsKey(preKeyId)) // mimic Java HashMap
     {
         store.Remove(preKeyId);
     }
     store.Add(preKeyId, record.serialize()); // put
 }
Esempio n. 12
0
        public PreKeyRecord LoadPreKey(uint preKeyId)
        {
            PreKeyRecord preKeyRecord = SignalKeyDBManager.INSTANCE.getPreKeyRecord(preKeyId, ACCOUNT.getIdAndDomain());

            if (preKeyRecord == null)
            {
                throw new InvalidKeyIdException("No such key: " + preKeyId);
            }
            return(preKeyRecord);
        }
Esempio n. 13
0
 public void setPreKey(uint preKeyId, PreKeyRecord preKey, string accountId)
 {
     dB.InsertOrReplace(new PreKeyTable()
     {
         id        = PreKeyTable.generateId(preKeyId, accountId),
         preKeyId  = preKeyId,
         accountId = accountId,
         preKey    = preKey.serialize()
     });
 }
Esempio n. 14
0
        public PreKeyRecord LoadPreKey(uint preKeyId)
        {
            PreKeyRecord preKeyRecord = OmemoSignalKeyDBManager.INSTANCE.getPreKeyRecord(preKeyId, ACCOUNT.getBareJid());

            if (preKeyRecord is null)
            {
                throw new InvalidKeyIdException("No such key: " + preKeyId);
            }
            return(preKeyRecord);
        }
Esempio n. 15
0
        private static Task <PreKeyRecord> generatePreKey(uint preKeyId)
        {
            return(Task.Run(() =>
            {
                ECKeyPair keyPair = Curve.generateKeyPair();
                PreKeyRecord record = new PreKeyRecord(preKeyId, keyPair);

                return record;
            }));
        }
Esempio n. 16
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="prekeyId"></param>
        /// <param name="preKeyRecord"></param>
        public void StorePreKey(uint prekeyId, PreKeyRecord preKeyRecord)
        {
            if (PreKeysObjectDic.ContainsKey(prekeyId))
            {
                PreKeysObjectDic.Remove(prekeyId);
            }

            PreKeysObjectDic.Add(prekeyId, new PreKeysObject()
            {
                PreKeyId = prekeyId.ToString(),
                Record   = preKeyRecord.Serialize()
            });
        }
        public PreKeyRecord LoadPreKey(uint preKeyId)
        {
            PreKeysRepository preKeysRepository = new PreKeysRepository();
            List <PreKeys>    preKeys           = preKeysRepository.GetPreKeys(Convert.ToString(preKeyId));

            if (preKeys != null && preKeys.Count > 0)
            {
                PreKeyRecord preKeyRecord = new PreKeyRecord(preKeys.First().Record);
                return(preKeyRecord);
            }

            return(null);
        }
        public void StorePreKey(uint preKeyId, PreKeyRecord record)
        {
            if (ContainsPreKey(preKeyId))
            {
                RemovePreKey(preKeyId);
            }

            PreKeysRepository preKeysRepository = new PreKeysRepository();
            PreKeys           preKey            = new PreKeys()
            {
                PreKeyId = Convert.ToString(preKeyId),
                Record   = record.Serialize()
            };
            bool result = preKeysRepository.Save(preKey);
        }
Esempio n. 20
0
 public static void StorePreKey(uint preKeyId, PreKeyRecord record)
 {
     lock (DBLock)
     {
         using (var ctx = new LibsignalDBContext())
         {
             ctx.PreKeys.Add(new SignalPreKey()
             {
                 Id  = preKeyId,
                 Key = Base64.encodeBytes(record.serialize())
             });
             ctx.SaveChanges();
         }
     }
 }
Esempio n. 21
0
        private static List <PreKeyRecord> GeneratePreKeys()
        {
            List <PreKeyRecord> records = new List <PreKeyRecord>();

            for (uint i = 1; i < App.PREKEY_BATCH_SIZE; i++)
            {
                uint         preKeyId = (App.Store.PreKeyIdOffset + i) % Medium.MAX_VALUE;
                ECKeyPair    keyPair  = Curve.generateKeyPair();
                PreKeyRecord record   = new PreKeyRecord(preKeyId, keyPair);

                StorePreKey(preKeyId, record);
                records.Add(record);
            }
            UpdatePreKeyIdOffset((App.Store.PreKeyIdOffset + App.PREKEY_BATCH_SIZE + 1) % Medium.MAX_VALUE);
            return(records);
        }
Esempio n. 22
0
        private static PreKeyRecord getOrGenerateLastResortPreKey()
        {
            if (ContainsPreKey(Medium.MAX_VALUE))
            {
                try
                {
                    return(LoadPreKey(Medium.MAX_VALUE));
                }
                catch (InvalidKeyIdException)
                {
                    RemovePreKey(Medium.MAX_VALUE);
                }
            }
            ECKeyPair    keyPair = Curve.generateKeyPair();
            PreKeyRecord record  = new PreKeyRecord(Medium.MAX_VALUE, keyPair);

            StorePreKey(Medium.MAX_VALUE, record);
            return(record);
        }
Esempio n. 23
0
        public static async Task <List <PreKeyRecord> > generatePreKeys()
        {
            PreKeyStore         preKeyStore = new TextSecurePreKeyStore(conn);
            List <PreKeyRecord> records     = new List <PreKeyRecord>();
            uint preKeyIdOffset             = getNextPreKeyId();

            for (uint i = 0; i < BATCH_SIZE; i++)
            {
                uint preKeyId = (preKeyIdOffset + i) % Medium.MAX_VALUE;

                PreKeyRecord record = await generatePreKey(preKeyId);

                preKeyStore.StorePreKey(preKeyId, record);
                records.Add(record);
            }

            setNextPreKeyId((preKeyIdOffset + BATCH_SIZE + 1) % Medium.MAX_VALUE);
            return(records);
        }
Esempio n. 24
0
        public void replaceOmemoPreKey(uint preKeyId, IOmemoStore omemoStore)
        {
            // Remove key:
            foreach (PreKeyRecord key in OMEMO_PRE_KEYS)
            {
                if (key.getId() == preKeyId)
                {
                    OMEMO_PRE_KEYS.Remove(key);
                    omemoStore.RemovePreKey(preKeyId);
                    break;
                }
            }

            // Generate new key:
            PreKeyRecord newKey = KeyHelper.generatePreKeys(preKeyId, 1)[0];

            OMEMO_PRE_KEYS.Add(newKey);
            omemoStore.StorePreKey(newKey.getId(), newKey);
            omemoBundleInfoAnnounced = false;
        }
Esempio n. 25
0
 public void StorePreKey(uint preKeyId, PreKeyRecord preKey)
 {
     SignalKeyDBManager.INSTANCE.setPreKey(preKeyId, preKey, ACCOUNT.getIdAndDomain());
 }
		public void StorePreKey(uint preKeyId, PreKeyRecord record)
		{
			store[preKeyId] = record.serialize();
		}
Esempio n. 27
0
 public void storePreKey(uint preKeyId, PreKeyRecord record)
 {
     preKeyStore.storePreKey(preKeyId, record);
 }
Esempio n. 28
0
 public void StorePreKey(uint preKeyId, PreKeyRecord record)
 {
     LibsignalDBContext.StorePreKey(preKeyId, record);
 }
Esempio n. 29
0
 public void StorePreKey(uint preKeyId, PreKeyRecord preKey)
 {
     OmemoSignalKeyDBManager.INSTANCE.setPreKey(preKeyId, preKey, ACCOUNT.getBareJid());
 }
Esempio n. 30
0
 public void StorePreKey(uint preKeyId, PreKeyRecord record)
 {
     preKeyStore.StorePreKey(preKeyId, record);
 }
Esempio n. 31
0
 public void StorePreKey(uint preKeyId, PreKeyRecord record)
 {
     PRE_KEYS[preKeyId] = record;
 }
 public void StorePreKey(uint preKeyId, PreKeyRecord record)
 {
     _store[preKeyId] = record.Serialize();
 }