Esempio n. 1
0
 public static void ExportKey(string Path, ECDiffieHellmanPublicKey Key)
 {
     using (BinaryWriter Writer = new BinaryWriter(File.Create(Path)))
     {
         Writer.Write((byte)Key.ToByteArray().Length);
         Writer.Write(Key.ToByteArray());
     }
 }
Esempio n. 2
0
        private ECPublicKeyParameters GetPublicKeyParameters(ECDiffieHellmanPublicKey publicKey)
        {
            byte[] ecdhBlob = publicKey.ToByteArray();

            int    keySize;
            string magic = Encoding.ASCII.GetString(ecdhBlob, 0, 4);

            if (magic.Equals("ECK1"))
            {
                keySize = 256;
            }
            else if (magic.Equals("ECK3"))
            {
                keySize = 384;
            }
            else if (magic.Equals("ECK5"))
            {
                keySize = 521;
            }
            else
            {
                throw new Exception("Unknown public key type");
            }
            if (keySize != _keySize)
            {
                throw new Exception("Public key size doesn't match our key size");
            }

            byte[] encoded = new byte[1 + ecdhBlob.Length - 8];
            encoded[0] = 0x04;
            Buffer.BlockCopy(ecdhBlob, 8, encoded, 1, ecdhBlob.Length - 8);
            Org.BouncyCastle.Math.EC.ECPoint ecPoint = _domainParameters.Curve.DecodePoint(encoded);
            return(new ECPublicKeyParameters(ecPoint, _domainParameters));
        }
Esempio n. 3
0
        public static byte[] ToDerEncoded([NotNull] this ECDiffieHellmanPublicKey key)
        {
            byte[] asn = new byte[24] {
                0x30, 0x76, 0x30, 0x10, 0x6, 0x7, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x2, 0x1, 0x6, 0x5, 0x2b, 0x81, 0x4, 0x0, 0x22, 0x3, 0x62, 0x0, 0x4
            };

            return(asn.Concat(key.ToByteArray().Skip(8)).ToArray());
        }
Esempio n. 4
0
 /// <summary>
 /// Generates a shared verified key.
 /// </summary>
 /// <param name="publicKey"></param>
 /// <param name="signedPublicKey"></param>
 /// <param name="parameters"></param>
 public void GenerateVerifiedSharedKey(ECDiffieHellmanPublicKey publicKey, byte[] signedPublicKey, RSAParameters parameters)
 {
     if (VerifySignedData(publicKey.ToByteArray(), signedPublicKey, parameters))
     {
         GenerateSharedKey(publicKey);
     }
     else
     {
         Console.WriteLine("Could not create end-to-end encryption key. RSA signing does not match.");
     }
 }
 public virtual void SetAccountLogKey(
     TAccount userAccount,
     ECDiffieHellmanCng ecAccountLogKey,
     byte[] phase1HashOfCorrectPassword)
 {
     userAccount.EcPrivateAccountLogKeyEncryptedWithPasswordHashPhase1 = Encryption.EncryptEcPrivateKeyWithAesCbc(ecAccountLogKey,
                                                                                                                  phase1HashOfCorrectPassword);
     using (ECDiffieHellmanPublicKey publicKey = ecAccountLogKey.PublicKey)
     {
         userAccount.EcPublicAccountLogKey = publicKey.ToByteArray();
     }
 }
Esempio n. 6
0
        public override byte[] DeriveKeyMaterial(ECDiffieHellmanPublicKey otherPartyPublicKey)
        {
            var d = privateKey.D;

            // read the other side's public key.
            var     opp = otherPartyPublicKey.ToByteArray();
            ECPoint Qs  = ECPoint.FromBlob(opp);

            // multiply their public key with our private d to get the shared secret.
            var p = Qs * d;
            var z = p.X.ToByteArray().Reverse().ToArray();

            return(z);
        }
Esempio n. 7
0
        public bool InitaliseSymmettricKey(ECDiffieHellmanPublicKey otherPartyPublicKey, byte[] signedPublicKey, RSAParameters otherPartyRSAPublicKey)
        {
            RSACryptoServiceProvider csp = new RSACryptoServiceProvider();

            csp.ImportParameters(otherPartyRSAPublicKey);
            if (csp.VerifyData(otherPartyPublicKey.ToByteArray(), SHA2, signedPublicKey))
            {
                symmettricKey = ECDH.DeriveKeyMaterial(otherPartyPublicKey);
                return(true);
            }
            else
            {
                return(false);
            }
        }
Esempio n. 8
0
        public void TestCertMangling()
        {
            string certString = @"MIICSjCCAdECCQDje/no7mXkVzAKBggqhkjOPQQDAjCBjjELMAkGA1UEBhMCVVMx
EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDAS
BgNVBAoMC0dvb2dsZSwgSW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEG
CSqGSIb3DQEJARYUZ29sYW5nLWRldkBnbWFpbC5jb20wHhcNMTIwNTIxMDYxMDM0
WhcNMjIwNTE5MDYxMDM0WjCBjjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlm
b3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDASBgNVBAoMC0dvb2dsZSwg
SW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEGCSqGSIb3DQEJARYUZ29s
YW5nLWRldkBnbWFpbC5jb20wdjAQBgcqhkjOPQIBBgUrgQQAIgNiAARRuzRNIKRK
jIktEmXanNmrTR/q/FaHXLhWRZ6nHWe26Fw7Rsrbk+VjGy4vfWtNn7xSFKrOu5ze
qxKnmE0h5E480MNgrUiRkaGO2GMJJVmxx20aqkXOk59U8yGA4CghE6MwCgYIKoZI
zj0EAwIDZwAwZAIwBZEN8gvmRmfeP/9C1PRLzODIY4JqWub2PLRT4mv9GU+yw3Gr
PU9A3CHMdEcdw/MEAjBBO1lId8KOCh9UZunsSMfqXiVurpzmhWd6VYZ/32G+M+Mh
3yILeYQzllt/g0rKVRk=";

            X509Certificate2 c = new X509Certificate2();

            c.Import(Convert.FromBase64String(certString));
            Assert.AreEqual("[email protected], CN=www.google.com, O=\"Google, Inc\", L=Mountain View, S=California, C=US", c.Issuer);
            //Assert.AreEqual("CN=Microsoft Corporate Root CA, O=Microsoft Corporation", c.Subject);
            Assert.AreEqual("X509", c.GetFormat());
            Assert.AreEqual("1.2.840.10045.2.1", c.GetKeyAlgorithm());
            Assert.AreEqual("06052B81040022", c.GetKeyAlgorithmParametersString());
            Assert.AreEqual("ECC", c.PublicKey.Oid.FriendlyName);
            ECDiffieHellmanPublicKey certKey = CryptoUtils.ImportEccPublicKeyFromCertificate(c);
            //Console.WriteLine(certKey.ToXmlString());

            // https://blogs.msdn.microsoft.com/shawnfa/2007/01/22/elliptic-curve-diffie-hellman/
            // http://stackoverflow.com/questions/11266711/using-cngkey-to-generate-rsa-key-pair-in-pem-dkim-compatible-using-c-simi
            {
                string input = "eyJhbGciOiJFUzM4NCIsIng1dSI6Ik1IWXdFQVlIS29aSXpqMENBUVlGSzRFRUFDSURZZ0FFN25uWnBDZnhtQ3JTd0RkQnY3ZUJYWE10S2hyb3hPcmlFcjNobU1PSkF1dy9acFFYajFLNUdHdEhTNENwRk50dGQxSllBS1lvSnhZZ2F5a3BpZTBFeUF2M3FpSzZ1dElIMnFuT0F0M1ZOclFZWGZJWkpTL1ZSZTNJbDhQZ3U5Q0IifQo.eyJleHAiOjE0NjQ5ODM4NDUsImV4dHJhRGF0YSI6eyJkaXNwbGF5TmFtZSI6Imd1cnVueCIsImlkZW50aXR5IjoiYWY2ZjdjNWUtZmNlYS0zZTQzLWJmM2EtZTAwNWU0MDBlNTc4In0sImlkZW50aXR5UHVibGljS2V5IjoiTUhZd0VBWUhLb1pJemowQ0FRWUZLNEVFQUNJRFlnQUU3bm5acENmeG1DclN3RGRCdjdlQlhYTXRLaHJveE9yaUVyM2htTU9KQXV3L1pwUVhqMUs1R0d0SFM0Q3BGTnR0ZDFKWUFLWW9KeFlnYXlrcGllMEV5QXYzcWlLNnV0SUgycW5PQXQzVk5yUVlYZklaSlMvVlJlM0lsOFBndTlDQiIsIm5iZiI6MTQ2NDk4Mzg0NH0K.4OrvYYbX09iwOkz-7_N_5yEejuATcUogEbe69fB-kr7r6sH_qSu6bxp9L64SEgABb0rU7tyYCLVnaCSQjd9Dvb34WI9EducgOPJ92qHspcpXr7j716LDfhZE31ksMtWQ";

                ECDiffieHellmanPublicKey rootKey = CryptoUtils.CreateEcDiffieHellmanPublicKey("MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE8ELkixyLcwlZryUQcu1TvPOmI2B7vX83ndnWRUaXm74wFfa5f/lwQNTfrLVHa2PmenpGI6JhIMUJaWZrjmMj90NoKNFSNBuKdm8rYiXsfaz3K36x/1U26HpG0ZxK/V1V");

                Console.WriteLine($"Root Public Key:\n{rootKey.ToXmlString()}");
                CngKey key = CngKey.Import(rootKey.ToByteArray(), CngKeyBlobFormat.EccPublicBlob);

                Console.WriteLine("Key family: " + key.AlgorithmGroup);
                //   "identityPublicKey": "MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE7nnZpCfxmCrSwDdBv7eBXXMtKhroxOriEr3hmMOJAuw/ZpQXj1K5GGtHS4CpFNttd1JYAKYoJxYgaykpie0EyAv3qiK6utIH2qnOAt3VNrQYXfIZJS/VRe3Il8Pgu9CB",

                var    newKey  = CryptoUtils.ImportECDsaCngKeyFromString("MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE7nnZpCfxmCrSwDdBv7eBXXMtKhroxOriEr3hmMOJAuw/ZpQXj1K5GGtHS4CpFNttd1JYAKYoJxYgaykpie0EyAv3qiK6utIH2qnOAt3VNrQYXfIZJS/VRe3Il8Pgu9CB");
                string decoded = JWT.Decode(input, newKey);
                //Assert.AreEqual("", decoded);


                //ECDsaCng t = new ECDsaCng();
                //t.HashAlgorithm = CngAlgorithm.ECDiffieHellmanP384;
                //t.KeySize = 384;
                //byte[] test = t.Key.Export(CngKeyBlobFormat.EccPublicBlob);
                //Assert.AreEqual(test, newKey);

                //string decoded = JWT.Decode(input, t.Key);
            }

            // Private key (in reality this is not necessary since we will generate it)
            AsymmetricKeyParameter privKey     = PrivateKeyFactory.CreateKey(Base64Url.Decode("MB8CAQAwEAYHKoZIzj0CAQYFK4EEACIECDAGAgEBBAEB"));
            PrivateKeyInfo         privKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privKey);

            byte[] derKey     = privKeyInfo.GetDerEncoded();
            CngKey privCngKey = CngKey.Import(derKey, CngKeyBlobFormat.Pkcs8PrivateBlob);


            Console.WriteLine(privKeyInfo.PrivateKeyAlgorithm.Algorithm);
            Console.WriteLine(privCngKey.Algorithm.Algorithm);

            // Public key
            ECDiffieHellmanPublicKey clientKey = CryptoUtils.CreateEcDiffieHellmanPublicKey("MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEDEKneqEvcqUqqFMM1HM1A4zWjJC+I8Y+aKzG5dl+6wNOHHQ4NmG2PEXRJYhujyodFH+wO0dEr4GM1WoaWog8xsYQ6mQJAC0eVpBM96spUB1eMN56+BwlJ4H3Qx4TAvAs");

            // EC key to generate shared secret

            ECDiffieHellmanCng ecKey = new ECDiffieHellmanCng(privCngKey);

            ecKey.HashAlgorithm         = CngAlgorithm.Sha256;
            ecKey.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;
            ecKey.SecretPrepend         = new byte[128];     // Server token
            //ecKey.SecretPrepend = new byte[0]; // Server token

            Console.WriteLine(ecKey.HashAlgorithm);
            Console.WriteLine(ecKey.KeyExchangeAlgorithm);

            byte[] secret = ecKey.DeriveKeyMaterial(clientKey);

            Console.WriteLine(Package.HexDump(secret));
            Console.WriteLine(Package.HexDump(Base64Url.Decode("ZOBpyzki/M8UZv5tiBih048eYOBVPkQE3r5Fl0gmUP4=")));
            Console.WriteLine(Package.HexDump(Base64Url.Decode("DEKneqEvcqUqqFMM1HM1A4zWjJC+I8Y+aKzG5dl+6wNOHHQ4NmG2PEXRJYhujyod")));

            //Console.WriteLine(Package.HexDump(Base64Url.Decode("DEKneqEvcqUqqFMM1HM1A4zWjJC+I8Y+aKzG5dl+6wNOHHQ4NmG2PEXRJYhujyod")));
        }
Esempio n. 9
0
 public override byte[] ToByteArray() => _wrapped.ToByteArray();
Esempio n. 10
0
 public static void Write(this BinaryWriter writer, ECDiffieHellmanPublicKey publicKey)
 {
     writer.Write(publicKey.ToByteArray());
 }