Пример #1
0
        public static byte[] calculateAgreement(ECPublicKey publicKey, ECPrivateKey privateKey)
        {
            if (publicKey == null)
            {
                throw new InvalidKeyException("public value is null");
            }

            if (privateKey == null)
            {
                throw new InvalidKeyException("private value is null");
            }

            if (publicKey.getType() != privateKey.getType())
            {
                throw new InvalidKeyException("Public and private keys must be of the same type!");
            }

            if (publicKey.getType() == DJB_TYPE)
            {
                return(Curve25519.getInstance(Curve25519ProviderType.BEST)
                       .calculateAgreement(((DjbECPublicKey)publicKey).getPublicKey(),
                                           ((DjbECPrivateKey)privateKey).getPrivateKey()));
            }
            else
            {
                throw new InvalidKeyException("Unknown type: " + publicKey.getType());
            }
        }
Пример #2
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
            });
        }
Пример #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
            });
        }
Пример #4
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
            });
        }
Пример #5
0
        private static unsafe AsnWriter?RewritePkcs8ECPrivateKeyWithZeroPublicKey(ReadOnlySpan <byte> source)
        {
            fixed(byte *ptr = &MemoryMarshal.GetReference(source))
            {
                using (MemoryManager <byte> manager = new PointerMemoryManager <byte>(ptr, source.Length))
                {
                    PrivateKeyInfoAsn      privateKeyInfo   = PrivateKeyInfoAsn.Decode(manager.Memory, AsnEncodingRules.BER);
                    AlgorithmIdentifierAsn privateAlgorithm = privateKeyInfo.PrivateKeyAlgorithm;

                    if (privateAlgorithm.Algorithm.Value != Oids.EcPublicKey)
                    {
                        return(null);
                    }

                    ECPrivateKey privateKey = ECPrivateKey.Decode(privateKeyInfo.PrivateKey, AsnEncodingRules.BER);
                    EccKeyFormatHelper.FromECPrivateKey(privateKey, privateAlgorithm, out ECParameters ecParameters);

                    fixed(byte *pD = ecParameters.D)
                    {
                        try
                        {
                            if (!ecParameters.Curve.IsExplicit || ecParameters.Q.X != null || ecParameters.Q.Y != null)
                            {
                                return(null);
                            }

                            byte[] zero = new byte[ecParameters.D !.Length];
Пример #6
0
    //public string onnAddrStr = string.Empty;

    public void Import(string key)
    {
        BigInteger num = BigIntegerExt.ParseHexUnsigned(key);

        secKey = new ECPrivateKey(num, curve);
        Init();
    }
Пример #7
0
        private StaticKeys CalculateStaticKeys(ECPublicKey staticPublic, ECPrivateKey staticPrivate, byte[] salt)
        {
            byte[]   staticSecret       = Curve.calculateAgreement(staticPublic, staticPrivate);
            byte[]   staticDerived      = new HKDFv3().deriveSecrets(staticSecret, salt, new byte[0], 96);
            byte[][] staticDerivedParts = ByteUtil.split(staticDerived, 32, 32, 32);

            return(new StaticKeys(staticDerivedParts[1], staticDerivedParts[2]));
        }
Пример #8
0
        private EphemeralKeys CalculateEphemeralKeys(ECPublicKey ephemeralPublic, ECPrivateKey ephemeralPrivate, byte[] salt)
        {
            byte[]   ephemeralSecret       = Curve.calculateAgreement(ephemeralPublic, ephemeralPrivate);
            byte[]   ephemeralDerived      = new HKDFv3().deriveSecrets(ephemeralSecret, salt, new byte[0], 96);
            byte[][] ephemeralDerivedParts = ByteUtil.split(ephemeralDerived, 32, 32, 32);

            return(new EphemeralKeys(ephemeralDerivedParts[0], ephemeralDerivedParts[1], ephemeralDerivedParts[2]));
        }
Пример #9
0
        public void TestToAndFromRawEcPrivateKey(ushort ecOpensslNid)
        {
            var originalPrivateKey = GetNewPrivateKey(ecOpensslNid);
            var raw = originalPrivateKey.ExportToRaw();
            var reconstructedPrivateKey = ECPrivateKey.ImportFromRaw(raw);

            Assert.IsTrue(AreEcPrivateKeyEqual(originalPrivateKey, reconstructedPrivateKey));
        }
Пример #10
0
        public ECKeyPair getSenderRatchetKeyPair()
        {
            ECPublicKey  publicKey  = getSenderRatchetKey();
            ECPrivateKey privateKey = Curve.decodePrivatePoint(sessionStructure.SenderChain
                                                               .SenderRatchetKeyPrivate
                                                               .ToByteArray());

            return(new ECKeyPair(publicKey, privateKey));
        }
Пример #11
0
        public IdentityKeyPair getPendingKeyExchangeIdentityKey()
        {
            IdentityKey publicKey = new IdentityKey(sessionStructure.PendingKeyExchange
                                                    .LocalIdentityKey.ToByteArray(), 0);

            ECPrivateKey privateKey = Curve.decodePrivatePoint(sessionStructure.PendingKeyExchange
                                                               .LocalIdentityKeyPrivate
                                                               .ToByteArray());

            return(new IdentityKeyPair(publicKey, privateKey));
        }
Пример #12
0
        public ECKeyPair getPendingKeyExchangeRatchetKey()
        {
            ECPublicKey publicKey = Curve.decodePoint(sessionStructure.PendingKeyExchange
                                                      .LocalRatchetKey.ToByteArray(), 0);

            ECPrivateKey privateKey = Curve.decodePrivatePoint(sessionStructure.PendingKeyExchange
                                                               .LocalRatchetKeyPrivate
                                                               .ToByteArray());

            return(new ECKeyPair(publicKey, privateKey));
        }
Пример #13
0
 public static byte[] CalculateSignature(ECPrivateKey signingKey, byte[] message)
 {
     if (signingKey.GetKeyType() == DJB_TYPE)
     {
         return(Curve25519.GetInstance(Curve25519ProviderType.BEST).CalculateSignature(((DjbECPrivateKey)signingKey).GetPrivateKey(), message));
     }
     else
     {
         throw new InvalidKeyException("Unknown type: " + signingKey.GetKeyType());
     }
 }
 private byte[] getSignature(ECPrivateKey signatureKey, byte[] serialized)
 {
     try
     {
         return(Curve.calculateSignature(signatureKey, serialized));
     }
     catch (InvalidKeyException e)
     {
         throw new Exception(e.Message);
     }
 }
Пример #15
0
 public static byte[] calculateSignature(ECPrivateKey signingKey, byte[] message)
 {
     if (signingKey.getType() == DJB_TYPE)
     {
         return Curve25519.getInstance(BEST)
                          .calculateSignature(((DjbECPrivateKey)signingKey).getPrivateKey(), message);
     }
     else
     {
         throw new InvalidKeyException("Unknown type: " + signingKey.getType());
     }
 }
Пример #16
0
        public virtual ECKeyPair GetKeyPair(ECPrivateKey privatekey, bool compressed = true)
        {
            var curve        = ECNamedCurveTable.GetByName(CURVEALGO);
            var domainParams = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H, curve.GetSeed());

            BigInteger d = new BigInteger(1, privatekey.Base64Array);
            ECPoint    q = domainParams.G.Multiply(d);

            var publicParams = new ECPublicKeyParameters(q, domainParams);
            var pubkey       = new ECPublicKey(publicParams.Q.GetEncoded(compressed));

            return(new ECKeyPair(privatekey, pubkey));
        }
Пример #17
0
 public IdentityKeyPair(byte[] serialized)
 {
     try
     {
         IdentityKeyPairStructure structure = IdentityKeyPairStructure.ParseFrom(serialized);
         this.publicKey = new IdentityKey(structure.PublicKey.ToByteArray(), 0);
         this.privateKey = Curve.decodePrivatePoint(structure.PrivateKey.ToByteArray());
     }
     catch (InvalidProtocolBufferException e)
     {
         throw new InvalidKeyException(e);
     }
 }
Пример #18
0
 public IdentityKeyPair(byte[] serialized)
 {
     try
     {
         IdentityKeyPairStructure structure = IdentityKeyPairStructure.ParseFrom(serialized);
         this.publicKey  = new IdentityKey(structure.PublicKey.ToByteArray(), 0);
         this.privateKey = Curve.decodePrivatePoint(structure.PrivateKey.ToByteArray());
     }
     catch (InvalidProtocolBufferException e)
     {
         throw new InvalidKeyException(e);
     }
 }
Пример #19
0
        public ECKeyPair getKeyPair()
        {
            try
            {
                ECPublicKey  publicKey  = Curve.decodePoint(structure.PublicKey.ToByteArray(), 0);
                ECPrivateKey privateKey = Curve.decodePrivatePoint(structure.PrivateKey.ToByteArray());

                return(new ECKeyPair(publicKey, privateKey));
            }
            catch (InvalidKeyException e)
            {
                throw new Exception(e.Message);
            }
        }
Пример #20
0
        internal static unsafe ECParameters FromECPrivateKey(ReadOnlySpan <byte> key, out int bytesRead)
        {
            fixed(byte *ptr = &MemoryMarshal.GetReference(key))
            {
                using (MemoryManager <byte> manager = new PointerMemoryManager <byte>(ptr, key.Length))
                {
                    ECPrivateKey parsedKey =
                        AsnSerializer.Deserialize <ECPrivateKey>(manager.Memory, AsnEncodingRules.BER, out bytesRead);

                    ECParameters           ret;
                    AlgorithmIdentifierAsn algId = default;
                    FromECPrivateKey(parsedKey, algId, out ret);
                    return(ret);
                }
            }
        }
Пример #21
0
        public virtual byte[] Decrypt(ECPrivateKey privateKey, byte[] data)
        {
            using (var stream = new MemoryStream(data))
            {
                //  read the IV
                byte[] iv = new byte[16];
                stream.Read(iv, 0, iv.Length);

                //  read the publickey
                var    pubkeysize = stream.ReadByte();
                byte[] pubkeyraw  = new byte[pubkeysize];
                stream.Read(pubkeyraw, 0, pubkeyraw.Length);
                var pubkey = new ECPublicKey(pubkeyraw);

                //  Do an EC point multiply with this.getPrivateKey() and ephemeral public key. This gives you a point M.
                var m = GetECPoint(pubkey).Multiply(new BigInteger(1, privateKey.Base64Array)).Normalize();

                //  Use the X component of point M and calculate the SHA512 hash H.
                byte[] h = RadixHash.Sha512Of(m.XCoord.GetEncoded()).ToByteArray();

                //  The first 32 bytes of H are called key_e and the last 32 bytes are called key_m.
                byte[] keyE = Arrays.CopyOfRange(h, 0, 32);
                byte[] keyM = Arrays.CopyOfRange(h, 32, 64);

                //  Read encrypted data
                var size = new byte[4];
                stream.Read(size, 0, size.Length);
                byte[] encrypted = new byte[BitConverter.ToInt32(size, 0)];
                stream.Read(encrypted, 0, encrypted.Length);

                //  Read MAC
                byte[] mac = new byte[32];
                stream.Read(mac, 0, mac.Length);

                //  Compare MAC with MAC'. If not equal, decryption will fail.
                byte[] pkMac = CalculateMAC(keyM, iv, pubkey, encrypted);
                if (pkMac.Equals(mac))
                {
                    throw new ApplicationException
                              ($"Decryption failed, mac mismatch , {Convert.ToBase64String(pkMac)} <> {Convert.ToBase64String(mac)}");
                }

                //  Decrypt the cipher text with AES-256-CBC, using IV as initialization vector, key_e as decryption key,
                //  and the cipher text as payload. The output is the padded input text.
                return(Crypt(false, encrypted, iv, keyE));
            }
        }
        public SenderKeyMessage(uint keyId, uint iteration, byte[] ciphertext, ECPrivateKey signatureKey)
        {
            byte[] version = { ByteUtil.intsToByteHighAndLow((int)CURRENT_VERSION, (int)CURRENT_VERSION) };
            byte[] message = WhisperProtos.SenderKeyMessage.CreateBuilder()
                             .SetId(keyId)
                             .SetIteration(iteration)
                             .SetCiphertext(ByteString.CopyFrom(ciphertext))
                             .Build().ToByteArray();

            byte[] signature = getSignature(signatureKey, ByteUtil.combine(version, message));

            serialized      = ByteUtil.combine(version, message, signature);
            messageVersion  = CURRENT_VERSION;
            this.keyId      = keyId;
            this.iteration  = iteration;
            this.ciphertext = ciphertext;
        }
Пример #23
0
        public static byte[] calculateVrfSignature(ECPrivateKey signingKey, byte[] message)
        {
            if (signingKey == null || message == null)
            {
                throw new InvalidKeyException("Values must not be null");
            }

            if (signingKey.getType() == DJB_TYPE)
            {
                return(Curve25519.getInstance(Curve25519ProviderType.BEST)
                       .calculateVrfSignature(((DjbECPrivateKey)signingKey).getPrivateKey(), message));
            }
            else
            {
                throw new InvalidKeyException("Unknown type: " + signingKey.getType());
            }
        }
Пример #24
0
        public SenderKeyMessage(uint keyId, uint iteration, byte[] ciphertext, ECPrivateKey signatureKey)
        {
            byte[] version = { ByteUtil.intsToByteHighAndLow((int)CURRENT_VERSION, (int)CURRENT_VERSION) };
            byte[] message = WhisperProtos.SenderKeyMessage.CreateBuilder()
                                                           .SetId(keyId)
                                                           .SetIteration(iteration)
                                                           .SetCiphertext(ByteString.CopyFrom(ciphertext))
                                                           .Build().ToByteArray();

            byte[] signature = getSignature(signatureKey, ByteUtil.combine(version, message));

            this.serialized = ByteUtil.combine(version, message, signature);
            this.messageVersion = CURRENT_VERSION;
            this.keyId = keyId;
            this.iteration = iteration;
            this.ciphertext = ciphertext;
        }
Пример #25
0
        public SenderKeyMessage(uint keyId, uint iteration, byte[] ciphertext, ECPrivateKey signatureKey)
        {
            byte[] version = { ByteUtil.intsToByteHighAndLow((int)CURRENT_VERSION, (int)CURRENT_VERSION) };
            byte[] message = new SenderKeyMessage
            {
                Id         = keyId,
                Iteration  = iteration,
                Ciphertext = ByteString.CopyFrom(ciphertext),
            }.ToByteArray();

            byte[] signature = getSignature(signatureKey, ByteUtil.combine(version, message));

            this.serialized     = ByteUtil.combine(version, message, signature);
            this.messageVersion = CURRENT_VERSION;
            this.keyId          = keyId;
            this.iteration      = iteration;
            this.ciphertext     = ciphertext;
        }
Пример #26
0
        public static IdentityKeyPair GetIdentityKeyPair()
        {
            if (!hasIdentityKey())
            {
                return(null);
            }

            try
            {
                //MasterCipher masterCipher = new MasterCipher(masterSecret);
                IdentityKey publicKey = getIdentityKey();
                //ECPrivateKey privateKey = /*masterCipher.decryptKey(*/Base64.decode(retrieve(IDENTITY_PRIVATE_KEY_DJB_PREF))/*)*/;
                ECPrivateKey privateKey = Curve.decodePrivatePoint(Base64.decode(retrieve(IDENTITY_PRIVATE_KEY_DJB_PREF)));

                return(new IdentityKeyPair(publicKey, privateKey));
            }
            catch (/*IOException | */ InvalidKeyException e)
            {
                throw new Exception(e.Message);
            }
        }
Пример #27
0
        public override byte[] DoSign(byte[] ske,
                                      out int hashAlgo, out int signAlgo)
        {
            hashAlgo = this.hashAlgo;
            byte[] hv = Hash(hashAlgo, ske);
            if (skey is RSAPrivateKey)
            {
                RSAPrivateKey rk = skey as RSAPrivateKey;
                signAlgo = SSL.RSA;
                byte[] head;
                switch (hashAlgo)
                {
                case SSL.MD5SHA1: head = null; break;

                case SSL.SHA1:    head = RSA.PKCS1_SHA1; break;

                case SSL.SHA224:  head = RSA.PKCS1_SHA224; break;

                case SSL.SHA256:  head = RSA.PKCS1_SHA256; break;

                case SSL.SHA384:  head = RSA.PKCS1_SHA384; break;

                case SSL.SHA512:  head = RSA.PKCS1_SHA512; break;

                default:
                    throw new Exception();
                }
                return(RSA.Sign(rk, head, hv));
            }
            else if (skey is ECPrivateKey)
            {
                ECPrivateKey ek = skey as ECPrivateKey;
                signAlgo = SSL.ECDSA;
                return(ECDSA.Sign(ek, null, hv));
            }
            else
            {
                throw new Exception("NYI");
            }
        }
Пример #28
0
        public virtual ECSignature GetECSignature(ECPrivateKey privateKey, byte[] data, bool beDeterministic = false, bool enforceLowS = true)
        {
            var curve  = SecNamedCurves.GetByName(CURVEALGO);
            var domain = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H);


            IDsaKCalculator kCalculator;

            if (beDeterministic)
            {
                kCalculator = new HMacDsaKCalculator(new Sha256Digest());
            }
            else
            {
                kCalculator = new RandomDsaKCalculator();
            }

            ECDsaSigner signer = new ECDsaSigner(kCalculator);

            signer.Init(true, new ECPrivateKeyParameters(new BigInteger(1, privateKey.Base64Array), domain));

            BigInteger[] components = signer.GenerateSignature(data);

            BigInteger r = components[0];
            BigInteger s = components[1];

            BigInteger curveOrder     = domain.N;
            BigInteger halvCurveOrder = curveOrder.ShiftRight(1);

            bool sIsLow = s.CompareTo(halvCurveOrder) <= 0;

            if (enforceLowS && !sIsLow)
            {
                s = curveOrder.Subtract(s);
            }

            return(new ECSignature(r, s));
        }
Пример #29
0
        public void testAgreement()
        {
            byte[] alicePublic =
            {
                0x05, 0x1b, 0xb7, 0x59, 0x66,
                0xf2, 0xe9, 0x3a, 0x36, 0x91,
                0xdf, 0xff, 0x94, 0x2b, 0xb2,
                0xa4, 0x66, 0xa1, 0xc0, 0x8b,
                0x8d, 0x78, 0xca, 0x3f, 0x4d,
                0x6d, 0xf8, 0xb8, 0xbf, 0xa2,
                0xe4, 0xee, 0x28
            };

            byte[] alicePrivate =
            {
                0xc8, 0x06, 0x43, 0x9d, 0xc9,
                0xd2, 0xc4, 0x76, 0xff, 0xed,
                0x8f, 0x25, 0x80, 0xc0, 0x88,
                0x8d, 0x58, 0xab, 0x40, 0x6b,
                0xf7, 0xae, 0x36, 0x98, 0x87,
                0x90, 0x21, 0xb9, 0x6b, 0xb4,
                0xbf, 0x59
            };

            byte[] bobPublic =
            {
                0x05, 0x65, 0x36, 0x14, 0x99,
                0x3d, 0x2b, 0x15, 0xee, 0x9e,
                0x5f, 0xd3, 0xd8, 0x6c, 0xe7,
                0x19, 0xef, 0x4e, 0xc1, 0xda,
                0xae, 0x18, 0x86, 0xa8, 0x7b,
                0x3f, 0x5f, 0xa9, 0x56, 0x5a,
                0x27, 0xa2, 0x2f
            };

            byte[] bobPrivate =
            {
                0xb0, 0x3b, 0x34, 0xc3, 0x3a,
                0x1c, 0x44, 0xf2, 0x25, 0xb6,
                0x62, 0xd2, 0xbf, 0x48, 0x59,
                0xb8, 0x13, 0x54, 0x11, 0xfa,
                0x7b, 0x03, 0x86, 0xd4, 0x5f,
                0xb7, 0x5d, 0xc5, 0xb9, 0x1b,
                0x44, 0x66
            };

            byte[] shared =
            {
                0x32, 0x5f, 0x23, 0x93, 0x28,
                0x94, 0x1c, 0xed, 0x6e, 0x67,
                0x3b, 0x86, 0xba, 0x41, 0x01,
                0x74, 0x48, 0xe9, 0x9b, 0x64,
                0x9a, 0x9c, 0x38, 0x06, 0xc1,
                0xdd, 0x7c, 0xa4, 0xc4, 0x77,
                0xe6, 0x29
            };

            ECPublicKey  alicePublicKey  = Curve.decodePoint(alicePublic, 0);
            ECPrivateKey alicePrivateKey = Curve.decodePrivatePoint(alicePrivate);

            ECPublicKey  bobPublicKey  = Curve.decodePoint(bobPublic, 0);
            ECPrivateKey bobPrivateKey = Curve.decodePrivatePoint(bobPrivate);

            byte[] sharedOne = Curve.calculateAgreement(alicePublicKey, bobPrivateKey);
            byte[] sharedTwo = Curve.calculateAgreement(bobPublicKey, alicePrivateKey);

            CollectionAssert.AreEqual(sharedOne, shared);
            CollectionAssert.AreEqual(sharedTwo, shared);
        }
Пример #30
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!");
                }
            }
        }
Пример #31
0
 public ECKeyPair(ECPublicKey publicKey, ECPrivateKey privateKey)
 {
     this.publicKey  = publicKey;
     this.privateKey = privateKey;
 }
Пример #32
0
 public IdentityKeyPair(IdentityKey publicKey, ECPrivateKey privateKey)
 {
     this.publicKey  = publicKey;
     this.privateKey = privateKey;
 }
Пример #33
0
        public void testRatchetingSessionAsAlice()
        {
            byte[] bobPublic =
            {
                0x05, 0x2c, 0xb4, 0x97, 0x76,
                0xb8, 0x77, 0x02, 0x05, 0x74,
                0x5a, 0x3a, 0x6e, 0x24, 0xf5,
                0x79, 0xcd, 0xb4, 0xba, 0x7a,
                0x89, 0x04, 0x10, 0x05, 0x92,
                0x8e, 0xbb, 0xad, 0xc9, 0xc0,
                0x5a, 0xd4, 0x58
            };

            byte[] bobIdentityPublic =
            {
                0x05, 0xf1, 0xf4, 0x38, 0x74,
                0xf6, 0x96, 0x69, 0x56, 0xc2,
                0xdd, 0x47, 0x3f, 0x8f, 0xa1,
                0x5a, 0xde, 0xb7, 0x1d, 0x1c,
                0xb9, 0x91, 0xb2, 0x34, 0x16,
                0x92, 0x32, 0x4c, 0xef, 0xb1,
                0xc5, 0xe6, 0x26
            };

            byte[] aliceBasePublic =
            {
                0x05, 0x47, 0x2d, 0x1f, 0xb1,
                0xa9, 0x86, 0x2c, 0x3a, 0xf6,
                0xbe, 0xac, 0xa8, 0x92, 0x02,
                0x77, 0xe2, 0xb2, 0x6f, 0x4a,
                0x79, 0x21, 0x3e, 0xc7, 0xc9,
                0x06, 0xae, 0xb3, 0x5e, 0x03,
                0xcf, 0x89, 0x50
            };

            byte[] aliceBasePrivate =
            {
                0x11, 0xae, 0x7c, 0x64, 0xd1,
                0xe6, 0x1c, 0xd5, 0x96, 0xb7,
                0x6a, 0x0d, 0xb5, 0x01, 0x26,
                0x73, 0x39, 0x1c, 0xae, 0x66,
                0xed, 0xbf, 0xcf, 0x07, 0x3b,
                0x4d, 0xa8, 0x05, 0x16, 0xa4,
                0x74, 0x49
            };

            byte[] aliceEphemeralPublic =
            {
                0x05, 0x6c, 0x3e, 0x0d, 0x1f,
                0x52, 0x02, 0x83, 0xef, 0xcc,
                0x55, 0xfc, 0xa5, 0xe6, 0x70,
                0x75, 0xb9, 0x04, 0x00, 0x7f,
                0x18, 0x81, 0xd1, 0x51, 0xaf,
                0x76, 0xdf, 0x18, 0xc5, 0x1d,
                0x29, 0xd3, 0x4b
            };

            byte[] aliceEphemeralPrivate =
            {
                0xd1, 0xba, 0x38, 0xce, 0xa9,
                0x17, 0x43, 0xd3, 0x39, 0x39,
                0xc3, 0x3c, 0x84, 0x98, 0x65,
                0x09, 0x28, 0x01, 0x61, 0xb8,
                0xb6, 0x0f, 0xc7, 0x87, 0x0c,
                0x59, 0x9c, 0x1d, 0x46, 0x20,
                0x12, 0x48
            };

            byte[] aliceIdentityPublic =
            {
                0x05, 0xb4, 0xa8, 0x45, 0x56,
                0x60, 0xad, 0xa6, 0x5b, 0x40,
                0x10, 0x07, 0xf6, 0x15, 0xe6,
                0x54, 0x04, 0x17, 0x46, 0x43,
                0x2e, 0x33, 0x39, 0xc6, 0x87,
                0x51, 0x49, 0xbc, 0xee, 0xfc,
                0xb4, 0x2b, 0x4a
            };

            byte[] aliceIdentityPrivate =
            {
                0x90, 0x40, 0xf0, 0xd4, 0xe0,
                0x9c, 0xf3, 0x8f, 0x6d, 0xc7,
                0xc1, 0x37, 0x79, 0xc9, 0x08,
                0xc0, 0x15, 0xa1, 0xda, 0x4f,
                0xa7, 0x87, 0x37, 0xa0, 0x80,
                0xeb, 0x0a, 0x6f, 0x4f, 0x5f,
                0x8f, 0x58
            };

            byte[] receiverChain =
            {
                0xd2, 0x2f, 0xd5, 0x6d, 0x3f,
                0xec, 0x81, 0x9c, 0xf4, 0xc3,
                0xd5, 0x0c, 0x56, 0xed, 0xfb,
                0x1c, 0x28, 0x0a, 0x1b, 0x31,
                0x96, 0x45, 0x37, 0xf1, 0xd1,
                0x61, 0xe1, 0xc9, 0x31, 0x48,
                0xe3, 0x6b
            };

            IdentityKey     bobIdentityKey           = new IdentityKey(bobIdentityPublic, 0);
            ECPublicKey     bobEphemeralPublicKey    = Curve.decodePoint(bobPublic, 0);
            ECPublicKey     bobBasePublicKey         = bobEphemeralPublicKey;
            ECPublicKey     aliceBasePublicKey       = Curve.decodePoint(aliceBasePublic, 0);
            ECPrivateKey    aliceBasePrivateKey      = Curve.decodePrivatePoint(aliceBasePrivate);
            ECKeyPair       aliceBaseKey             = new ECKeyPair(aliceBasePublicKey, aliceBasePrivateKey);
            ECPublicKey     aliceEphemeralPublicKey  = Curve.decodePoint(aliceEphemeralPublic, 0);
            ECPrivateKey    aliceEphemeralPrivateKey = Curve.decodePrivatePoint(aliceEphemeralPrivate);
            ECKeyPair       aliceEphemeralKey        = new ECKeyPair(aliceEphemeralPublicKey, aliceEphemeralPrivateKey);
            IdentityKey     aliceIdentityPublicKey   = new IdentityKey(aliceIdentityPublic, 0);
            ECPrivateKey    aliceIdentityPrivateKey  = Curve.decodePrivatePoint(aliceIdentityPrivate);
            IdentityKeyPair aliceIdentityKey         = new IdentityKeyPair(aliceIdentityPublicKey, aliceIdentityPrivateKey);

            SessionState session = new SessionState();

            AliceAxolotlParameters parameters = AliceAxolotlParameters.newBuilder()
                                                .setOurBaseKey(aliceBaseKey)
                                                .setOurIdentityKey(aliceIdentityKey)
                                                .setTheirIdentityKey(bobIdentityKey)
                                                .setTheirSignedPreKey(bobBasePublicKey)
                                                .setTheirRatchetKey(bobEphemeralPublicKey)
                                                .setTheirOneTimePreKey(May <ECPublicKey> .NoValue)
                                                .create();

            RatchetingSession.initializeSession(session, 2, parameters);

            Assert.AreEqual(session.getLocalIdentityKey(), aliceIdentityKey.getPublicKey());
            Assert.AreEqual(session.getRemoteIdentityKey(), bobIdentityKey);
            CollectionAssert.AreEqual(session.getReceiverChainKey(bobEphemeralPublicKey).getKey(), receiverChain);
        }
Пример #34
0
 private byte[] getSignature(ECPrivateKey signatureKey, byte[] serialized)
 {
     try
     {
         return Curve.calculateSignature(signatureKey, serialized);
     }
     catch (InvalidKeyException e)
     {
         throw new Exception(e.Message);
     }
 }
Пример #35
-1
        public static byte[] calculateAgreement(ECPublicKey publicKey, ECPrivateKey privateKey)
        {
            if (publicKey.getType() != privateKey.getType())
            {
                throw new InvalidKeyException("Public and private keys must be of the same type!");
            }

            if (publicKey.getType() == DJB_TYPE)
            {
                return Curve25519.getInstance(Curve25519ProviderType.BEST)
                                 .calculateAgreement(((DjbECPublicKey)publicKey).getPublicKey(),
                                                     ((DjbECPrivateKey)privateKey).getPrivateKey());
            }
            else
            {
                throw new InvalidKeyException("Unknown type: " + publicKey.getType());
            }
        }
Пример #36
-1
 public ECKeyPair(ECPublicKey publicKey, ECPrivateKey privateKey)
 {
     this.publicKey = publicKey;
     this.privateKey = privateKey;
 }
Пример #37
-1
 public IdentityKeyPair(IdentityKey publicKey, ECPrivateKey privateKey)
 {
     this.publicKey = publicKey;
     this.privateKey = privateKey;
 }