Exemplo n.º 1
0
		static double Run (ECDiffieHellman ecdh)
		{
			int loopA = 5, loopB = 5;
			double result = SpeedTest.Run (ecdh, loopA);
			for (int i = 0; i < loopB; i++) {
				double temp = SpeedTest.Run (ecdh, loopA);
				result = Math.Min (result, temp);
			}
			return result;
		}
Exemplo n.º 2
0
        public void PerformTest()
        {
            // Read the public key
            PgpPublicKeyRing pubKeyRing = new PgpPublicKeyRing(testPubKey);

            DoBasicKeyRingCheck(pubKeyRing);

            // Read the private key
            PgpSecretKeyRing secretKeyRing = new PgpSecretKeyRing(testPrivKey);

            TestDecrypt(secretKeyRing);

            EncryptDecryptTest(ECDiffieHellman.Create(ECCurve.NamedCurves.nistP256));

            EncryptDecryptTest(new X25519());
        }
Exemplo n.º 3
0
        // Derives the shared secret between the client and enclave.
        private byte[] GetSharedSecret(EnclavePublicKey enclavePublicKey, EnclaveDiffieHellmanInfo enclaveDHInfo, ECDiffieHellman clientDHKey)
        {
            // Perform signature verification. The enclave's DiffieHellman public key was signed by the enclave's RSA public key.
            using (RSA rsa = KeyConverter.CreateRSAFromPublicKeyBlob(enclavePublicKey.PublicKey))
            {
                if (!rsa.VerifyData(enclaveDHInfo.PublicKey, enclaveDHInfo.PublicKeySignature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1))
                {
                    throw new ArgumentException(Strings.GetSharedSecretFailed);
                }
            }

            using (ECDiffieHellman ecdh = KeyConverter.CreateECDiffieHellmanFromPublicKeyBlob(enclaveDHInfo.PublicKey))
            {
                return(KeyConverter.DeriveKey(clientDHKey, ecdh.PublicKey));
            }
        }
        public static void HmacDerivationVariesOnKey()
        {
            byte[] hmacKeyAlice = { 0, 1, 2, 3, 4, 5 };
            byte[] hmacKeyBob   = { 10, 1, 2, 3, 4, 5 };

            using (ECDiffieHellman alice = ECDiffieHellmanFactory.Create())
                using (ECDiffieHellman bob = ECDiffieHellmanFactory.Create())
                    using (ECDiffieHellmanPublicKey alicePublic = alice.PublicKey)
                        using (ECDiffieHellmanPublicKey bobPublic = bob.PublicKey)
                        {
                            byte[] aliceDerived = alice.DeriveKeyFromHmac(bobPublic, HashAlgorithmName.SHA512, hmacKeyAlice);
                            byte[] bobDerived   = bob.DeriveKeyFromHmac(alicePublic, HashAlgorithmName.SHA512, hmacKeyBob);

                            Assert.NotEqual(aliceDerived, bobDerived);
                        }
        }
        internal MessageClientIdentity(string systemName, string clientName, ECDiffieHellman dh, bool isPrivateIdentity)
        {
            SystemName      = systemName;
            Name            = clientName;
            ECDiffieHellman = dh;

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                ECDsa = new ECDsaCng();
            }
            else
            {
                ECDsa = new ECDsaOpenSsl();
            }

            ECDsa.ImportParameters(dh.ExportExplicitParameters(isPrivateIdentity));
        }
        public static void HashDerivationVariesOnPrepend()
        {
            byte[] alicePrefix = new byte[10];
            byte[] bobPrefix   = new byte[alicePrefix.Length];
            bobPrefix[0] = 0xFF;

            using (ECDiffieHellman alice = ECDiffieHellmanFactory.Create())
                using (ECDiffieHellman bob = ECDiffieHellmanFactory.Create())
                    using (ECDiffieHellmanPublicKey alicePublic = alice.PublicKey)
                        using (ECDiffieHellmanPublicKey bobPublic = bob.PublicKey)
                        {
                            byte[] aliceDerived = alice.DeriveKeyFromHash(bobPublic, HashAlgorithmName.SHA512, alicePrefix, null);
                            byte[] bobDerived   = alice.DeriveKeyFromHash(alicePublic, HashAlgorithmName.SHA512, bobPrefix, null);

                            Assert.NotEqual(aliceDerived, bobDerived);
                        }
        }
        public static void HmacDerivationVariesOnAppend()
        {
            byte[] aliceSuffix = new byte[10];
            byte[] bobSuffix   = new byte[aliceSuffix.Length];
            bobSuffix[0] = 0xFF;

            using (ECDiffieHellman alice = ECDiffieHellmanFactory.Create())
                using (ECDiffieHellman bob = ECDiffieHellmanFactory.Create())
                    using (ECDiffieHellmanPublicKey alicePublic = alice.PublicKey)
                        using (ECDiffieHellmanPublicKey bobPublic = bob.PublicKey)
                        {
                            byte[] aliceDerived = alice.DeriveKeyFromHmac(bobPublic, HashAlgorithmName.SHA512, s_sampleHmacKey, null, aliceSuffix);
                            byte[] bobDerived   = bob.DeriveKeyFromHmac(alicePublic, HashAlgorithmName.SHA512, s_sampleHmacKey, null, bobSuffix);

                            Assert.NotEqual(aliceDerived, bobDerived);
                        }
        }
Exemplo n.º 8
0
        public ICertificatePal CopyWithPrivateKey(ECDiffieHellman privateKey)
        {
            var typedKey = privateKey as ECDiffieHellmanImplementation.ECDiffieHellmanSecurityTransforms;

            if (typedKey != null)
            {
                return(CopyWithPrivateKey(typedKey.GetKeys().PrivateKey));
            }

            byte[] ecPrivateKey = privateKey.ExportECPrivateKey();

            using (PinAndClear.Track(ecPrivateKey))
                using (SafeSecKeyRefHandle privateSecKey = Interop.AppleCrypto.ImportEphemeralKey(ecPrivateKey, true))
                {
                    return(CopyWithPrivateKey(privateSecKey));
                }
        }
Exemplo n.º 9
0
        public static void TlsPrfVariesOnSeed()
        {
            byte[] aliceSeed = s_emptySeed;
            byte[] bobSeed   = new byte[64];
            bobSeed[0] = 0x81;

            using (ECDiffieHellman alice = ECDiffieHellmanFactory.Create())
                using (ECDiffieHellman bob = ECDiffieHellmanFactory.Create())
                    using (ECDiffieHellmanPublicKey alicePublic = alice.PublicKey)
                        using (ECDiffieHellmanPublicKey bobPublic = bob.PublicKey)
                        {
                            byte[] aliceDerived = alice.DeriveKeyTls(bobPublic, s_fourByteLabel, aliceSeed);
                            byte[] bobDerived   = bob.DeriveKeyTls(alicePublic, s_fourByteLabel, bobSeed);

                            Assert.NotEqual(aliceDerived, bobDerived);
                        }
        }
Exemplo n.º 10
0
        /// <inheritsdoc />
        public override bool TryUnwrapKey(ReadOnlySpan <byte> keyBytes, Span <byte> destination, JwtHeader header, out int bytesWritten)
        {
            if (_disposed)
            {
                ThrowHelper.ThrowObjectDisposedException(GetType());
            }

            var epk = header.Epk;

            if (epk is null)
            {
                ThrowHelper.ThrowJwtDescriptorException_HeaderIsRequired(HeaderParameters.EpkUtf8);
            }

            byte[] secretAppend = BuildSecretAppend(header.Apu, header.Apv);
            byte[] exchangeHash;
            using (var ephemeralKey = ECDiffieHellman.Create(epk.ExportParameters()))
                using (var privateKey = ECDiffieHellman.Create(((ECJwk)Key).ExportParameters(true)))
                {
                    if (ephemeralKey.KeySize != privateKey.KeySize)
                    {
                        return(ThrowHelper.TryWriteError(out bytesWritten));
                    }

                    exchangeHash = privateKey.DeriveKeyFromHash(ephemeralKey.PublicKey, _hashAlgorithm, _secretPreprend, secretAppend);
                }

            if (Algorithm.ProduceEncryptionKey)
            {
                using var key = SymmetricJwk.FromSpan(new ReadOnlySpan <byte>(exchangeHash, 0, _keySizeInBytes), false);
                if (key.TryGetKeyUnwrapper(EncryptionAlgorithm, Algorithm.WrappedAlgorithm, out var keyUnwrapper))
                {
                    return(keyUnwrapper.TryUnwrapKey(keyBytes, destination, header, out bytesWritten));
                }
                else
                {
                    return(ThrowHelper.TryWriteError(out bytesWritten));
                }
            }
            else
            {
                new ReadOnlySpan <byte>(exchangeHash, 0, _keySizeInBytes).CopyTo(destination);
                bytesWritten = destination.Length;
                return(true);
            }
        }
Exemplo n.º 11
0
        public static void RunECDHE(int iterations)
        {
            Console.WriteLine("Running " + iterations + " diffie hellman key exchanges");

            Stopwatch watch = new Stopwatch();

            for (int i = 0; i < iterations; i++)
            {
                watch.Start();

                // Both create their instances
                ECDiffieHellman serverDiffie = new ECDiffieHellman();
                ECDiffieHellman clientDiffie = new ECDiffieHellman();

                // Exchange publics

                /* START TRANSMISSION */
                byte[] serverPublic = serverDiffie.GetPublicKey();
                byte[] clientPublic = clientDiffie.GetPublicKey();
                /* END TRANSMISSION */

                // Calculate shared
                byte[] key1 = serverDiffie.GetSharedSecretRaw(clientPublic);
                byte[] key2 = clientDiffie.GetSharedSecretRaw(serverPublic);

                watch.Stop();

                if (key1.Length != key2.Length)
                {
                    Console.WriteLine("CRITICAL: LENGTH MISSMATCH");
                    continue;
                }

                for (int x = 0; x < key1.Length; x++)
                {
                    if (key1[x] != key2[x])
                    {
                        Console.WriteLine("CRITICAL: MISSMATCH");
                        break;
                    }
                }
            }

            Console.WriteLine("Completed in " + watch.ElapsedMilliseconds + " ms, " + (watch.ElapsedMilliseconds / iterations) + " ms per exchange");
        }
Exemplo n.º 12
0
        public static void UseAfterDispose(bool importKey)
        {
            ECDiffieHellman          key = ECDiffieHellmanFactory.Create();
            ECDiffieHellmanPublicKey pubKey;
            HashAlgorithmName        hash = HashAlgorithmName.SHA256;

            if (importKey)
            {
                key.ImportParameters(EccTestData.GetNistP256ReferenceKey());
            }

            // Ensure the key is populated, then dispose it.
            using (key)
            {
                pubKey = key.PublicKey;
                key.DeriveKeyFromHash(pubKey, hash);

                pubKey.Dispose();
                Assert.Throws <ObjectDisposedException>(() => key.DeriveKeyFromHash(pubKey, hash));
                Assert.Throws <ObjectDisposedException>(() => key.DeriveKeyFromHmac(pubKey, hash, null));
                Assert.Throws <ObjectDisposedException>(() => key.DeriveKeyFromHmac(pubKey, hash, new byte[3]));
                Assert.Throws <ObjectDisposedException>(() => key.DeriveKeyTls(pubKey, new byte[4], new byte[64]));

                pubKey = key.PublicKey;
            }

            key.Dispose();

            Assert.Throws <ObjectDisposedException>(() => key.DeriveKeyFromHash(pubKey, hash));
            Assert.Throws <ObjectDisposedException>(() => key.DeriveKeyFromHmac(pubKey, hash, null));
            Assert.Throws <ObjectDisposedException>(() => key.DeriveKeyFromHmac(pubKey, hash, new byte[3]));
            Assert.Throws <ObjectDisposedException>(() => key.DeriveKeyTls(pubKey, new byte[4], new byte[64]));
            Assert.Throws <ObjectDisposedException>(() => key.GenerateKey(ECCurve.NamedCurves.nistP256));
            Assert.Throws <ObjectDisposedException>(() => key.ImportParameters(EccTestData.GetNistP256ReferenceKey()));

            // Either set_KeySize or the ExportParameters should throw.
            Assert.Throws <ObjectDisposedException>(
                () =>
            {
                key.KeySize = 384;
                key.ExportParameters(false);
            });

            pubKey.Dispose();
        }
Exemplo n.º 13
0
        public static void ExportSubjectPublicKeyInfo_ECDH()
        {
            using ECDiffieHellman ecdh = ECDiffieHellman.Create();
            ecdh.ImportFromPem(TestData.EcDhPkcs8Key);
            PublicKey key = new PublicKey(ecdh);

            Span <byte> algSpki = ecdh.ExportSubjectPublicKeyInfo();

            Assert.True(algSpki.SequenceEqual(key.ExportSubjectPublicKeyInfo()), "SequenceEquals(ExportSubjectPublicKeyInfo)");

            // Just right
            Assert.True(key.TryExportSubjectPublicKeyInfo(algSpki, out int written), nameof(key.TryExportSubjectPublicKeyInfo));
            Assert.Equal(algSpki.Length, written);

            // Too small
            Assert.False(key.TryExportSubjectPublicKeyInfo(algSpki.Slice(1), out written), nameof(key.TryExportSubjectPublicKeyInfo));
            Assert.Equal(0, written);
        }
Exemplo n.º 14
0
        public void Test_GEC2()
        {
            ECDiffieHellman U       = new ECDiffieHellman(ECDomainNames.secp160r1);
            ECDiffieHellman V       = new ECDiffieHellman(ECDomainNames.secp160r1);
            int             byteLen = (int)((U.Parameters.Domain.Bits >> 3) + ((U.Parameters.Domain.Bits & 7) == 0 ? 0 : 1));

            U.Parameters.PrivateKey = Number.Parse("971761939728640320549601132085879836204587084162", 10).ToByteArray(byteLen, false);
            V.Parameters.PrivateKey = Number.Parse("399525573676508631577122671218044116107572676710", 10).ToByteArray(byteLen, false);

            int keyDataLen = 20;

            byte[] kU = U.PerformKeyAgreement(V.Parameters.PublicKey, keyDataLen);
            byte[] kV = V.PerformKeyAgreement(U.Parameters.PublicKey, keyDataLen);
            Assert.AreEqual(kU, kV, "#1");

            byte[] expected = Number.Parse("744AB703F5BC082E59185F6D049D2D367DB245C2", 16).ToByteArray(20, false);
            Assert.AreEqual(kU, expected, "#2");
        }
        // Derives the shared secret between the client and enclave.
        private byte[] GetSharedSecret(EnclavePublicKey enclavePublicKey, EnclaveDiffieHellmanInfo enclaveDHInfo, ECDiffieHellman clientDHKey)
        {
            // Perform signature verification. The enclave's DiffieHellman public key was signed by the enclave's RSA public key.
            RSAParameters rsaParams = KeyConverter.RSAPublicKeyBlobToParams(enclavePublicKey.PublicKey);

            using (RSA rsa = RSA.Create(rsaParams))
            {
                if (!rsa.VerifyData(enclaveDHInfo.PublicKey, enclaveDHInfo.PublicKeySignature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1))
                {
                    throw new ArgumentException(Strings.GetSharedSecretFailed);
                }
            }

            ECParameters    ecParams     = KeyConverter.ECCPublicKeyBlobToParams(enclaveDHInfo.PublicKey);
            ECDiffieHellman enclaveDHKey = ECDiffieHellman.Create(ecParams);

            return(clientDHKey.DeriveKeyFromHash(enclaveDHKey.PublicKey, HashAlgorithmName.SHA256));
        }
        // Serializes an ECDiffieHellmanPublicKey to an ECC public key blob
        // "ECDiffieHellmanPublicKey.ToByteArray() doesn't have a (standards-)defined export
        // format. The version used by ECDiffieHellmanPublicKeyCng is Windows-specific"
        // from https://github.com/dotnet/runtime/issues/27276
        // => ECDiffieHellmanPublicKey.ToByteArray() is not supported in Unix
        internal static byte[] GetECDiffieHellmanPublicKeyBlob(ECDiffieHellman ecDiffieHellman)
        {
            byte[] keyBlob = new byte[ECCPublicKeyBlob.Size];

            // Set magic number
            Buffer.BlockCopy(KeyBlobMagicNumber.ECDHPublicP384, 0, keyBlob, 0, 4);
            // Set key size
            keyBlob[4] = (byte)ECCPublicKeyBlob.KeySize;

            ECPoint ecPoint = ecDiffieHellman.PublicKey.ExportParameters().Q;

            Debug.Assert(ecPoint.X.Length == ECCPublicKeyBlob.KeySize && ecPoint.Y.Length == ECCPublicKeyBlob.KeySize,
                         $"ECDH public key was not the expected length. Actual (X): {ecPoint.X.Length}. Actual (Y): {ecPoint.Y.Length} Expected: {ECCPublicKeyBlob.Size}");
            // Copy x and y coordinates to key blob
            Buffer.BlockCopy(ecPoint.X, 0, keyBlob, ECCPublicKeyBlob.HeaderSize, ECCPublicKeyBlob.KeySize);
            Buffer.BlockCopy(ecPoint.Y, 0, keyBlob, ECCPublicKeyBlob.HeaderSize + ECCPublicKeyBlob.KeySize, ECCPublicKeyBlob.KeySize);
            return(keyBlob);
        }
Exemplo n.º 17
0
        public static Hash EncryptString(ByteString data, ECKeyPair keyPair)
        {
#if NETCOREAPP
            throw new NotImplementedException();
#else
            using (var ecDiffieHellman = ECDiffieHellman.Create(keyPair))
            {
                using (var ephem = ECDiffieHellman.Create(keyPair.ECParameters.Curve))
                {
                    ECParameters ephemPublicParams = ephem.ExportParameters(false);
                    int          pointLen          = ephemPublicParams.Q.X.Length;
                    byte[]       rBar = new byte[pointLen * 2 + 1];
                    rBar[0] = (byte)(keyPair.PublicKey.X.Length + keyPair.PublicKey.Y.Length);
                    Buffer.BlockCopy(ephemPublicParams.Q.X, 0, rBar, 1, pointLen);
                    Buffer.BlockCopy(ephemPublicParams.Q.Y, 0, rBar, 1 + pointLen, pointLen);
                    var ek = ephem.DeriveKeyFromHash(ecDiffieHellman.PublicKey, HashAlgorithmName.SHA256, null,
                                                     new byte[] { 0, 0, 0, 1 });
                    var mk = ephem.DeriveKeyFromHash(ecDiffieHellman.PublicKey, HashAlgorithmName.SHA256, null,
                                                     new byte[] { 0, 0, 0, 2 });

                    using (RijndaelManaged aes = new RijndaelManaged())
                    {
                        aes.Padding = PaddingMode.PKCS7;
                        using (ICryptoTransform encryptor = aes.CreateEncryptor(ek, new byte[16]))
                        {
                            if (!encryptor.CanTransformMultipleBlocks)
                            {
                                throw new InvalidOperationException();
                            }

                            Hash   em = encryptor.TransformFinalBlock(data, 0, data.Length);
                            byte[] da;
                            using (HMAC hmac = new HMACSHA256(mk))
                            {
                                da = hmac.ComputeHash(em);
                            }

                            return(rBar.Concat((byte[])em).Concat(da).ToArray());
                        }
                    }
                }
            }
#endif
        }
Exemplo n.º 18
0
        public ECDiffieHellmanKey(
            ECDiffieHellman ecdh,
            PgpHashAlgorithm hashAlgorithm,
            PgpSymmetricKeyAlgorithm symmetricAlgorithm,
            byte[] fingerprint)
        {
            if (fingerprint == null)
            {
                throw new ArgumentNullException(nameof(fingerprint));
            }

            this.ecdh               = ecdh;
            this.hashAlgorithm      = hashAlgorithm;
            this.symmetricAlgorithm = symmetricAlgorithm;
            this.fingerprint        = fingerprint;

            VerifyHashAlgorithm();
            VerifySymmetricKeyAlgorithm();
        }
Exemplo n.º 19
0
        public static double Run(ECDiffieHellman ecdh, int loop)
        {
            Stopwatch sw         = new Stopwatch();
            int       keyDataLen = 20;

            byte[] otherPublicKey = ecdh.Parameters.PublicKey;

            // re-generate key
            ecdh.Parameters.PrivateKey = null;

            ecdh.PerformKeyAgreement(otherPublicKey, keyDataLen);
            sw.Reset(); sw.Start();
            for (int i = 0; i < loop; i++)
            {
                ecdh.PerformKeyAgreement(otherPublicKey, keyDataLen);
            }
            sw.Stop();
            return(sw.Elapsed.TotalMilliseconds / (double)loop);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Encrypt a plain text m,essage using the public key and deriving a shared key
        /// ONLY A TEST FUNCTION
        /// </summary>
        /// <param name="publicKey"></param>
        /// <param name="plainText"></param>
        /// <returns></returns>
        private byte[] EncryptText(byte[] publicKey, string plainText)
        {
            var cipher2 = ECDiffieHellman.Create();

            cipher2.KeySize = cipher.KeySize;
            var pubKey2 = cipher2.ExportSubjectPublicKeyInfo();
            var cipher3 = ECDiffieHellman.Create();

            cipher3.KeySize = cipher.KeySize;
            cipher3.ImportSubjectPublicKeyInfo(publicKey, out _);
            var cipher2Key = cipher2.DeriveKeyMaterial(cipher3.PublicKey);

            byte[] encryptedMessage;
            byte[] iv;
            using (Aes aes = new AesCryptoServiceProvider())
            {
                aes.Key = cipher2Key;
                iv      = aes.IV;

                // Encrypt the message
                using MemoryStream ciphertext = new MemoryStream();
                using CryptoStream cs         = new CryptoStream(ciphertext, aes.CreateEncryptor(), CryptoStreamMode.Write);
                var plaintextMessage = Encoding.UTF8.GetBytes(plainText);
                cs.Write(plaintextMessage, 0, plaintextMessage.Length);
                cs.Close();
                encryptedMessage = ciphertext.ToArray();
            }
            using (Aes aes = new AesCryptoServiceProvider())
            {
                cipher3.ImportSubjectPublicKeyInfo(pubKey2, out _);
                aes.Key = cipher.DeriveKeyMaterial(cipher3.PublicKey);
                aes.IV  = iv;

                // Decrypt the message
                using MemoryStream plaintext = new MemoryStream();
                using CryptoStream cs        = new CryptoStream(plaintext, aes.CreateDecryptor(), CryptoStreamMode.Write);
                cs.Write(encryptedMessage, 0, encryptedMessage.Length);
                cs.Close();
                string message = Encoding.UTF8.GetString(plaintext.ToArray());
                Console.WriteLine(message);
            }
            return(iv);
        }
Exemplo n.º 21
0
        public void Create_ECDiffieHellman()
        {
            #region Arrange

            #endregion

            #region Act

            var result = Encryption.NitroKey.EllipticCurveCryptographer.GetPublicKey("Brainpool #1", Constants.TestPin);

            #endregion

            #region Assert

            Console.Out.WriteLine(result.ToJson);
            Assert.DoesNotThrow(() => ECDiffieHellman.Create(result.CreateECParameters()));

            #endregion
        }
        // When overridden in a derived class, performs enclave attestation, generates a symmetric key for the session, creates a an enclave session and stores the session information in the cache.
        internal override void CreateEnclaveSession(byte[] attestationInfo, ECDiffieHellman clientDHKey, EnclaveSessionParameters enclaveSessionParameters, byte[] customData, int customDataLength, out SqlEnclaveSession sqlEnclaveSession, out long counter)
        {
            sqlEnclaveSession = null;
            counter           = 0;
            try
            {
                ThreadRetryCache.Remove(Thread.CurrentThread.ManagedThreadId.ToString());
                sqlEnclaveSession = GetEnclaveSessionFromCache(enclaveSessionParameters, out counter);
                if (sqlEnclaveSession == null)
                {
                    if (!string.IsNullOrEmpty(enclaveSessionParameters.AttestationUrl) && customData != null && customDataLength > 0)
                    {
                        byte[] nonce = customData;

                        IdentityModelEventSource.ShowPII = true;

                        // Deserialize the payload
                        AzureAttestationInfo attestInfo = new AzureAttestationInfo(attestationInfo);

                        // Validate the attestation info
                        VerifyAzureAttestationInfo(enclaveSessionParameters.AttestationUrl, attestInfo.EnclaveType, attestInfo.AttestationToken.AttestationToken, attestInfo.Identity, nonce);

                        // Set up shared secret and validate signature
                        byte[] sharedSecret = GetSharedSecret(attestInfo.Identity, nonce, attestInfo.EnclaveType, attestInfo.EnclaveDHInfo, clientDHKey);

                        // add session to cache
                        sqlEnclaveSession = AddEnclaveSessionToCache(enclaveSessionParameters, sharedSecret, attestInfo.SessionId, out counter);
                    }
                    else
                    {
                        throw SQL.AttestationFailed(Strings.FailToCreateEnclaveSession);
                    }
                }
            }
            finally
            {
                // As per current design, we want to minimize the number of create session calls. To achieve this we block all the GetEnclaveSession calls until the first call to
                // GetEnclaveSession -> GetAttestationParameters -> CreateEnclaveSession completes or the event timeout happen.
                // Case 1: When the first request successfully creates the session, then all outstanding GetEnclaveSession will use the current session.
                // Case 2: When the first request unable to create the enclave session (may be due to some error or the first request doesn't require enclave computation) then in those case we set the event timeout to 0.
                UpdateEnclaveSessionLockStatus(sqlEnclaveSession);
            }
        }
        public static void HashDerivation_KnownResults(
            HashAlgorithmName hashAlgorithm,
            string prependBytes,
            string appendBytes,
            string answerBytes)
        {
            byte[] prepend = prependBytes?.HexToByteArray();
            byte[] append  = appendBytes?.HexToByteArray();
            byte[] answer  = answerBytes.HexToByteArray();
            byte[] output;

            using (ECDiffieHellman ecdh = OpenKnownKey())
                using (ECDiffieHellmanPublicKey publicKey = ecdh.PublicKey)
                {
                    output = ecdh.DeriveKeyFromHash(publicKey, hashAlgorithm, prepend, append);
                }

            Assert.Equal(answer, output);
        }
Exemplo n.º 24
0
        public void TestMethod1()
        {
            string b64InputKey = "MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEVQxN/wFsMiYihwv1psUgKRIhgX02OPBQl0aKYNtKXoCk67hE/lsR8UC77Fqm1HPuMALWG8RcihSHoZwx2HfOz11QkwvlKEf8UuMrbp0yt/mQNJx6QQm6CiZ7e63sYqdV";

            ECPublicKeyParameters asyKey = (ECPublicKeyParameters)
                                           PublicKeyFactory.CreateKey(b64InputKey.DecodeBase64Url());

            ECParameters param = new ECParameters();

            param.Curve = ECCurve.NamedCurves.nistP384;
            param.Q.X   = asyKey.Q.AffineXCoord.GetEncoded();
            param.Q.Y   = asyKey.Q.AffineYCoord.GetEncoded();

            var ecPublicKey = ECDiffieHellman.Create(param).PublicKey;

            var          effi          = ECDiffieHellman.Create(ECCurve.NamedCurves.nistP384);
            ECParameters privateKey    = effi.ExportParameters(true);
            var          secretPrepend = Encoding.UTF8.GetBytes("RANDOM SECRET");

            byte[] secret = effi.DeriveKeyFromHash(ecPublicKey, HashAlgorithmName.SHA256, secretPrepend, new byte[0]);

            IBufferedCipher decryptor = CipherUtilities.GetCipher("AES/CFB8/NoPadding");
            IBufferedCipher encryptor = CipherUtilities.GetCipher("AES/CFB8/NoPadding");

            decryptor.Init(false, new ParametersWithIV(new KeyParameter(secret), secret.Take(16).ToArray()));

            encryptor.Init(true, new ParametersWithIV(new KeyParameter(secret), secret.Take(16).ToArray()));

            string b64PublicKey  = effi.PublicKey.ToDerEncoded().EncodeBase64();
            var    handshakeJson = new HandshakeData()
            {
                salt = secretPrepend.EncodeBase64()
            };

            var signKey = ECDsa.Create(privateKey);

            string val = JWT.Encode(handshakeJson, signKey, JwsAlgorithm.ES384, new Dictionary <string, object> {
                { "x5u", b64PublicKey }
            });
            //Log.Warn($"Headers: {string.Join(";", JWT.Headers(val))}");
            //Log.Warn($"Return salt:\n{JWT.Payload(val)}");
        }
        private static void VerifyNamedCurve(ECParameters parameters, ECDiffieHellman ec, int keySize, bool includePrivate)
        {
            parameters.Validate();
            Assert.True(parameters.Curve.IsNamed);
            Assert.Equal(keySize, ec.KeySize);
            Assert.True(
                includePrivate && parameters.D.Length > 0 ||
                !includePrivate && parameters.D == null);

            if (includePrivate)
            {
                ec.Exercise();
            }

            // Ensure the key doesn't get regenerated after export
            ECParameters paramSecondExport = ec.ExportParameters(includePrivate);

            paramSecondExport.Validate();
            AssertEqual(parameters, paramSecondExport);
        }
Exemplo n.º 26
0
        public static void ECCurve_ctor()
        {
            using (ECDiffieHellman ecdh = ECDiffieHellmanFactory.Create(ECCurve.NamedCurves.nistP256))
            {
                Assert.Equal(256, ecdh.KeySize);
                ecdh.Exercise();
            }

            using (ECDiffieHellman ecdh = ECDiffieHellmanFactory.Create(ECCurve.NamedCurves.nistP384))
            {
                Assert.Equal(384, ecdh.KeySize);
                ecdh.Exercise();
            }

            using (ECDiffieHellman ecdh = ECDiffieHellmanFactory.Create(ECCurve.NamedCurves.nistP521))
            {
                Assert.Equal(521, ecdh.KeySize);
                ecdh.Exercise();
            }
        }
Exemplo n.º 27
0
        public override void Initialize()
        {
            var kexAlgorithm = session.Algorithms.KexAlgorithms[0];

            switch (kexAlgorithm)
            {
            case "*****@*****.**": ecdh = new Curve25519Managed(); break;

            case "ecdh-sha2-nistp521": ecdh = new ECDiffieHellmanManaged(MathEC.ECCurve.secp521r1); break;

            case "ecdh-sha2-nistp384": ecdh = new ECDiffieHellmanManaged(MathEC.ECCurve.secp384r1); break;

            case "ecdh-sha2-nistp256":
            default: ecdh = new ECDiffieHellmanManaged(MathEC.ECCurve.secp256r1); break;
            }

            var ecdhInit = new SshECDHKexInit(ecdh.PublicKey.ToByteArray());

            session.Socket.WritePacket(ecdhInit);
        }
Exemplo n.º 28
0
        public static void TestECDHPublicKey_DeriveSecret()
        {
            using (var publicEcdhCert = new X509Certificate2(TestData.EccCert_KeyAgreement))
                using (ECDiffieHellman otherParty = ECDiffieHellman.Create())
                    using (ECDiffieHellman publicKey = publicEcdhCert.GetECDiffieHellmanPublicKey())
                    {
                        otherParty.ImportFromPem(TestData.EcDhPkcs8Key);
                        byte[] key = otherParty.DeriveKeyFromHash(publicKey.PublicKey, HashAlgorithmName.SHA256);

                        byte[] expectedKey = new byte[]
                        {
                            0x3f, 0x67, 0x8f, 0x51, 0xa0, 0x91, 0xfa, 0x5d,
                            0x38, 0x00, 0x92, 0xd3, 0x5b, 0x29, 0xd4, 0x00,
                            0x1c, 0x4a, 0x8f, 0x30, 0x7d, 0x78, 0xf4, 0x79,
                            0xed, 0x3d, 0x0b, 0x23, 0xdc, 0xfa, 0x26, 0x57
                        };

                        Assert.Equal(expectedKey, key);
                    }
        }
Exemplo n.º 29
0
        public ECDiffieHellman?GetECDiffieHellmanPublicKey()
        {
            if (_oid.Value != Oids.EcPublicKey)
            {
                return(null);
            }

            ECDiffieHellman ecdh = ECDiffieHellman.Create();

            try
            {
                ecdh.ImportSubjectPublicKeyInfo(ExportSubjectPublicKeyInfo(), out _);
                return(ecdh);
            }
            catch
            {
                ecdh.Dispose();
                throw;
            }
        }
Exemplo n.º 30
0
        /// <inheritsdoc />
        public override SymmetricJwk WrapKey(Jwk?staticKey, JwtHeader header, Span <byte> destination)
        {
            Debug.Assert(header != null);

            var partyUInfo   = GetPartyInfo(header, JwtHeaderParameterNames.Apu);
            var partyVInfo   = GetPartyInfo(header, JwtHeaderParameterNames.Apv);
            var secretAppend = BuildSecretAppend(partyUInfo, partyVInfo);
            ReadOnlySpan <byte> exchangeHash;
            var             ecKey         = _key;
            var             otherPartyKey = ecKey.CreateEcdhKey();
            ECDiffieHellman ephemeralKey  = (staticKey is null) ? ECDiffieHellman.Create(ecKey.Crv.CurveParameters) : ((ECJwk)staticKey).CreateEcdhKey();

            try
            {
                exchangeHash = new ReadOnlySpan <byte>(ephemeralKey.DeriveKeyFromHash(otherPartyKey.PublicKey, _hashAlgorithm, _secretPreprend, secretAppend), 0, _keySizeInBytes);
                var epk = ECJwk.FromParameters(ephemeralKey.ExportParameters(false));
                header.Add(JwtHeaderParameterNames.Epk, epk);
            }
            finally
            {
                if (staticKey is null)
                {
                    ephemeralKey.Dispose();
                }
            }

            SymmetricJwk contentEncryptionKey;

            if (Algorithm.ProduceEncryptionKey)
            {
                using var keyWrapper = new AesKeyWrapper(exchangeHash, EncryptionAlgorithm, _keyManagementAlgorithm !);
                contentEncryptionKey = keyWrapper.WrapKey(null, header, destination);
            }
            else
            {
                exchangeHash.CopyTo(destination);
                contentEncryptionKey = SymmetricJwk.FromSpan(exchangeHash, false);
            }

            return(contentEncryptionKey);
        }
        public static void TestGeneralExportWithExplicitParameters()
        {
            if (!ECDiffieHellmanFactory.ExplicitCurvesSupported)
            {
                return;
            }

            using (ECDiffieHellman ecdsa = ECDiffieHellmanFactory.Create())
            {
                ECParameters param = EccTestData.GetNistP256ExplicitTestData();
                param.Validate();
                ecdsa.ImportParameters(param);
                Assert.True(param.Curve.IsExplicit);

                param = ecdsa.ExportParameters(false);
                param.Validate();

                // We should have explicit values, not named, as this curve has no name.
                Assert.True(param.Curve.IsExplicit);
            }
        }
Exemplo n.º 32
0
 public ECDHE_ECDSA(ECDSA ecdsa)
 {
     _ecdh = new ECDiffieHellman (openCrypto.EllipticCurve.ECDomainNames.secp256r1);
     _ecdh.KDF = null;
     _ecdsa = ecdsa;
 }