public PreKeySignalMessage(uint messageVersion, uint registrationId, May <uint> preKeyId,
                                   uint signedPreKeyId, ECPublicKey baseKey, IdentityKey identityKey,
                                   SignalMessage message)
        {
            this.version        = messageVersion;
            this.registrationId = registrationId;
            this.preKeyId       = preKeyId;
            this.signedPreKeyId = signedPreKeyId;
            this.baseKey        = baseKey;
            this.identityKey    = identityKey;
            this.message        = message;

            PreKeySignalMessage preKeySignalMessage = new PreKeySignalMessage
            {
                SignedPreKeyId = signedPreKeyId,
                BaseKey        = ByteString.CopyFrom(baseKey.serialize()),
                IdentityKey    = ByteString.CopyFrom(identityKey.serialize()),
                Message        = ByteString.CopyFrom(message.serialize()),
                RegistrationId = registrationId
            };

            if (preKeyId.HasValue)                                       // .isPresent()
            {
                preKeySignalMessage.PreKeyId = preKeyId.ForceGetValue(); // get()
            }

            byte[] versionBytes = { ByteUtil.intsToByteHighAndLow((int)this.version, (int)CURRENT_VERSION) };
            byte[] messageBytes = preKeySignalMessage.ToByteArray();

            this.serialized = ByteUtil.combine(versionBytes, messageBytes);
        }
        private SenderCertificate CreateCertificateFor(ECKeyPair trustRoot, String sender, int deviceId, ECPublicKey identityKey, long expires)
        {
            ECKeyPair serverKey = Curve.generateKeyPair();

            byte[] serverCertificateBytes = new libsignalmetadata.protobuf.ServerCertificate.Types.Certificate()
            {
                Id  = 1,
                Key = ByteString.CopyFrom(serverKey.getPublicKey().serialize())
            }.ToByteArray();

            byte[] serverCertificateSignature = Curve.calculateSignature(trustRoot.getPrivateKey(), serverCertificateBytes);

            ServerCertificate serverCertificate = new ServerCertificate(new libsignalmetadata.protobuf.ServerCertificate()
            {
                Certificate = ByteString.CopyFrom(serverCertificateBytes),
                Signature   = ByteString.CopyFrom(serverCertificateSignature)
            }.ToByteArray());

            byte[] senderCertificateBytes = new libsignalmetadata.protobuf.SenderCertificate.Types.Certificate
            {
                Sender       = sender,
                SenderDevice = (uint)deviceId,
                IdentityKey  = ByteString.CopyFrom(identityKey.serialize()),
                Expires      = (ulong)expires,
                Signer       = libsignalmetadata.protobuf.ServerCertificate.Parser.ParseFrom(serverCertificate.Serialized)
            }.ToByteArray();

            byte[] senderCertificateSignature = Curve.calculateSignature(serverKey.getPrivateKey(), senderCertificateBytes);

            return(new SenderCertificate(new libsignalmetadata.protobuf.SenderCertificate()
            {
                Certificate = ByteString.CopyFrom(senderCertificateBytes),
                Signature = ByteString.CopyFrom(senderCertificateSignature)
            }.ToByteArray()));
        }
        private SenderKeyState(uint id, uint iteration, byte[] chainKey,
                               ECPublicKey signatureKeyPublic,
                               May <ECPrivateKey> signatureKeyPrivate)
        {
            SenderKeyStateStructure.Types.SenderChainKey senderChainKeyStructure =
                SenderKeyStateStructure.Types.SenderChainKey.CreateBuilder()
                .SetIteration(iteration)
                .SetSeed(ByteString.CopyFrom(chainKey))
                .Build();

            SenderKeyStateStructure.Types.SenderSigningKey.Builder signingKeyStructure =
                SenderKeyStateStructure.Types.SenderSigningKey.CreateBuilder()
                .SetPublic(ByteString.CopyFrom(signatureKeyPublic.serialize()));

            if (signatureKeyPrivate.HasValue)
            {
                signingKeyStructure.SetPrivate(ByteString.CopyFrom(signatureKeyPrivate.ForceGetValue().serialize()));
            }

            this.senderKeyStateStructure = SenderKeyStateStructure.CreateBuilder()
                                           .SetSenderKeyId(id)
                                           .SetSenderChainKey(senderChainKeyStructure)
                                           .SetSenderSigningKey(signingKeyStructure)
                                           .Build();
        }
        public KeyExchangeMessage(uint messageVersion, uint sequence, uint flags,
                                  ECPublicKey baseKey, byte[] baseKeySignature,
                                  ECPublicKey ratchetKey,
                                  IdentityKey identityKey)
        {
            this.supportedVersion = CiphertextMessage.CURRENT_VERSION;
            this.version = messageVersion;
            this.sequence = sequence;
            this.flags = flags;
            this.baseKey = baseKey;
            this.baseKeySignature = baseKeySignature;
            this.ratchetKey = ratchetKey;
            this.identityKey = identityKey;

            byte[] version = { ByteUtil.intsToByteHighAndLow((int)this.version, (int)this.supportedVersion) };
            WhisperProtos.KeyExchangeMessage.Builder builder = WhisperProtos.KeyExchangeMessage
                                           .CreateBuilder()
                                           .SetId((sequence << 5) | flags) //(sequence << 5) | flags
                                           .SetBaseKey(ByteString.CopyFrom(baseKey.serialize()))
                                           .SetRatchetKey(ByteString.CopyFrom(ratchetKey.serialize()))
                                           .SetIdentityKey(ByteString.CopyFrom(identityKey.serialize()));

            if (messageVersion >= 3)
            {
                builder.SetBaseKeySignature(ByteString.CopyFrom(baseKeySignature));
            }

            this.serialized = ByteUtil.combine(version, builder.Build().ToByteArray());
        }
Example #5
0
        public PreKeySignalMessage(uint messageVersion, uint registrationId, May <uint> preKeyId,
                                   uint signedPreKeyId, ECPublicKey baseKey, IdentityKey identityKey,
                                   SignalMessage message)
        {
            this.version        = messageVersion;
            this.registrationId = registrationId;
            this.preKeyId       = preKeyId;
            this.signedPreKeyId = signedPreKeyId;
            this.baseKey        = baseKey;
            this.identityKey    = identityKey;
            this.message        = message;

            WhisperProtos.PreKeySignalMessage.Builder builder =
                WhisperProtos.PreKeySignalMessage.CreateBuilder()
                .SetSignedPreKeyId(signedPreKeyId)
                .SetBaseKey(ByteString.CopyFrom(baseKey.serialize()))
                .SetIdentityKey(ByteString.CopyFrom(identityKey.serialize()))
                .SetMessage(ByteString.CopyFrom(message.serialize()))
                .SetRegistrationId(registrationId);

            if (preKeyId.HasValue)                             // .isPresent()
            {
                builder.SetPreKeyId(preKeyId.ForceGetValue()); // get()
            }

            byte[] versionBytes = { ByteUtil.intsToByteHighAndLow((int)this.version, (int)CURRENT_VERSION) };
            byte[] messageBytes = builder.Build().ToByteArray();

            this.serialized = ByteUtil.combine(versionBytes, messageBytes);
        }
Example #6
0
        public SignalMessage(uint messageVersion, byte[] macKey, ECPublicKey senderRatchetKey,
                             uint counter, uint previousCounter, byte[] ciphertext,
                             IdentityKey senderIdentityKey,
                             IdentityKey receiverIdentityKey)
        {
            byte[] version = { ByteUtil.intsToByteHighAndLow((int)messageVersion, (int)CURRENT_VERSION) };
            byte[] message = new SignalMessage
            {
                ratchedKeyOneofCase_ = RatchedKeyOneofOneofCase.RatchetKey,
                RatchetKey           = ByteString.CopyFrom(senderRatchetKey.serialize()), //TODO serialize ok?
                counterOneofCase_    = CounterOneofOneofCase.Counter,
                Counter = counter,
                previousCounterOneofCase_ = PreviousCounterOneofOneofCase.PreviousCounter,
                PreviousCounter           = previousCounter,
                ciphertextOneofCase_      = CiphertextOneofOneofCase.Ciphertext,
                Ciphertext = ByteString.CopyFrom(ciphertext),
            }.ToByteArray();

            byte[] mac = getMac(senderIdentityKey, receiverIdentityKey, macKey, ByteUtil.combine(version, message));

            this.serialized       = ByteUtil.combine(version, message, mac);
            this.senderRatchetKey = senderRatchetKey;
            this.counter          = counter;
            this.previousCounter  = previousCounter;
            this.ciphertext       = ciphertext;
            this.messageVersion   = messageVersion;
        }
Example #7
0
        private SenderKeyState(uint id, uint iteration, byte[] chainKey,
                              ECPublicKey signatureKeyPublic,
                              May<ECPrivateKey> signatureKeyPrivate)
        {
            SenderKeyStateStructure.Types.SenderChainKey senderChainKeyStructure =
                SenderKeyStateStructure.Types.SenderChainKey.CreateBuilder()
                                                      .SetIteration(iteration)
                                                      .SetSeed(ByteString.CopyFrom(chainKey))
                                                      .Build();

            SenderKeyStateStructure.Types.SenderSigningKey.Builder signingKeyStructure =
                SenderKeyStateStructure.Types.SenderSigningKey.CreateBuilder()
                                                        .SetPublic(ByteString.CopyFrom(signatureKeyPublic.serialize()));

            if (signatureKeyPrivate.HasValue)
            {
                signingKeyStructure.SetPrivate(ByteString.CopyFrom(signatureKeyPrivate.ForceGetValue().serialize()));
            }

            this.senderKeyStateStructure = SenderKeyStateStructure.CreateBuilder()
                                                                  .SetSenderKeyId(id)
                                                                  .SetSenderChainKey(senderChainKeyStructure)
                                                                  .SetSenderSigningKey(signingKeyStructure)
                                                                  .Build();
        }
        public PreKeyWhisperMessage(uint messageVersion, uint registrationId, May<uint> preKeyId,
                                    uint signedPreKeyId, ECPublicKey baseKey, IdentityKey identityKey,
                                    WhisperMessage message)
        {
            this.version = messageVersion;
            this.registrationId = registrationId;
            this.preKeyId = preKeyId;
            this.signedPreKeyId = signedPreKeyId;
            this.baseKey = baseKey;
            this.identityKey = identityKey;
            this.message = message;

            WhisperProtos.PreKeyWhisperMessage.Builder builder =
                WhisperProtos.PreKeyWhisperMessage.CreateBuilder()
                                                  .SetSignedPreKeyId(signedPreKeyId)
                                                  .SetBaseKey(ByteString.CopyFrom(baseKey.serialize()))
                                                  .SetIdentityKey(ByteString.CopyFrom(identityKey.serialize()))
                                                  .SetMessage(ByteString.CopyFrom(message.serialize()))
                                                  .SetRegistrationId(registrationId);

            if (preKeyId.HasValue) // .isPresent()
            {
                builder.SetPreKeyId(preKeyId.ForceGetValue()); // get()
            }

            byte[] versionBytes = { ByteUtil.intsToByteHighAndLow((int)this.version, (int)CURRENT_VERSION) };
            byte[] messageBytes = builder.Build().ToByteArray();

            this.serialized = ByteUtil.combine(versionBytes, messageBytes);
        }
        private SenderKeyState(uint id, uint iteration, byte[] chainKey,
                               ECPublicKey signatureKeyPublic,
                               May <ECPrivateKey> signatureKeyPrivate)
        {
            SenderKeyStateStructure.Types.SenderChainKey senderChainKeyStructure = new SenderKeyStateStructure.Types.SenderChainKey
            {
                Iteration = iteration,
                Seed      = ByteString.CopyFrom(chainKey)
            };

            SenderKeyStateStructure.Types.SenderSigningKey signingKeyStructure = new SenderKeyStateStructure.Types.SenderSigningKey
            {
                Public = ByteString.CopyFrom(signatureKeyPublic.serialize())
            };

            if (signatureKeyPrivate.HasValue)
            {
                signingKeyStructure.Private = ByteString.CopyFrom(signatureKeyPrivate.ForceGetValue().serialize());
            }

            this.senderKeyStateStructure = new SenderKeyStateStructure
            {
                SenderKeyId      = id,
                SenderChainKey   = senderChainKeyStructure,
                SenderSigningKey = signingKeyStructure
            };
        }
Example #10
0
        //--------------------------------------------------------Attributes:-----------------------------------------------------------------\\
        #region --Attributes--


        #endregion
        //--------------------------------------------------------Constructor:----------------------------------------------------------------\\
        #region --Constructors--


        #endregion
        //--------------------------------------------------------Set-, Get- Methods:---------------------------------------------------------\\
        #region --Set-, Get- Methods--
        /// <summary>
        /// Reads the raw key from the given ECPublicKey.
        /// Based on: https://github.com/langboost/libsignal-protocol-pcl/blob/ef9dece1283948f89c7cc4c5825f944f77ed2c3e/signal-protocol-pcl/ecc/Curve.cs#L37
        /// </summary>
        /// <param name="key">The public key you want to retrieve the raw key from.</param>
        /// <returns>Returns the raw key from the given ECPublicKey.</returns>
        public static byte[] getRawFromECPublicKey(ECPublicKey key)
        {
            byte[] keySerialized = key.serialize();
            byte[] keyRaw        = new byte[32];
            System.Buffer.BlockCopy(keySerialized, keySerialized.Length - keyRaw.Length, keyRaw, 0, keyRaw.Length);

            return(keyRaw);
        }
Example #11
0
        public void Test_Libsignal_Pre_key_Serialize_Deserialize_1()
        {
            IList <PreKeyRecord> alicePreKeys = CryptoUtils.generateOmemoPreKeys();

            byte[] pubKey = alicePreKeys[0].getKeyPair().getPublicKey().serialize();

            ECPublicKey key = Curve.decodePoint(pubKey, 0);

            Assert.IsTrue(key.serialize().SequenceEqual(pubKey));
        }
Example #12
0
        public void TestDecodeSize()
        {
            ECKeyPair keyPair = Curve.generateKeyPair();

            byte[] serializedPublic = keyPair.getPublicKey().serialize();

            ECPublicKey justRight = Curve.decodePoint(serializedPublic, 0);

            try
            {
                ECPublicKey tooSmall = Curve.decodePoint(serializedPublic, 1);
                Assert.Fail("Shouldn't decode");
            }
            catch (InvalidKeyException e)
            {
                // good
            }

            try
            {
                ECPublicKey empty = Curve.decodePoint(new byte[0], 0);
                Assert.Fail("Shouldn't parse");
            }
            catch (InvalidKeyException e)
            {
                // good
            }

            try
            {
                byte[] badKeyType = new byte[33];
                Array.Copy(serializedPublic, 0, badKeyType, 0, serializedPublic.Length);
                badKeyType[0] = 0x01;
                Curve.decodePoint(badKeyType, 0);
                Assert.Fail("Should be bad key type");
            }
            catch (InvalidKeyException e)
            {
                // good
            }

            byte[] extraSpace = new byte[serializedPublic.Length + 1];
            Array.Copy(serializedPublic, 0, extraSpace, 0, serializedPublic.Length);
            ECPublicKey extra = Curve.decodePoint(extraSpace, 0);

            byte[] offsetSpace = new byte[serializedPublic.Length + 1];
            Array.Copy(serializedPublic, 0, offsetSpace, 1, serializedPublic.Length);
            ECPublicKey offset = Curve.decodePoint(offsetSpace, 1);

            CollectionAssert.AreEqual(serializedPublic, justRight.serialize());
            CollectionAssert.AreEqual(extra.serialize(), serializedPublic);
            CollectionAssert.AreEqual(offset.serialize(), serializedPublic);
        }
Example #13
0
        public void setUnacknowledgedPreKeyMessage(May <uint> preKeyId, uint signedPreKeyId, ECPublicKey baseKey)
        {
            PendingPreKey.Builder pending = PendingPreKey.CreateBuilder()
                                            .SetSignedPreKeyId(signedPreKeyId)
                                            .SetBaseKey(ByteString.CopyFrom(baseKey.serialize()));

            if (preKeyId.HasValue)
            {
                pending.SetPreKeyId(preKeyId.ForceGetValue());
            }

            this.sessionStructure = this.sessionStructure.ToBuilder()
                                    .SetPendingPreKey(pending.Build())
                                    .Build();
        }
        public void setUnacknowledgedPreKeyMessage(May <uint> preKeyId, uint signedPreKeyId, ECPublicKey baseKey)
        {
            PendingPreKey pending = new PendingPreKey
            {
                SignedPreKeyId = (int)signedPreKeyId,
                BaseKey        = ByteString.CopyFrom(baseKey.serialize())
            };

            if (preKeyId.HasValue)
            {
                pending.PreKeyId = preKeyId.ForceGetValue();
            }

            this.sessionStructure.PendingPreKey = pending;
        }
Example #15
0
        public UnidentifiedSenderMessage(ECPublicKey ephemeral, byte[] encryptedStatic, byte[] encryptedMessage)
        {
            Version          = CIPHERTEXT_VERSION;
            Ephemeral        = ephemeral;
            EncryptedStatic  = encryptedStatic;
            EncryptedMessage = encryptedMessage;

            byte[] versionBytes = { ByteUtil.intsToByteHighAndLow(CIPHERTEXT_VERSION, CIPHERTEXT_VERSION) };
            byte[] messageBytes = new libsignalmetadata.protobuf.UnidentifiedSenderMessage()
            {
                EncryptedMessage = ByteString.CopyFrom(encryptedMessage),
                EncryptedStatic  = ByteString.CopyFrom(encryptedStatic),
                EphemeralPublic  = ByteString.CopyFrom(ephemeral.serialize())
            }.ToByteArray();
            this.Serialized = ByteUtil.combine(versionBytes, messageBytes);
        }
        public SenderKeyDistributionMessage(uint id, uint iteration, byte[] chainKey, ECPublicKey signatureKey)
        {
            byte[] version  = { ByteUtil.intsToByteHighAndLow((int)CURRENT_VERSION, (int)CURRENT_VERSION) };
            byte[] protobuf = WhisperProtos.SenderKeyDistributionMessage.CreateBuilder()
                              .SetId(id)
                              .SetIteration(iteration)
                              .SetChainKey(ByteString.CopyFrom(chainKey))
                              .SetSigningKey(ByteString.CopyFrom(signatureKey.serialize()))
                              .Build().ToByteArray();

            this.id           = id;
            this.iteration    = iteration;
            this.chainKey     = chainKey;
            this.signatureKey = signatureKey;
            this.serialized   = ByteUtil.combine(version, protobuf);
        }
        public SenderKeyDistributionMessage(uint id, uint iteration, byte[] chainKey, ECPublicKey signatureKey)
        {
            byte[] version = { ByteUtil.intsToByteHighAndLow((int)CURRENT_VERSION, (int)CURRENT_VERSION) };
            byte[] protobuf = WhisperProtos.SenderKeyDistributionMessage.CreateBuilder()
                                                                        .SetId(id)
                                                                        .SetIteration(iteration)
                                                                        .SetChainKey(ByteString.CopyFrom(chainKey))
                                                                        .SetSigningKey(ByteString.CopyFrom(signatureKey.serialize()))
                                                                        .Build().ToByteArray();

            this.id = id;
            this.iteration = iteration;
            this.chainKey = chainKey;
            this.signatureKey = signatureKey;
            this.serialized = ByteUtil.combine(version, protobuf);
        }
Example #18
0
        public SenderKeyDistributionMessage(uint id, uint iteration, byte[] chainKey, ECPublicKey signatureKey)
        {
            byte[] version  = { ByteUtil.intsToByteHighAndLow((int)CURRENT_VERSION, (int)CURRENT_VERSION) };
            byte[] protobuf = new SenderKeyDistributionMessage
            {
                Id         = id,
                Iteration  = iteration,
                ChainKey   = ByteString.CopyFrom(chainKey),
                SigningKey = ByteString.CopyFrom(signatureKey.serialize())
            }.ToByteArray();

            this.id           = id;
            this.iteration    = iteration;
            this.chainKey     = chainKey;
            this.signatureKey = signatureKey;
            this.serialized   = ByteUtil.combine(version, protobuf);
        }
Example #19
0
        public void addReceiverChain(ECPublicKey senderRatchetKey, ChainKey chainKey)
        {
            Chain.Types.ChainKey chainKeyStructure = Chain.Types.ChainKey.CreateBuilder()
                                                     .SetKey(ByteString.CopyFrom(chainKey.getKey()))
                                                     .SetIndex(chainKey.getIndex())
                                                     .Build();

            Chain chain = Chain.CreateBuilder()
                          .SetChainKey(chainKeyStructure)
                          .SetSenderRatchetKey(ByteString.CopyFrom(senderRatchetKey.serialize()))
                          .Build();

            this.sessionStructure = this.sessionStructure.ToBuilder().AddReceiverChains(chain).Build();

            if (this.sessionStructure.ReceiverChainsList.Count > 5)
            {
                this.sessionStructure = this.sessionStructure.ToBuilder() /*.ClearReceiverChains()*/.Build(); //RemoveReceiverChains(0) TODO: why does it work without
            }
        }
        public void addReceiverChain(ECPublicKey senderRatchetKey, ChainKey chainKey)
        {
            Chain.Types.ChainKey chainKeyStructure = Chain.Types.ChainKey.CreateBuilder()
                                                     .SetKey(ByteString.CopyFrom(chainKey.getKey()))
                                                     .SetIndex(chainKey.getIndex())
                                                     .Build();

            Chain chain = Chain.CreateBuilder()
                          .SetChainKey(chainKeyStructure)
                          .SetSenderRatchetKey(ByteString.CopyFrom(senderRatchetKey.serialize()))
                          .Build();

            sessionStructure = sessionStructure.ToBuilder().AddReceiverChains(chain).Build();

            if (sessionStructure.ReceiverChainsList.Count > 5)
            {
                sessionStructure = sessionStructure.ToBuilder().Build();
            }
        }
        public void addReceiverChain(ECPublicKey senderRatchetKey, ChainKey chainKey)
        {
            Chain.Types.ChainKey chainKeyStructure = new Chain.Types.ChainKey
            {
                Key   = ByteString.CopyFrom(chainKey.getKey()),
                Index = chainKey.getIndex()
            };

            Chain chain = new Chain
            {
                ChainKey         = chainKeyStructure,
                SenderRatchetKey = ByteString.CopyFrom(senderRatchetKey.serialize())
            };

            this.sessionStructure.ReceiverChains.Add(chain);

            while (this.sessionStructure.ReceiverChains.Count > 5)
            {
                this.sessionStructure.ReceiverChains.RemoveAt(0); //TODO why was here a TODO?
            }
        }
Example #22
0
        public WhisperMessage(uint messageVersion, byte[] macKey, ECPublicKey senderRatchetKey,
                              uint counter, uint previousCounter, byte[] ciphertext,
                              IdentityKey senderIdentityKey,
                              IdentityKey receiverIdentityKey)
        {
            byte[] version = { ByteUtil.intsToByteHighAndLow((int)messageVersion, (int)CURRENT_VERSION) };
            byte[] message = WhisperProtos.WhisperMessage.CreateBuilder()
                             .SetRatchetKey(ByteString.CopyFrom(senderRatchetKey.serialize()))
                             .SetCounter(counter)
                             .SetPreviousCounter(previousCounter)
                             .SetCiphertext(ByteString.CopyFrom(ciphertext))
                             .Build().ToByteArray();

            byte[] mac = getMac(messageVersion, senderIdentityKey, receiverIdentityKey, macKey,
                                ByteUtil.combine(version, message));

            this.serialized       = ByteUtil.combine(version, message, mac);
            this.senderRatchetKey = senderRatchetKey;
            this.counter          = counter;
            this.previousCounter  = previousCounter;
            this.ciphertext       = ciphertext;
            this.messageVersion   = messageVersion;
        }
Example #23
0
        public WhisperMessage(uint messageVersion, byte[] macKey, ECPublicKey senderRatchetKey,
                              uint counter, uint previousCounter, byte[] ciphertext,
                              IdentityKey senderIdentityKey,
                              IdentityKey receiverIdentityKey)
        {
            byte[] version = { ByteUtil.intsToByteHighAndLow((int)messageVersion, (int)CURRENT_VERSION) };
            byte[] message = WhisperProtos.WhisperMessage.CreateBuilder()
                                           .SetRatchetKey(ByteString.CopyFrom(senderRatchetKey.serialize()))
                                           .SetCounter(counter)
                                           .SetPreviousCounter(previousCounter)
                                           .SetCiphertext(ByteString.CopyFrom(ciphertext))
                                           .Build().ToByteArray();

            byte[] mac = getMac(messageVersion, senderIdentityKey, receiverIdentityKey, macKey,
                                    ByteUtil.combine(version, message));

            this.serialized = ByteUtil.combine(version, message, mac);
            this.senderRatchetKey = senderRatchetKey;
            this.counter = counter;
            this.previousCounter = previousCounter;
            this.ciphertext = ciphertext;
            this.messageVersion = messageVersion;
        }
Example #24
0
 public byte[] serialize()
 {
     return(publicKey.serialize());
 }
Example #25
0
        public byte[] Encrypt(SignalProtocolAddress destinationAddress, SenderCertificate senderCertificate, byte[] paddedPlaintext)
        {
            CiphertextMessage message       = new SessionCipher(SignalProtocolStore, destinationAddress).encrypt(paddedPlaintext);
            IdentityKeyPair   ourIdentity   = SignalProtocolStore.GetIdentityKeyPair();
            ECPublicKey       theirIdentity = SignalProtocolStore.GetIdentity(destinationAddress).getPublicKey();

            ECKeyPair ephemeral = Curve.generateKeyPair();

            byte[]        ephemeralSalt = ByteUtil.combine(Encoding.ASCII.GetBytes("UnidentifiedDelivery"), theirIdentity.serialize(), ephemeral.getPublicKey().serialize());
            EphemeralKeys ephemeralKeys = CalculateEphemeralKeys(theirIdentity, ephemeral.getPrivateKey(), ephemeralSalt);

            byte[] staticKeyCiphertext = Encrypt(ephemeralKeys.CipherKey, ephemeralKeys.MacKey, ourIdentity.getPublicKey().getPublicKey().serialize());

            byte[]     staticSalt = ByteUtil.combine(ephemeralKeys.ChainKey, staticKeyCiphertext);
            StaticKeys staticKeys = CalculateStaticKeys(theirIdentity, ourIdentity.getPrivateKey(), staticSalt);
            UnidentifiedSenderMessageContent content = new UnidentifiedSenderMessageContent((int)message.getType(), senderCertificate, message.serialize());

            byte[] messageBytes = Encrypt(staticKeys.CipherKey, staticKeys.MacKey, content.Serialized);

            return(new UnidentifiedSenderMessage(ephemeral.getPublicKey(), staticKeyCiphertext, messageBytes).Serialized);
        }
Example #26
0
        public void testSignature()
        {
            byte[] aliceIdentityPrivate =
            {
                0xc0, 0x97, 0x24, 0x84, 0x12,
                0xe5, 0x8b, 0xf0, 0x5d, 0xf4,
                0x87, 0x96, 0x82, 0x05, 0x13,
                0x27, 0x94, 0x17, 0x8e, 0x36,
                0x76, 0x37, 0xf5, 0x81, 0x8f,
                0x81, 0xe0, 0xe6, 0xce, 0x73,
                0xe8, 0x65
            };

            byte[] aliceIdentityPublic =
            {
                0x05, 0xab, 0x7e, 0x71, 0x7d,
                0x4a, 0x16, 0x3b, 0x7d, 0x9a,
                0x1d, 0x80, 0x71, 0xdf, 0xe9,
                0xdc, 0xf8, 0xcd, 0xcd, 0x1c,
                0xea, 0x33, 0x39, 0xb6, 0x35,
                0x6b, 0xe8, 0x4d, 0x88, 0x7e,
                0x32, 0x2c, 0x64
            };

            byte[] aliceEphemeralPublic =
            {
                0x05, 0xed, 0xce, 0x9d, 0x9c,
                0x41, 0x5c, 0xa7, 0x8c, 0xb7,
                0x25, 0x2e, 0x72, 0xc2, 0xc4,
                0xa5, 0x54, 0xd3, 0xeb, 0x29,
                0x48, 0x5a, 0x0e, 0x1d, 0x50,
                0x31, 0x18, 0xd1, 0xa8, 0x2d,
                0x99, 0xfb, 0x4a
            };

            byte[] aliceSignature =
            {
                0x5d, 0xe8, 0x8c, 0xa9, 0xa8,
                0x9b, 0x4a, 0x11, 0x5d, 0xa7,
                0x91, 0x09, 0xc6, 0x7c, 0x9c,
                0x74, 0x64, 0xa3, 0xe4, 0x18,
                0x02, 0x74, 0xf1, 0xcb, 0x8c,
                0x63, 0xc2, 0x98, 0x4e, 0x28,
                0x6d, 0xfb, 0xed, 0xe8, 0x2d,
                0xeb, 0x9d, 0xcd, 0x9f, 0xae,
                0x0b, 0xfb, 0xb8, 0x21, 0x56,
                0x9b, 0x3d, 0x90, 0x01, 0xbd,
                0x81, 0x30, 0xcd, 0x11, 0xd4,
                0x86, 0xce, 0xf0, 0x47, 0xbd,
                0x60, 0xb8, 0x6e, 0x88
            };

            ECPrivateKey alicePrivateKey = Curve.decodePrivatePoint(aliceIdentityPrivate);
            ECPublicKey  alicePublicKey  = Curve.decodePoint(aliceIdentityPublic, 0);
            ECPublicKey  aliceEphemeral  = Curve.decodePoint(aliceEphemeralPublic, 0);

            if (!Curve.verifySignature(alicePublicKey, aliceEphemeral.serialize(), aliceSignature))
            {
                Assert.Fail("Sig verification failed!");
            }

            for (int i = 0; i < aliceSignature.Length; i++)
            {
                byte[] modifiedSignature = new byte[aliceSignature.Length];
                System.Buffer.BlockCopy(aliceSignature, 0, modifiedSignature, 0, modifiedSignature.Length);

                modifiedSignature[i] ^= 0x01;

                if (Curve.verifySignature(alicePublicKey, aliceEphemeral.serialize(), modifiedSignature))
                {
                    Assert.Fail("Sig verification succeeded!");
                }
            }
        }
Example #27
0
            public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
            {
                ECPublicKey pubKey = (ECPublicKey)value;

                writer.WriteValue(Base64.encodeBytesWithoutPadding(pubKey.serialize()));
            }
Example #28
0
 //--------------------------------------------------------Misc Methods:---------------------------------------------------------------\\
 #region --Misc Methods (Public)--
 public bool checkIdentityKey(ECPublicKey other)
 {
     return(other.serialize().SequenceEqual(IDENTITY_PUB_KEY.serialize()));
 }
		public void setUnacknowledgedPreKeyMessage(May<uint> preKeyId, uint signedPreKeyId, ECPublicKey baseKey)
		{
			PendingPreKey.Builder pending = PendingPreKey.CreateBuilder()
														 .SetSignedPreKeyId(signedPreKeyId)
														 .SetBaseKey(ByteString.CopyFrom(baseKey.serialize()));

			if (preKeyId.HasValue)
			{
				pending.SetPreKeyId(preKeyId.ForceGetValue());
			}

			this.sessionStructure = this.sessionStructure.ToBuilder()
														 .SetPendingPreKey(pending.Build())
														 .Build();
		}
		public void addReceiverChain(ECPublicKey senderRatchetKey, ChainKey chainKey)
		{
			Chain.Types.ChainKey chainKeyStructure = Chain.Types.ChainKey.CreateBuilder()
															 .SetKey(ByteString.CopyFrom(chainKey.getKey()))
															 .SetIndex(chainKey.getIndex())
															 .Build();

			Chain chain = Chain.CreateBuilder()
							   .SetChainKey(chainKeyStructure)
							   .SetSenderRatchetKey(ByteString.CopyFrom(senderRatchetKey.serialize()))
							   .Build();

			this.sessionStructure = this.sessionStructure.ToBuilder().AddReceiverChains(chain).Build();

			if (this.sessionStructure.ReceiverChainsList.Count > 5)
			{
				this.sessionStructure = this.sessionStructure.ToBuilder()/*.ClearReceiverChains()*/.Build(); //RemoveReceiverChains(0) TODO: why does it work without
			}
		}
        public KeyExchangeMessage(uint messageVersion, uint sequence, uint flags,
                                  ECPublicKey baseKey, byte[] baseKeySignature,
                                  ECPublicKey ratchetKey,
                                  IdentityKey identityKey)
        {
            this.supportedVersion = CiphertextMessage.CURRENT_VERSION;
            this.version          = messageVersion;
            this.sequence         = sequence;
            this.flags            = flags;
            this.baseKey          = baseKey;
            this.baseKeySignature = baseKeySignature;
            this.ratchetKey       = ratchetKey;
            this.identityKey      = identityKey;

            byte[] version = { ByteUtil.intsToByteHighAndLow((int)this.version, (int)this.supportedVersion) };
            WhisperProtos.KeyExchangeMessage.Builder builder = WhisperProtos.KeyExchangeMessage
                                                               .CreateBuilder()
                                                               .SetId((sequence << 5) | flags) //(sequence << 5) | flags
                                                               .SetBaseKey(ByteString.CopyFrom(baseKey.serialize()))
                                                               .SetRatchetKey(ByteString.CopyFrom(ratchetKey.serialize()))
                                                               .SetIdentityKey(ByteString.CopyFrom(identityKey.serialize()));

            if (messageVersion >= 3)
            {
                builder.SetBaseKeySignature(ByteString.CopyFrom(baseKeySignature));
            }

            this.serialized = ByteUtil.combine(version, builder.Build().ToByteArray());
        }