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 void StoreLocalData(uint registrationId, IdentityKeyPair identityKeyPair)
 {
     if (this.OnStoreLocalData != null)
     {
         this.OnStoreLocalData(registrationId, identityKeyPair);
     }
 }
Beispiel #3
0
        /// <summary>
        /// Fetch a ProvisionMessage from the server.
        /// </summary>
        /// <param name="token"></param>
        /// <param name="tempIdentity"></param>
        /// <returns></returns>
        public async Task <SignalServiceProvisionMessage> GetProvisioningMessage(CancellationToken token, IdentityKeyPair tempIdentity)
        {
            ProvisionMessage protoPm = await ProvisioningSocket.GetProvisioningMessage(token, tempIdentity);

            string provisioningCode = protoPm.ProvisioningCode;

            byte[] publicKeyBytes = protoPm.IdentityKeyPublic.ToByteArray();
            if (publicKeyBytes.Length == 32)
            {
                byte[] type = { Curve.DJB_TYPE };
                publicKeyBytes = ByteUtil.combine(type, publicKeyBytes);
            }
            ECPublicKey publicKey = Curve.decodePoint(publicKeyBytes, 0);

            byte[]          privateKeyBytes = protoPm.IdentityKeyPrivate.ToByteArray();
            ECPrivateKey    privateKey      = Curve.decodePrivatePoint(privateKeyBytes);
            IdentityKeyPair identity        = new IdentityKeyPair(new IdentityKey(publicKey), privateKey);

            return(new SignalServiceProvisionMessage()
            {
                Number = protoPm.Number,
                Identity = identity,
                Code = protoPm.ProvisioningCode
            });
        }
Beispiel #4
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);
        }
Beispiel #5
0
        public NewDeviceLinkResult FinishNewDeviceRegistration(IdentityKeyPair tempIdentity, string signalingKey, string password, bool sms, bool fetches, int regid, string name)
        {
            ProvisionMessage pm = ProvisioningSocket.GetProvisioningMessage(tempIdentity);
            string           provisioningCode = pm.ProvisioningCode;

            byte[] publicKeyBytes = pm.IdentityKeyPublic.ToByteArray();
            if (publicKeyBytes.Length == 32)
            {
                byte[] type = { Curve.DJB_TYPE };
                publicKeyBytes = ByteUtil.combine(type, publicKeyBytes);
            }
            ECPublicKey publicKey = Curve.decodePoint(publicKeyBytes, 0);

            byte[]          privateKeyBytes = pm.IdentityKeyPrivate.ToByteArray();
            ECPrivateKey    privateKey      = Curve.decodePrivatePoint(privateKeyBytes);
            IdentityKeyPair identity        = new IdentityKeyPair(new IdentityKey(publicKey), privateKey);

            pushServiceSocket = new PushServiceSocket(Urls, new StaticCredentialsProvider(pm.Number, password, null, -1), userAgent);
            int deviceId = pushServiceSocket.finishNewDeviceRegistration(provisioningCode, signalingKey, sms, fetches, regid, name);

            return(new NewDeviceLinkResult()
            {
                DeviceId = deviceId,
                Identity = identity,
                Number = pm.Number
            });
        }
        public DeviceConsistencyMessage(DeviceConsistencyCommitment commitment, IdentityKeyPair identityKeyPair)
        {
            try
            {
                byte[] signatureBytes = Curve.CalculateVrfSignature(identityKeyPair.GetPrivateKey(), commitment.ToByteArray());
                byte[] vrfOutputBytes = Curve.VerifyVrfSignature(identityKeyPair.GetPublicKey().GetPublicKey(), commitment.ToByteArray(), signatureBytes);

                _generation = commitment.GetGeneration();
                _signature  = new DeviceConsistencySignature(signatureBytes, vrfOutputBytes);
                _serialized = SignalProtos.DeviceConsistencyCodeMessage.CreateBuilder()
                              .SetGeneration((uint)commitment.GetGeneration())
                              .SetSignature(ByteString.CopyFrom(_signature.GetSignature()))
                              .Build()
                              .ToByteArray();
            }
            catch (InvalidKeyException e)
            {
                Debug.Assert(false);
                throw e;
            }
            catch (VrfSignatureVerificationFailedException e)
            {
                Debug.Assert(false);
                throw e;
            }
        }
Beispiel #7
0
        /// <summary>
        /// TODO
        /// </summary>
        /// <param name="deviceIdentifier"></param>
        /// <param name="deviceKey"></param>
        /// <param name="identityKeyPair"></param>
        /// <param name="profileKey"></param>
        /// <param name="code"></param>
        /// <param name="token"></param>
        /// <exception cref="InvalidKeyException"><</exception>
        /// <exception cref="IOException"></exception>
        public async Task AddDeviceAsync(string deviceIdentifier,
                                         ECPublicKey deviceKey,
                                         IdentityKeyPair identityKeyPair,
                                         byte[] profileKey,
                                         string code,
                                         CancellationToken?token = null)
        {
            if (token == null)
            {
                token = CancellationToken.None;
            }

            ProvisioningCipher cipher  = new ProvisioningCipher(deviceKey);
            ProvisionMessage   message = new ProvisionMessage
            {
                IdentityKeyPublic  = ByteString.CopyFrom(identityKeyPair.getPublicKey().serialize()),
                IdentityKeyPrivate = ByteString.CopyFrom(identityKeyPair.getPrivateKey().serialize()),
                Number             = credentials.E164,
                ProvisioningCode   = code
            };

            if (profileKey != null)
            {
                message.ProfileKey = ByteString.CopyFrom(profileKey);
            }

            byte[] ciphertext = cipher.Encrypt(message);
            await pushServiceSocket.SendProvisioningMessageAsync(deviceIdentifier, ciphertext, token);
        }
Beispiel #8
0
        private void initializeSessionsV2(SessionState aliceSessionState, SessionState bobSessionState)
        {
            ECKeyPair       aliceIdentityKeyPair = Curve.generateKeyPair();
            IdentityKeyPair aliceIdentityKey     = new IdentityKeyPair(new IdentityKey(aliceIdentityKeyPair.getPublicKey()),
                                                                       aliceIdentityKeyPair.getPrivateKey());
            ECKeyPair aliceBaseKey      = Curve.generateKeyPair();
            ECKeyPair aliceEphemeralKey = Curve.generateKeyPair();

            ECKeyPair       bobIdentityKeyPair = Curve.generateKeyPair();
            IdentityKeyPair bobIdentityKey     = new IdentityKeyPair(new IdentityKey(bobIdentityKeyPair.getPublicKey()),
                                                                     bobIdentityKeyPair.getPrivateKey());
            ECKeyPair bobBaseKey      = Curve.generateKeyPair();
            ECKeyPair bobEphemeralKey = bobBaseKey;

            AliceAxolotlParameters aliceParameters = AliceAxolotlParameters.newBuilder()
                                                     .setOurIdentityKey(aliceIdentityKey)
                                                     .setOurBaseKey(aliceBaseKey)
                                                     .setTheirIdentityKey(bobIdentityKey.getPublicKey())
                                                     .setTheirSignedPreKey(bobEphemeralKey.getPublicKey())
                                                     .setTheirRatchetKey(bobEphemeralKey.getPublicKey())
                                                     .setTheirOneTimePreKey(May <ECPublicKey> .NoValue)
                                                     .create();

            BobAxolotlParameters bobParameters = BobAxolotlParameters.newBuilder()
                                                 .setOurIdentityKey(bobIdentityKey)
                                                 .setOurOneTimePreKey(May <ECKeyPair> .NoValue)
                                                 .setOurRatchetKey(bobEphemeralKey)
                                                 .setOurSignedPreKey(bobBaseKey)
                                                 .setTheirBaseKey(aliceBaseKey.getPublicKey())
                                                 .setTheirIdentityKey(aliceIdentityKey.getPublicKey())
                                                 .create();

            RatchetingSession.initializeSession(aliceSessionState, 2, aliceParameters);
            RatchetingSession.initializeSession(bobSessionState, 2, bobParameters);
        }
Beispiel #9
0
        public ProvisionMessage Decrypt(IdentityKeyPair tmpIdentity, byte[] message)
        {
            ProvisionEnvelope env       = ProvisionEnvelope.Parser.ParseFrom(message);
            ECPublicKey       publicKey = Curve.decodePoint(env.PublicKey.ToByteArray(), 0);

            byte[]   sharedSecret  = Curve.calculateAgreement(publicKey, tmpIdentity.getPrivateKey());
            byte[]   derivedSecret = new HKDFv3().deriveSecrets(sharedSecret, Encoding.UTF8.GetBytes("TextSecure Provisioning Message"), 64);
            byte[][] parts         = Util.Split(derivedSecret, 32, 32);
            byte[]   joined        = env.Body.ToByteArray();
            if (joined[0] != 0x01)
            {
                throw new Exception("Bad version number on provision message!");
            }
            byte[] iv = new byte[16];
            Array.Copy(joined, 1, iv, 0, 16);
            byte[] ciphertext = new byte[joined.Length - 32 - 17];
            Array.Copy(joined, 17, ciphertext, 0, joined.Length - 32 - 17);
            byte[] ivAndCiphertext = new byte[joined.Length - 32];
            Array.Copy(joined, ivAndCiphertext, joined.Length - 32);
            byte[] mac = new byte[32];
            Array.Copy(joined, joined.Length - 32, mac, 0, 32);

            VerifyMac(parts[1], ivAndCiphertext, mac);
            return(ProvisionMessage.Parser.ParseFrom(Decrypt(parts[0], iv, ciphertext)));
        }
Beispiel #10
0
        /// <summary>
        /// Fetch a ProvisionMessage from the server.
        /// </summary>
        /// <param name="tempIdentity"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public async Task <SignalServiceProvisionMessage> GetProvisioningMessageAsync(IdentityKeyPair tempIdentity, CancellationToken?token = null)
        {
            if (token == null)
            {
                token = CancellationToken.None;
            }

            if (provisioningSocket == null)
            {
                throw new NullReferenceException($"{nameof(provisioningSocket)} is null. Maybe you forgot to call GetNewDeviceUuid?");
            }
            ProvisionMessage protoPm = await provisioningSocket.GetProvisioningMessageAsync(tempIdentity, token);

            string provisioningCode = protoPm.ProvisioningCode;

            byte[] publicKeyBytes = protoPm.IdentityKeyPublic.ToByteArray();
            if (publicKeyBytes.Length == 32)
            {
                byte[] type = { Curve.DJB_TYPE };
                publicKeyBytes = ByteUtil.combine(type, publicKeyBytes);
            }
            ECPublicKey publicKey = Curve.decodePoint(publicKeyBytes, 0);

            byte[]          privateKeyBytes = protoPm.IdentityKeyPrivate.ToByteArray();
            ECPrivateKey    privateKey      = Curve.decodePrivatePoint(privateKeyBytes);
            IdentityKeyPair identity        = new IdentityKeyPair(new IdentityKey(publicKey), privateKey);

            return(new SignalServiceProvisionMessage()
            {
                Number = protoPm.Number,
                Identity = identity,
                Code = protoPm.ProvisioningCode
            });
        }
Beispiel #11
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));
            }
        }
Beispiel #12
0
        public ProvisionMessage GetProvisioningMessage(IdentityKeyPair tmpIdentity)
        {
            byte[]           raw = IncomingRequests.Take(Token);
            WebSocketMessage msg = WebSocketMessage.Parser.ParseFrom(raw);

            return(new ProvisioningCipher(null).Decrypt(tmpIdentity, msg.Request.Body.ToByteArray()));
        }
        public DeviceConsistencyMessage(DeviceConsistencyCommitment commitment, IdentityKeyPair identityKeyPair)
        {
            try
            {
                byte[] signatureBytes = Curve.calculateVrfSignature(identityKeyPair.getPrivateKey(), commitment.toByteArray());
                byte[] vrfOutputBytes = Curve.verifyVrfSignature(identityKeyPair.getPublicKey().getPublicKey(), commitment.toByteArray(), signatureBytes);

                this.generation = commitment.getGeneration();
                this.signature  = new DeviceConsistencySignature(signatureBytes, vrfOutputBytes);
                this.serialized = new DeviceConsistencyCodeMessage
                {
                    Generation = (uint)commitment.getGeneration(),
                    Signature  = ByteString.CopyFrom(signature.getSignature())
                }.ToByteArray();
            }
            catch (InvalidKeyException e)
            {
                Debug.Assert(false);
                throw e;
            }
            catch (VrfSignatureVerificationFailedException e)
            {
                Debug.Assert(false);
                throw e;
            }
        }
Beispiel #14
0
        /// <summary>
        /// Generate a signed PreKey
        /// </summary>
        /// <param name="identityKeyPair">The local client's identity key pair.</param>
        /// <param name="signedPreKeyId">The PreKey id to assign the generated signed PreKey</param>
        /// <returns>the generated signed PreKey</returns>
        /// <exception cref="InvalidKeyException">when the provided identity key is invalid</exception>
        public static SignedPreKeyRecord generateSignedPreKey(IdentityKeyPair identityKeyPair, uint signedPreKeyId)
        {
            ECKeyPair keyPair = Curve.generateKeyPair();

            byte[] signature = Curve.calculateSignature(identityKeyPair.getPrivateKey(), keyPair.getPublicKey().serialize());

            return(new SignedPreKeyRecord(signedPreKeyId, getTime(), keyPair, signature));
        }
Beispiel #15
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();
 }
Beispiel #16
0
        public static SignedPreKeyRecord GenerateSignedPreKey(IdentityKeyPair identityKeyPair, UInt32 signedPreKeyId)
        {
            var keyPair   = Curve.GenerateKeyPair();
            var signature = Curve.CalculateSignature(identityKeyPair.PrivateKey, keyPair.PublicKey.Serialize());

            var Jan1st1970 = new DateTime
                (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

            return new SignedPreKeyRecord(signedPreKeyId, (long)(DateTime.UtcNow - Jan1st1970).TotalMilliseconds, keyPair, signature);
        }
Beispiel #17
0
        public async Task <ProvisionMessage> GetProvisioningMessageAsync(IdentityKeyPair tmpIdentity, CancellationToken?token = null)
        {
            if (token == null)
            {
                token = CancellationToken.None;
            }

            var msg = await TakeAsync(token);

            return(new ProvisioningCipher(null !).Decrypt(tmpIdentity, msg.Request.Body.ToByteArray()));
        }
Beispiel #18
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;
            }));
        }
Beispiel #19
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);
        }
Beispiel #20
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);
            // });
        }
        public void Test_CryptoUtils_GenOmemoFingerprint()
        {
            string identKeyPairSerializedHex = "0a210511dbad7fcece74492f390f0a2a8387c543e802ab7f2176e303e28840559c41521220a082ae07fd8941536457cb2f3e4b560a87991d380f02af460b5204e46ca7b15a";

            byte[]          identKeyPairSerialized = CryptoUtils.hexStringToByteArray(identKeyPairSerializedHex);
            IdentityKeyPair identKeyPair           = new IdentityKeyPair(identKeyPairSerialized);

            string outputRef = "11dbad7f cece7449 2f390f0a 2a8387c5 43e802ab 7f2176e3 03e28840 559c4152";
            string output    = CryptoUtils.generateOmemoFingerprint(identKeyPair.getPublicKey(), false);

            Assert.AreEqual(outputRef, output);
        }
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public IdentityKeyPair GetIdentityKeyPair()
        {
            IdentityKeyPair  result = null;
            IdentitiesObject identity;

            IdentitiesObjectDic.TryGetValue("-1", out identity);
            if (identity != null)
            {
                result = new IdentityKeyPair(new IdentityKey(new DjbECPublicKey(identity.PublicKey)), new DjbECPrivateKey(identity.PrivateKey));
            }

            return(result);
        }
        public void StoreLocalData(uint registrationId, IdentityKeyPair identityKey)
        {
            IdentityKeysRepository identityKeysRepository = new IdentityKeysRepository();
            IdentityKeys           newKeys = new IdentityKeys()
            {
                RecipientId    = "-1",
                RegistrationId = Convert.ToString(registrationId),
                PublicKey      = identityKey.GetPublicKey().Serialize(),
                PrivateKey     = identityKey.GetPrivateKey().Serialize()
            };

            identityKeysRepository.Save(newKeys);
        }
        // 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));
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="registrationId"></param>
        /// <param name="identityKey"></param>
        public void StoreLocalData(uint registrationId, IdentityKeyPair identityKey)
        {
            if (IdentitiesObjectDic.ContainsKey("-1"))
            {
                IdentitiesObjectDic.Remove("-1");
            }

            IdentitiesObjectDic.Add("-1", new IdentitiesObject()
            {
                RecipientId    = "-1",
                RegistrationId = registrationId.ToString(),
                PublicKey      = identityKey.GetPublicKey().Serialize(),
                PrivateKey     = identityKey.GetPrivateKey().Serialize()
            });
        }
Beispiel #27
0
        protected override string Execute()
        {
            if (TextSecurePreferences.isSignedPreKeyRegistered())
            {
                Log.Warn("Signed prekey already registered...");
                return("");
            }

            IdentityKeyPair identityKeyPair    = IdentityKeyUtil.GetIdentityKeyPair();
            var             signedPreKeyRecord = PreKeyUtil.generateSignedPreKey(identityKeyPair);

            App.Current.accountManager.setSignedPreKey(signedPreKeyRecord);
            TextSecurePreferences.setSignedPreKeyRegistered(true);

            return("");
        }
        public async void addDevice(string deviceIdentifier,
                                    ECPublicKey deviceKey,
                                    IdentityKeyPair identityKeyPair,
                                    string code)//throws InvalidKeyException, IOException
        {
            ProvisioningCipher cipher  = new ProvisioningCipher(deviceKey);
            ProvisionMessage   message = ProvisionMessage.CreateBuilder()
                                         .SetIdentityKeyPublic(ByteString.CopyFrom(identityKeyPair.getPublicKey().serialize()))
                                         .SetIdentityKeyPrivate(ByteString.CopyFrom(identityKeyPair.getPrivateKey().serialize()))
                                         .SetNumber(user)
                                         .SetProvisioningCode(code)
                                         .Build();

            byte[] ciphertext = cipher.encrypt(message);
            await this.pushServiceSocket.sendProvisioningMessage(deviceIdentifier, ciphertext);
        }
Beispiel #29
0
        public void testDeviceConsistency()
        {
            IdentityKeyPair deviceOne   = KeyHelper.generateIdentityKeyPair();
            IdentityKeyPair deviceTwo   = KeyHelper.generateIdentityKeyPair();
            IdentityKeyPair deviceThree = KeyHelper.generateIdentityKeyPair();

            List <IdentityKey> keyList = new List <IdentityKey>(new[]
            {
                deviceOne.getPublicKey(),
                deviceTwo.getPublicKey(),
                deviceThree.getPublicKey()
            });

            Random random = new Random();

            HelperMethods.Shuffle(keyList, random);
            DeviceConsistencyCommitment deviceOneCommitment = new DeviceConsistencyCommitment(1, keyList);

            HelperMethods.Shuffle(keyList, random);
            DeviceConsistencyCommitment deviceTwoCommitment = new DeviceConsistencyCommitment(1, keyList);

            HelperMethods.Shuffle(keyList, random);
            DeviceConsistencyCommitment deviceThreeCommitment = new DeviceConsistencyCommitment(1, keyList);

            CollectionAssert.AreEqual(deviceOneCommitment.toByteArray(), deviceTwoCommitment.toByteArray());
            CollectionAssert.AreEqual(deviceTwoCommitment.toByteArray(), deviceThreeCommitment.toByteArray());

            DeviceConsistencyMessage deviceOneMessage   = new DeviceConsistencyMessage(deviceOneCommitment, deviceOne);
            DeviceConsistencyMessage deviceTwoMessage   = new DeviceConsistencyMessage(deviceOneCommitment, deviceTwo);
            DeviceConsistencyMessage deviceThreeMessage = new DeviceConsistencyMessage(deviceOneCommitment, deviceThree);

            DeviceConsistencyMessage receivedDeviceOneMessage   = new DeviceConsistencyMessage(deviceOneCommitment, deviceOneMessage.getSerialized(), deviceOne.getPublicKey());
            DeviceConsistencyMessage receivedDeviceTwoMessage   = new DeviceConsistencyMessage(deviceOneCommitment, deviceTwoMessage.getSerialized(), deviceTwo.getPublicKey());
            DeviceConsistencyMessage receivedDeviceThreeMessage = new DeviceConsistencyMessage(deviceOneCommitment, deviceThreeMessage.getSerialized(), deviceThree.getPublicKey());

            CollectionAssert.AreEqual(deviceOneMessage.getSignature().getVrfOutput(), receivedDeviceOneMessage.getSignature().getVrfOutput());
            CollectionAssert.AreEqual(deviceTwoMessage.getSignature().getVrfOutput(), receivedDeviceTwoMessage.getSignature().getVrfOutput());
            CollectionAssert.AreEqual(deviceThreeMessage.getSignature().getVrfOutput(), receivedDeviceThreeMessage.getSignature().getVrfOutput());

            string codeOne   = generateCode(deviceOneCommitment, deviceOneMessage, receivedDeviceTwoMessage, receivedDeviceThreeMessage);
            string codeTwo   = generateCode(deviceTwoCommitment, deviceTwoMessage, receivedDeviceThreeMessage, receivedDeviceOneMessage);
            string codeThree = generateCode(deviceThreeCommitment, deviceThreeMessage, receivedDeviceTwoMessage, receivedDeviceOneMessage);

            Assert.AreEqual(codeOne, codeTwo);
            Assert.AreEqual(codeTwo, codeThree);
        }
        BobSignalProtocolParameters(IdentityKeyPair ourIdentityKey, EcKeyPair ourSignedPreKey,
                                    EcKeyPair ourRatchetKey, May <EcKeyPair> ourOneTimePreKey,
                                    IdentityKey theirIdentityKey, IEcPublicKey theirBaseKey)
        {
            _ourIdentityKey   = ourIdentityKey;
            _ourSignedPreKey  = ourSignedPreKey;
            _ourRatchetKey    = ourRatchetKey;
            _ourOneTimePreKey = ourOneTimePreKey;
            _theirIdentityKey = theirIdentityKey;
            _theirBaseKey     = theirBaseKey;

            if (ourIdentityKey == null || ourSignedPreKey == null || ourRatchetKey == null ||
                ourOneTimePreKey == null || theirIdentityKey == null || theirBaseKey == null)
            {
                throw new Exception("Null value!");
            }
        }
        BobAxolotlParameters(IdentityKeyPair ourIdentityKey, ECKeyPair ourSignedPreKey,
                             ECKeyPair ourRatchetKey, May<ECKeyPair> ourOneTimePreKey,
                             IdentityKey theirIdentityKey, ECPublicKey theirBaseKey)
        {
            this.ourIdentityKey = ourIdentityKey;
            this.ourSignedPreKey = ourSignedPreKey;
            this.ourRatchetKey = ourRatchetKey;
            this.ourOneTimePreKey = ourOneTimePreKey;
            this.theirIdentityKey = theirIdentityKey;
            this.theirBaseKey = theirBaseKey;

            if (ourIdentityKey == null || ourSignedPreKey == null || ourRatchetKey == null ||
                ourOneTimePreKey == null || theirIdentityKey == null || theirBaseKey == null)
            {
                throw new Exception("Null value!");
            }
        }
        SymmetricSignalProtocolParameters(ECKeyPair ourBaseKey, ECKeyPair ourRatchetKey,
                                          IdentityKeyPair ourIdentityKey, ECPublicKey theirBaseKey,
                                          ECPublicKey theirRatchetKey, IdentityKey theirIdentityKey)
        {
            this.ourBaseKey       = ourBaseKey;
            this.ourRatchetKey    = ourRatchetKey;
            this.ourIdentityKey   = ourIdentityKey;
            this.theirBaseKey     = theirBaseKey;
            this.theirRatchetKey  = theirRatchetKey;
            this.theirIdentityKey = theirIdentityKey;

            if (ourBaseKey == null || ourRatchetKey == null || ourIdentityKey == null ||
                theirBaseKey == null || theirRatchetKey == null || theirIdentityKey == null)
            {
                throw new Exception("Null values!");
            }
        }
  SymmetricAxolotlParameters(ECKeyPair ourBaseKey, ECKeyPair ourRatchetKey,
                             IdentityKeyPair ourIdentityKey, ECPublicKey theirBaseKey,
                             ECPublicKey theirRatchetKey, IdentityKey theirIdentityKey)
        {
            this.ourBaseKey = ourBaseKey;
            this.ourRatchetKey = ourRatchetKey;
            this.ourIdentityKey = ourIdentityKey;
            this.theirBaseKey = theirBaseKey;
            this.theirRatchetKey = theirRatchetKey;
            this.theirIdentityKey = theirIdentityKey;

            if (ourBaseKey == null || ourRatchetKey == null || ourIdentityKey == null ||
                theirBaseKey == null || theirRatchetKey == null || theirIdentityKey == null)
            {
                throw new Exception("Null values!");
            }
        }
        public AliceAxolotlParameters(IdentityKeyPair ourIdentityKey, ECKeyPair ourBaseKey,
		                               IdentityKey theirIdentityKey, ECPublicKey theirSignedPreKey,
		                               ECPublicKey theirRatchetKey, Maybe<ECPublicKey> theirOneTimePreKey)
        {
            OurIdentityKey = ourIdentityKey;
            OurBaseKey = ourBaseKey;
            TheirIdentityKey = theirIdentityKey;
            TheirSignedPreKey = theirSignedPreKey;
            TheirRatchetKey = theirRatchetKey;
            TheirOneTimePreKey = theirOneTimePreKey;

            if (ourIdentityKey == null || ourBaseKey == null || theirIdentityKey == null ||
                theirSignedPreKey == null || theirRatchetKey == null)
            {

                throw new Exception ("Null values!");
            }
        }
Beispiel #35
0
        /**
         * Generate a signed PreKey
         *
         * @param identityKeyPair The local client's identity key pair.
         * @param signedPreKeyId The PreKey id to assign the generated signed PreKey
         *
         * @return the generated signed PreKey
         * @throws InvalidKeyException when the provided identity key is invalid
         */
        public static SignedPreKeyRecord generateSignedPreKey(IdentityKeyPair identityKeyPair, uint signedPreKeyId)
        {
            ECKeyPair keyPair = Curve.generateKeyPair();
            byte[] signature = Curve.calculateSignature(identityKeyPair.getPrivateKey(), keyPair.getPublicKey().serialize());

            return new SignedPreKeyRecord(signedPreKeyId, getTime(), keyPair, signature);
        }
 public Builder setOurIdentityKey(IdentityKeyPair ourIdentityKey)
 {
     this.ourIdentityKey = ourIdentityKey;
     return this;
 }
Beispiel #37
0
        public void SetPendingKeyExchange(UInt32 sequence,
		                                  ECKeyPair ourBaseKey,
		                                  ECKeyPair ourRatchetKey,
		                                  IdentityKeyPair ourIdentityKey)
        {
            var structure = new PendingKeyExchange {
                Sequence = sequence,
                LocalBaseKey = ourBaseKey.PublicKey.Serialize(),
                LocalBaseKeyPrivate = ourBaseKey.PrivateKey.Serialize(),
                LocalRatchetKey = ourRatchetKey.PublicKey.Serialize(),
                LocalRatchetKeyPrivate = ourRatchetKey.PrivateKey.Serialize(),
                LocalIdentityKey = ourIdentityKey.PublicKey.Serialize(),
                LocalIdentityKeyPrivate = ourIdentityKey.PrivateKey.Serialize()
            };

            Structure.PendKeyExchange = structure;
        }
 public Builder SetOurIdentityKey(IdentityKeyPair ourIdentityKey)
 {
     _ourIdentityKey = ourIdentityKey;
     return this;
 }
 public InMemoryAxolotlStore(IdentityKeyPair identityKeyPair, uint registrationId)
 {
     this.identityKeyStore = new InMemoryIdentityKeyStore(identityKeyPair, registrationId);
 }
		public void setPendingKeyExchange(uint sequence,
										  ECKeyPair ourBaseKey,
										  ECKeyPair ourRatchetKey,
										  IdentityKeyPair ourIdentityKey)
		{
			PendingKeyExchange structure =
				PendingKeyExchange.CreateBuilder()
								  .SetSequence(sequence)
								  .SetLocalBaseKey(ByteString.CopyFrom(ourBaseKey.getPublicKey().serialize()))
								  .SetLocalBaseKeyPrivate(ByteString.CopyFrom(ourBaseKey.getPrivateKey().serialize()))
								  .SetLocalRatchetKey(ByteString.CopyFrom(ourRatchetKey.getPublicKey().serialize()))
								  .SetLocalRatchetKeyPrivate(ByteString.CopyFrom(ourRatchetKey.getPrivateKey().serialize()))
								  .SetLocalIdentityKey(ByteString.CopyFrom(ourIdentityKey.getPublicKey().serialize()))
								  .SetLocalIdentityKeyPrivate(ByteString.CopyFrom(ourIdentityKey.getPrivateKey().serialize()))
								  .Build();

			this.sessionStructure = this.sessionStructure.ToBuilder()
														 .SetPendingKeyExchange(structure)
														 .Build();
		}
		/// <summary>
		/// .ctor
		/// </summary>
		public InMemoryIdentityKeyStore(IdentityKeyPair identityKeyPair, uint localRegistrationId)
		{
			this.identityKeyPair = identityKeyPair;
			this.localRegistrationId = localRegistrationId;
		}
 public InMemoryAxolotlStore(IdentityKeyPair identityKeyPair, UInt32 registrationId)
 {
     _identityKeyStore = new InMemoryIdentityKeyStore(identityKeyPair, registrationId);
 }
 public InMemoryIdentityKeyStore(IdentityKeyPair identityKeyPair, UInt32 localRegistrationId)
 {
     _trustedKeys = new Dictionary<string, IdentityKey> ();
     _identityKeyPair = identityKeyPair;
     _localRegistrationId = localRegistrationId;
 }