public static CngKey Create(CngAlgorithm algorithm, string keyName, CngKeyCreationParameters creationParameters)
 {
     if (algorithm == null)
     {
         throw new ArgumentNullException("algorithm");
     }
     if (creationParameters == null)
     {
         creationParameters = new CngKeyCreationParameters();
     }
     if (!NCryptNative.NCryptSupported)
     {
         throw new PlatformNotSupportedException(System.SR.GetString("Cryptography_PlatformNotSupported"));
     }
     if (keyName != null)
     {
         KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(keyName, KeyContainerPermissionFlags.Create) {
             ProviderName = creationParameters.Provider.Provider
         };
         KeyContainerPermission permission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
         permission.AccessEntries.Add(accessEntry);
         permission.Demand();
     }
     SafeNCryptProviderHandle provider = NCryptNative.OpenStorageProvider(creationParameters.Provider.Provider);
     SafeNCryptKeyHandle keyHandle = NCryptNative.CreatePersistedKey(provider, algorithm.Algorithm, keyName, creationParameters.KeyCreationOptions);
     SetKeyProperties(keyHandle, creationParameters);
     NCryptNative.FinalizeKey(keyHandle);
     CngKey key = new CngKey(provider, keyHandle);
     if (keyName == null)
     {
         key.IsEphemeral = true;
     }
     return key;
 }
Ejemplo n.º 2
0
        private CngAlgorithm GetCngAlgorithm(HashAlgorithm hashAlgorithm)
        {
            CngAlgorithm cngAlgorithm = null;

            if (hashAlgorithm == null)
            {
                cngAlgorithm = CngAlgorithm.Sha1;
            }
            else if (hashAlgorithm is MD5)
            {
                cngAlgorithm = CngAlgorithm.MD5;
            }
            else if (hashAlgorithm is SHA1)
            {
                cngAlgorithm = CngAlgorithm.Sha1;
            }
            else if (hashAlgorithm is SHA256)
            {
                cngAlgorithm = CngAlgorithm.Sha256;
            }
            else if (hashAlgorithm is SHA384)
            {
                cngAlgorithm = CngAlgorithm.Sha384;
            }
            else if (hashAlgorithm is SHA512)
            {
                cngAlgorithm = CngAlgorithm.Sha512;
            }
            return(cngAlgorithm);
        }
Ejemplo n.º 3
0
        public CngKey GetOrGenerateKey(int keySize, CngAlgorithm algorithm)
        {
            // If our key size was changed, we need to generate a new key.
            if (_lazyKey != null)
            {
                if (_lazyKey.KeySize != keySize)
                    DisposeKey();
            }

            // If we don't have a key yet, we need to generate one now.
            if (_lazyKey == null)
            {
                CngKeyCreationParameters creationParameters = new CngKeyCreationParameters()
                {
                    ExportPolicy = CngExportPolicies.AllowPlaintextExport,
                };

                CngProperty keySizeProperty = new CngProperty(KeyPropertyName.Length, BitConverter.GetBytes(keySize), CngPropertyOptions.None);
                creationParameters.Parameters.Add(keySizeProperty);

                _lazyKey = CngKey.Create(algorithm, null, creationParameters);
            }

            return _lazyKey;
        }
Ejemplo n.º 4
0
        public static CngKey Create(CngAlgorithm algorithm, string keyName, CngKeyCreationParameters creationParameters)
        {
            if (algorithm == null)
                throw new ArgumentNullException("algorithm");

            if (creationParameters == null)
                creationParameters = new CngKeyCreationParameters();

            SafeNCryptProviderHandle providerHandle = creationParameters.Provider.OpenStorageProvider();
            SafeNCryptKeyHandle keyHandle;
            ErrorCode errorCode = Interop.NCrypt.NCryptCreatePersistedKey(providerHandle, out keyHandle, algorithm.Algorithm, keyName, 0, creationParameters.KeyCreationOptions);
            if (errorCode != ErrorCode.ERROR_SUCCESS)
                throw errorCode.ToCryptographicException();

            InitializeKeyProperties(keyHandle, creationParameters);

            errorCode = Interop.NCrypt.NCryptFinalizeKey(keyHandle, 0);
            if (errorCode != ErrorCode.ERROR_SUCCESS)
                throw errorCode.ToCryptographicException();

            CngKey key = new CngKey(providerHandle, keyHandle);

            // No name translates to an ephemeral key
            if (keyName == null)
            {
                key.IsEphemeral = true;
            }

            return key;
        }
Ejemplo n.º 5
0
 public static bool Verify(byte[] securedInput, byte[] signature, CngKey key, CngAlgorithm hash, int saltSize)
 {
     using (HashAlgorithm algo = HashAlgorithm(hash))
     {
         return(VerifyHash(algo.ComputeHash(securedInput), signature, key, hash.Algorithm, saltSize));
     }
 }
Ejemplo n.º 6
0
        private static ECDsa LoadBase58CngPublicKey(string publicKey, CngAlgorithm alg)
        {
            var ecDsaCng = new ECDsaCng(CngKey.Import(Base58Encoding.Decode(publicKey), CngKeyBlobFormat.EccPublicBlob));

            ecDsaCng.HashAlgorithm = alg;
            return(ecDsaCng);
        }
Ejemplo n.º 7
0
        private static ECDsa LoadBase64CngPublicKey(string publicKey, CngAlgorithm alg)
        {
            var ecDsaCng = new ECDsaCng(CngKey.Import(Convert.FromBase64String(publicKey), CngKeyBlobFormat.EccPublicBlob));

            ecDsaCng.HashAlgorithm = alg;
            return(ecDsaCng);
        }
Ejemplo n.º 8
0
        internal BCryptHMAC(CngAlgorithm algorithm,
                            CngProvider algorithmProvider,
                            string hashName,
                            int blockSize,
                            byte[] key)
        {
            Debug.Assert(algorithm != null, "algorithm != null");
            Debug.Assert(algorithmProvider != null, "algorithmProvider != null");
            Debug.Assert(!String.IsNullOrEmpty(hashName), "!String.IsNullOrEmpty(hashName)");
            Debug.Assert(blockSize > 0, "blockSize > 0");
            Debug.Assert(key != null, "key != null");

            BlockSizeValue = blockSize;
            HashName       = hashName;

            m_algorithm = BCryptNative.OpenAlgorithm(algorithm.Algorithm,
                                                     algorithmProvider.Provider,
                                                     BCryptNative.AlgorithmProviderOptions.HmacAlgorithm);

            // Resetting the key will call Initialize for us, and get us setup with a hash handle,
            // so we don't need to create the hash handle ourselves
            Key = key;

            HashSizeValue = BCryptNative.GetInt32Property(m_hash, BCryptNative.HashPropertyName.HashLength) * 8;
        }
Ejemplo n.º 9
0
        public CngKey GetOrGenerateKey(int keySize, CngAlgorithm algorithm)
        {
            // If our key size was changed, we need to generate a new key.
            if (_lazyKey != null)
            {
                if (_lazyKey.KeySize != keySize)
                {
                    DisposeKey();
                }
            }

            // If we don't have a key yet, we need to generate one now.
            if (_lazyKey == null)
            {
                CngKeyCreationParameters creationParameters = new CngKeyCreationParameters()
                {
                    ExportPolicy = CngExportPolicies.AllowPlaintextExport,
                };

                CngProperty keySizeProperty = new CngProperty(KeyPropertyName.Length, BitConverter.GetBytes(keySize), CngPropertyOptions.None);
                creationParameters.Parameters.Add(keySizeProperty);

                _lazyKey = CngKey.Create(algorithm, null, creationParameters);
            }

            return(_lazyKey);
        }
Ejemplo n.º 10
0
        //[Fact] - Keeping this test for reference but we don't want to run it as an inner-loop test because
        //         it creates a key on disk.
        public static void AesRoundTrip256BitsNoneECBUsingStoredKey()
        {
            CngAlgorithm algname = new CngAlgorithm("AES");
            string       keyName = "CoreFxTest-" + Guid.NewGuid();
            CngKey       _cngKey = CngKey.Create(algname, keyName);

            try
            {
                using (Aes alg = new AesCng(keyName))
                {
                    try
                    {
                        alg.Padding = PaddingMode.None;
                        alg.Mode    = CipherMode.ECB;

                        int keySize = alg.KeySize;

                        byte[] plainText         = "15a818701f0f7c99fe4b1b4b860f131b".HexToByteArray();
                        byte[] cipher            = alg.Encrypt(plainText);
                        byte[] decrypted         = alg.Decrypt(cipher);
                        byte[] expectedDecrypted = "15a818701f0f7c99fe4b1b4b860f131b".HexToByteArray();
                        Assert.Equal <byte>(expectedDecrypted, decrypted);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
                }
            }
            finally
            {
                _cngKey.Delete();
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Create a CNG Key and form as string.
        /// </summary>
        /// <param name="ca">The Algorithm.</param>
        /// <param name="cbf">The CNG Key Blob Format.</param>
        /// <returns>The key.</returns>
        public string GenerateCngKeyAsString(CngAlgorithm ca, CngKeyBlobFormat cbf)
        {
            CngKey ck = GenerateCngKey(ca);

            byte[] b = ck.Export(cbf);

            string[] s = new string[b.Length];

            int i = 0;

            foreach (byte v in b)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(v);

                s[i] = sb.ToString();
            }

            StringBuilder strb = new StringBuilder();

            foreach (string st in s)
            {
                strb.Append(st);
                strb.Append(',');
            }

            return(strb.ToString());
        }
        /// <summary>
        /// Constructs the core to use a stored CNG key.
        /// </summary>
        public CngSymmetricAlgorithmCore(string algorithm, ICngSymmetricAlgorithm outer, string keyName, CngProvider provider, CngKeyOpenOptions openOptions)
        {
            if (keyName == null)
            {
                throw new ArgumentNullException("keyName");
            }
            if (provider == null)
            {
                throw new ArgumentNullException("provider");
            }

            _algorithm = algorithm;
            _outer     = outer;

            _keyName       = keyName;
            _provider      = provider;
            _optionOptions = openOptions;

            using (CngKey cngKey = ProduceCngKey())
            {
                CngAlgorithm actualAlgorithm = cngKey.Algorithm;
                if (algorithm != actualAlgorithm.Algorithm)
                {
                    throw new CryptographicException(SR.GetString(SR.Cryptography_CngKeyWrongAlgorithm, actualAlgorithm.Algorithm, algorithm));
                }

                _outer.BaseKeySize = cngKey.KeySize;
            }
        }
Ejemplo n.º 13
0
 public static bool Verify(byte[] securedInput, byte[] signature, CngKey key, CngAlgorithm hash, int saltSize)
 {
     using (HashAlgorithm algo = HashAlgorithm(hash))
     {
         return VerifyHash(algo.ComputeHash(securedInput),signature, key, hash.Algorithm, saltSize);
     }
 }
Ejemplo n.º 14
0
 public static byte[] Sign(byte[] input, CngKey key, CngAlgorithm hash, int saltSize)
 {
     using (HashAlgorithm algo = HashAlgorithm(hash))
     {
         return(SignHash(algo.ComputeHash(input), key, hash.Algorithm, saltSize));
     }
 }
		public EcDsaPrivateKeyProvider(
			ID2LSecurityTokenFactory d2lSecurityTokenFactory,
			CngAlgorithm algorithm
		) {
			m_d2lSecurityTokenFactory = d2lSecurityTokenFactory;
			m_algorithm = algorithm;
		}
Ejemplo n.º 16
0
        public static void CreateEphemeral_WithParameters()
        {
            CngAlgorithm             alg = CngAlgorithm.ECDiffieHellmanP256;
            CngKeyCreationParameters p   = new CngKeyCreationParameters();

            p.ExportPolicy = CngExportPolicies.AllowExport;
            p.KeyUsage     = CngKeyUsages.KeyAgreement;
            p.UIPolicy     = new CngUIPolicy(CngUIProtectionLevels.ForceHighProtection, "MyFriendlyName", "MyDescription", "MyUseContext", "MyCreationTitle");
            byte[] myPropValue1 = "23afbc".HexToByteArray();
            p.Parameters.Add(new CngProperty("MyProp1", myPropValue1, CngPropertyOptions.CustomProperty));
            byte[] myPropValue2 = "8765".HexToByteArray();
            p.Parameters.Add(new CngProperty("MyProp2", myPropValue2, CngPropertyOptions.CustomProperty));

            using (CngKey key = CngKey.Create(alg, null, p))
            {
                Assert.Equal(CngAlgorithm.ECDiffieHellmanP256, key.Algorithm);
                Assert.Equal(CngExportPolicies.AllowExport, key.ExportPolicy);
                Assert.Equal(CngKeyUsages.KeyAgreement, key.KeyUsage);
                CngUIPolicy uiPolicy = key.UIPolicy;
                Assert.Equal(CngUIProtectionLevels.ForceHighProtection, uiPolicy.ProtectionLevel);
                Assert.Equal("MyFriendlyName", uiPolicy.FriendlyName);
                Assert.Equal("MyDescription", uiPolicy.Description);
                Assert.Equal("MyUseContext", uiPolicy.UseContext);
                Assert.Equal("MyCreationTitle", uiPolicy.CreationTitle);

                byte[] propValue1Actual = key.GetProperty("MyProp1", CngPropertyOptions.CustomProperty).GetValue();
                Assert.Equal <byte>(myPropValue1, propValue1Actual);

                byte[] propValue2Actual = key.GetProperty("MyProp2", CngPropertyOptions.CustomProperty).GetValue();
                Assert.Equal <byte>(myPropValue2, propValue2Actual);
            }
        }
Ejemplo n.º 17
0
        internal BCryptHMAC(CngAlgorithm algorithm,
                            CngProvider algorithmProvider,
                            string hashName,
                            int blockSize,
                            byte[] key)
        {
            Debug.Assert(algorithm != null, "algorithm != null");
            Debug.Assert(algorithmProvider != null, "algorithmProvider != null");
            Debug.Assert(!String.IsNullOrEmpty(hashName), "!String.IsNullOrEmpty(hashName)");
            Debug.Assert(blockSize > 0, "blockSize > 0");
            Debug.Assert(key != null, "key != null");

            BlockSizeValue = blockSize;
            HashName = hashName;

            m_algorithm = BCryptNative.OpenAlgorithm(algorithm.Algorithm,
                                                     algorithmProvider.Provider,
                                                     BCryptNative.AlgorithmProviderOptions.HmacAlgorithm);

            // Resetting the key will call Initialize for us, and get us setup with a hash handle,
            // so we don't need to create the hash handle ourselves
            Key = key;

            HashSizeValue = BCryptNative.GetInt32Property(m_hash, BCryptNative.HashPropertyName.HashLength) * 8;
        }
Ejemplo n.º 18
0
        public ECDiffieHellmanBc(Int32 keySize)
        {
            Org.BouncyCastle.Asn1.X9.X9ECParameters ecParams;
            switch (keySize) {
            case 256:
                ecParams = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256r1");
                break;
            case 384:
                ecParams = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp384r1");
                break;
            case 521:
                ecParams = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp521r1");
                break;
            default:
                throw new ArgumentException("ECDiffieHellman key size " + keySize + " not supported");
            }
            _keySize = keySize;
            _domainParameters = new ECDomainParameters(ecParams.Curve, ecParams.G, ecParams.N, ecParams.H, ecParams.GetSeed());

            // Initialize key generation parameters with new SecureRandom
            Org.BouncyCastle.Security.SecureRandom secureRandom = new Org.BouncyCastle.Security.SecureRandom();
            ECKeyGenerationParameters keyGenParams = new ECKeyGenerationParameters(_domainParameters, secureRandom);

            // Generate key pair from domain parameters
            Org.BouncyCastle.Crypto.Generators.ECKeyPairGenerator generator = new Org.BouncyCastle.Crypto.Generators.ECKeyPairGenerator();
            generator.Init(keyGenParams);
            Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair keyPair = generator.GenerateKeyPair();

            // Save the private and public key parameters
            _privateKeyParameters = (ECPrivateKeyParameters) keyPair.Private;
            _publicKeyParameters = (ECPublicKeyParameters) keyPair.Public;

            _kdf = ECDiffieHellmanKeyDerivationFunction.Hash;
            _hashAlgorithm = CngAlgorithm.Sha256;
        }
Ejemplo n.º 19
0
        internal BCryptAuthenticatedSymmetricAlgorithm(CngAlgorithm algorithm,
                                                       CngProvider implementation,
                                                       KeySizes[] legalBlockSizes,
                                                       KeySizes[] legalKeySizes)
        {
            Debug.Assert(algorithm != null, "algorithm != null");
            Debug.Assert(implementation != null, "implementation != null");
            Debug.Assert(legalBlockSizes != null, "legalBlockSizes != null");
            Debug.Assert(legalKeySizes != null, "legalKeySizes != null");

            m_algorithm      = algorithm;
            m_implementation = implementation;
            m_chainingMode   = CngChainingMode.Gcm;

            LegalBlockSizesValue = legalBlockSizes;
            LegalKeySizesValue   = legalKeySizes;

            // Create a temporary algorithm handle so that we can query it for some properties - such as the
            // block and tag sizes.
            using (SafeBCryptAlgorithmHandle algorithmHandle = SetupAlgorithm())
            {
                // Get block size in bits
                BlockSize = BCryptNative.GetInt32Property(algorithmHandle, BCryptNative.ObjectPropertyName.BlockLength) * 8;

                UpdateLegalTagSizes(algorithmHandle);
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Create a CNG keypair
        /// </summary>
        /// <param name="pkAlgo">Key algorithm (from supported set)</param>
        /// <param name="name">Key container name</param>
        /// <returns>
        /// CNG keypair
        /// </returns>
        /// <exception cref="System.NotSupportedException">Creation of key not supported for:  + pkAlgo.Algorithm</exception>
        /// <remarks>
        /// Keys are exportable
        /// </remarks>
        public static CngKey Create(CngAlgorithm pkAlgo, string name)
        {
            // Normalise the name
            string _name = name.Replace(' ', '_');

            CngKeyCreationParameters keyParams = new CngKeyCreationParameters();

            keyParams.ExportPolicy       = CngExportPolicies.AllowPlaintextExport;
            keyParams.KeyCreationOptions = CngKeyCreationOptions.OverwriteExistingKey;
            keyParams.Provider           = CngProvider.MicrosoftSoftwareKeyStorageProvider;

            // Note that CngAlgorithm is not an enum
            if (pkAlgo.Algorithm.Contains("ECDSA"))
            {
                keyParams.KeyUsage = CngKeyUsages.Signing;
            }
            else if (pkAlgo.Algorithm.Contains("ECDH"))
            {
                keyParams.KeyUsage = CngKeyUsages.KeyAgreement;
            }
            else
            {
                throw new NotSupportedException("Creation of key not supported for: " + pkAlgo.Algorithm);
            }

            return(CngKey.Create(pkAlgo, _name, keyParams));
        }
Ejemplo n.º 21
0
        public static ECDiffieHellmanCngPublicKey FromTLSPublicKey(CngAlgorithm alg, byte[] tlsKey)
        {
            if (alg == CngAlgorithm.ECDiffieHellmanP256)
            {
                if (tlsKey.Length != 65)
                {
                    throw new ArgumentOutOfRangeException(nameof(tlsKey), $"Expecting 65 bytes, received {tlsKey.Length} bytes.");
                }

                var buffer = new byte[72];
                buffer.AsSpan().Write(BCRYPT_ECDH_PUBLIC_P256_MAGIC).Write(tlsKey.AsSpan().Slice(1));

                return((ECDiffieHellmanCngPublicKey)ECDiffieHellmanCngPublicKey.FromByteArray(buffer, CngKeyBlobFormat.EccPublicBlob));
            }

            if (alg == CngAlgorithm.ECDiffieHellmanP384)
            {
                if (tlsKey.Length != 97)
                {
                    throw new ArgumentOutOfRangeException(nameof(tlsKey), $"Expecting 97 bytes, received {tlsKey.Length} bytes.");
                }

                var buffer = new byte[104];
                buffer.AsSpan().Write(BCRYPT_ECDH_PUBLIC_P384_MAGIC).Write(tlsKey.AsSpan().Slice(1));

                return((ECDiffieHellmanCngPublicKey)ECDiffieHellmanCngPublicKey.FromByteArray(buffer, CngKeyBlobFormat.EccPublicBlob));
            }

            throw new NotImplementedException();
        }
Ejemplo n.º 22
0
        internal BCryptHMAC(CngAlgorithm algorithm,
                            CngProvider algorithmProvider,
                            string hashName,
                            int blockSize,
                            byte[] key)
        {
            Debug.Assert(algorithm != null, "algorithm != null");
            Debug.Assert(algorithmProvider != null, "algorithmProvider != null");
            Debug.Assert(!String.IsNullOrEmpty(hashName), "!String.IsNullOrEmpty(hashName)");
            Debug.Assert(blockSize > 0, "blockSize > 0");
            Debug.Assert(key != null, "key != null");

            BlockSizeValue = blockSize;

            // We set the HashName up to be the CNG version of the hash, since the base type will instantiate
            // the algorithm, and the CNG versions have different FIPS characteristics than the standard implementations.
            HashName = String.Format(CultureInfo.InvariantCulture,
                                     "System.Security.Cryptography.{0}Cng, {1}",
                                     hashName,
                                     typeof(SHA256Cng).Assembly.FullName);

            m_implementation = algorithmProvider;

            m_algorithm = BCryptNative.OpenAlgorithm(algorithm.Algorithm,
                                                     algorithmProvider.Provider,
                                                     BCryptNative.AlgorithmProviderOptions.HmacAlgorithm);

            // Resetting the key will call Initialize for us, and get us setup with a hash handle,
            // so we don't need to create the hash handle ourselves
            Key = key;

            HashSizeValue = BCryptNative.GetInt32Property(m_hash, BCryptNative.HashPropertyName.HashLength) * 8;
        }
Ejemplo n.º 23
0
        /// <summary>constructor</summary>
        /// <param name="func">キー派生関数(Bob側と合わせる)。</param>
        /// <param name="hash">秘密協定の処理に使用するハッシュ アルゴリズム(Bob側と合わせる)</param>
        /// <param name="hmacKey">HMACキー</param>
        /// <param name="secretPrependOrLabel">SecretPrepend or Label</param>
        /// <param name="secretAppendOrSeed">SecretAppend or Seed</param>
        public EcdhCngBob(ECDiffieHellmanKeyDerivationFunction func, CngAlgorithm hash,
                          byte[] hmacKey, byte[] secretPrependOrLabel, byte[] secretAppendOrSeed)
        {
            ECDiffieHellmanCng ecdh = new ECDiffieHellmanCng();

            this._asa = ecdh; // 保持

            // Alice側と合わせる。
            ecdh.KeyDerivationFunction = func;
            if (func == ECDiffieHellmanKeyDerivationFunction.Hash)
            {
                ecdh.HashAlgorithm = hash;
                ecdh.SecretPrepend = secretPrependOrLabel;
                ecdh.SecretAppend  = secretAppendOrSeed;
            }
            else if (func == ECDiffieHellmanKeyDerivationFunction.Hmac)
            {
                ecdh.HashAlgorithm = hash;
                ecdh.HmacKey       = hmacKey;
                ecdh.SecretPrepend = secretPrependOrLabel;
                ecdh.SecretAppend  = secretAppendOrSeed;
            }
            else if (func == ECDiffieHellmanKeyDerivationFunction.Tls)
            {
                ecdh.Label = secretPrependOrLabel;
                ecdh.Seed  = secretAppendOrSeed;
            }

            // Aliceと鍵交換する交換鍵
            this._exchangeKey = ecdh.PublicKey.ToByteArray();
        }
Ejemplo n.º 24
0
        public bool VerifyHash(byte[] hash, byte[] signature, CngAlgorithm hashAlgorithm)
        {
            if (hash == null)
            {
                throw new ArgumentNullException("hash");
            }
            if (signature == null)
            {
                throw new ArgumentNullException("signature");
            }
            if (hashAlgorithm == null)
            {
                throw new ArgumentNullException("hashAlgorithm");
            }

            switch (SignaturePaddingMode)
            {
            case AsymmetricPaddingMode.Pkcs1:
                return(NCryptNative.VerifySignaturePkcs1(KeyHandle, hash, hashAlgorithm.Algorithm, signature));

            case AsymmetricPaddingMode.Pss:
                return(NCryptNative.VerifySignaturePss(KeyHandle, hash, hashAlgorithm.Algorithm, SignatureSaltBytes, signature));

            default:
                throw new InvalidOperationException(Properties.Resources.UnsupportedPaddingMode);
            }
        }
Ejemplo n.º 25
0
        private static HashAlgorithm HashAlgorithm(CngAlgorithm hash)
        {
#if NET40 || NET461
            if (hash == CngAlgorithm.Sha256)
            {
                return(new SHA256Cng());
            }
            if (hash == CngAlgorithm.Sha384)
            {
                return(new SHA384Cng());
            }
            if (hash == CngAlgorithm.Sha512)
            {
                return(new SHA512Cng());
            }

            throw new ArgumentException(string.Format("RsaPss expects hash function to be SHA256, SHA384 or SHA512, but was given:{0}", hash));
#elif NETSTANDARD1_4
            if (hash == CngAlgorithm.Sha256)
            {
                return(SHA256.Create());
            }
            if (hash == CngAlgorithm.Sha384)
            {
                return(SHA384.Create());
            }
            if (hash == CngAlgorithm.Sha512)
            {
                return(SHA512.Create());
            }
            throw new NotImplementedException("not yet");
#endif
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Initializes a new instance of <see cref="ECDHKey"/> class, using the specified curve algorithm.
        /// </summary>
        /// <param name="algorithm">The algorithm the key will be used with.</param>
        /// <param name="keyName">The name of the key, if the key should be persisted.</param>
        /// <exception cref="ArgumentNullException"><paramref name="algorithm"/> is <see langword="null"/>.</exception>
        /// <exception cref="ArgumentException"><paramref name="algorithm"/> is not a valid curve algorithm.</exception>
        /// <exception cref="InvalidOperationException">
        /// The key specified by <paramref name="keyName"/> is not using the specified <paramref name="algorithm"/>.
        /// </exception>
        public ECDHKey(CngAlgorithm algorithm, string keyName = null)
        {
            Contract.Requires <ArgumentNullException>(algorithm != null, nameof(algorithm));
            Contract.Requires <ArgumentException>(algorithm.Algorithm.StartsWith("ECDH_"), nameof(algorithm));

            key = LoadOrCreateKey(keyName, algorithm);
        }
        /// <summary>
        /// Constructs the core to use a stored CNG key.
        /// </summary>
        public CngSymmetricAlgorithmCore(ICngSymmetricAlgorithm outer, string keyName, CngProvider provider, CngKeyOpenOptions openOptions)
        {
            if (keyName == null)
            {
                throw new ArgumentNullException(nameof(keyName));
            }
            if (provider == null)
            {
                throw new ArgumentNullException(nameof(provider));
            }

            _outer = outer;

            _keyName       = keyName;
            _provider      = provider;
            _optionOptions = openOptions;

            using (CngKey cngKey = ProduceCngKey())
            {
                CngAlgorithm actualAlgorithm = cngKey.Algorithm;
                string       algorithm       = _outer.GetNCryptAlgorithmIdentifier();

                if (algorithm != actualAlgorithm.Algorithm)
                {
                    throw new CryptographicException(SR.Format(SR.Cryptography_CngKeyWrongAlgorithm, actualAlgorithm.Algorithm, algorithm));
                }

                _outer.BaseKeySize = cngKey.KeySize;
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        ///     Unpack a CAPI CRYPT_OID_INFO structure into an Oid2
        /// </summary>
        private Oid2(CapiNative.CRYPT_OID_INFO oidInfo)
        {
            m_oid   = oidInfo.pszOID ?? String.Empty;
            m_name  = oidInfo.pwszName ?? String.Empty;
            m_group = oidInfo.dwGroupId;

            // Algorithm information is only set for specific OID groups
            if (oidInfo.dwGroupId == OidGroup.EncryptionAlgorithm ||
                oidInfo.dwGroupId == OidGroup.HashAlgorithm ||
                oidInfo.dwGroupId == OidGroup.PublicKeyAlgorithm ||
                oidInfo.dwGroupId == OidGroup.SignatureAlgorithm)
            {
                // Values of 0 or -1 indicate that there is no CAPI algorithm mapping
                if (oidInfo.dwValue != 0 && oidInfo.dwValue != -1)
                {
                    m_algorithmId = oidInfo.dwValue;
                }

                if (!String.IsNullOrEmpty(oidInfo.pwszCNGAlgid))
                {
                    m_cngAlgorithm = new CngAlgorithm(oidInfo.pwszCNGAlgid);
                }

                if (!String.IsNullOrEmpty(oidInfo.pwszCNGExtraAlgid))
                {
                    m_cngExtraAlgorithm = new CngAlgorithm(oidInfo.pwszCNGExtraAlgid);
                }
            }
        }
Ejemplo n.º 29
0
 public static byte[] Sign(byte[] input, CngKey key, CngAlgorithm hash, int saltSize)
 {
     using (HashAlgorithm algo = HashAlgorithm(hash))
     {
         return SignHash(algo.ComputeHash(input), key, hash.Algorithm, saltSize);
     }
 }
Ejemplo n.º 30
0
        public static void VerifyMachineKey(
            CngAlgorithm algorithm,
            int plainBytesCount,
            Func <string, SymmetricAlgorithm> persistedFunc,
            Func <SymmetricAlgorithm> ephemeralFunc)
        {
            string keyName = Guid.NewGuid().ToString();
            CngKeyCreationParameters creationParameters = new CngKeyCreationParameters
            {
                Provider           = CngProvider.MicrosoftSoftwareKeyStorageProvider,
                ExportPolicy       = CngExportPolicies.AllowPlaintextExport,
                KeyCreationOptions = CngKeyCreationOptions.MachineKey,
            };

            CngKey cngKey = CngKey.Create(algorithm, keyName, creationParameters);

            try
            {
                VerifyPersistedKey(
                    keyName,
                    plainBytesCount,
                    persistedFunc,
                    ephemeralFunc,
                    CipherMode.CBC,
                    PaddingMode.PKCS7);
            }
            finally
            {
                // Delete also Disposes the key, no using should be added here.
                cngKey.Delete();
            }
        }
Ejemplo n.º 31
0
        public static void CreateEmphemeral_Default()
        {
            CngAlgorithm alg = CngAlgorithm.ECDiffieHellmanP256;

            using (CngKey key = CngKey.Create(alg, null, null))
            {
            }
        }
Ejemplo n.º 32
0
 public EcDsaPrivateKeyProvider(
     ID2LSecurityTokenFactory d2lSecurityTokenFactory,
     CngAlgorithm algorithm
     )
 {
     m_d2lSecurityTokenFactory = d2lSecurityTokenFactory;
     m_algorithm = algorithm;
 }
Ejemplo n.º 33
0
        /// <summary>
        /// Create a CNG Key and form as string, then export as a file.
        /// </summary>
        /// <param name="ca">The Algorithm.</param>
        /// <param name="cbf">The CNG Key Blob Format.</param>
        public void GenerateAndExportAsFile(string path, CngAlgorithm ca, CngKeyBlobFormat cbf)
        {
            StreamWriter sw = new StreamWriter(path);

            sw.Write(GenerateCngKeyAsString(ca, cbf));

            sw.Close();
        }
Ejemplo n.º 34
0
        public void ConstructorCustom()
        {
            CngAlgorithm algo = new CngAlgorithm("custom");

            Check(algo);
            Assert.IsFalse(algo.Equals((CngAlgorithm)null), "Equals((CngAlgorithm)null)");
            Assert.IsFalse(algo.Equals((object)null), "Equals((object)null)");
        }
Ejemplo n.º 35
0
 protected static CngKey GivenTheKey(string keyname, CngAlgorithm algorithm)
 {
     return CngKey.Create(algorithm, keyname, new CngKeyCreationParameters
     {
         Provider = CngProvider.MicrosoftSoftwareKeyStorageProvider,
         KeyCreationOptions = CngKeyCreationOptions.MachineKey,
         KeyUsage = CngKeyUsages.Signing
     });
 }
 public BCryptHashAlgorithm(CngAlgorithm algorithm, string implementation)
 {
     if (!BCryptNative.BCryptSupported)
     {
         throw new PlatformNotSupportedException(System.SR.GetString("Cryptography_PlatformNotSupported"));
     }
     this.m_algorithmHandle = BCryptNative.OpenAlgorithm(algorithm.Algorithm, implementation);
     this.Initialize();
 }
Ejemplo n.º 37
0
        public void ECDiffieHellmanP384()
        {
            CngAlgorithm algo = CngAlgorithm.ECDiffieHellmanP384;

            Assert.AreEqual("ECDH_P384", algo.Algorithm, "Algorithm");
            Assert.IsTrue(algo.Equals(CngAlgorithm.ECDiffieHellmanP384), "Equals(static)");
            Assert.IsTrue(Object.ReferenceEquals(algo, CngAlgorithm.ECDiffieHellmanP384), "ReferenceEquals");
            Check(algo);
        }
Ejemplo n.º 38
0
        public void ECDsaP521()
        {
            CngAlgorithm algo = CngAlgorithm.ECDsaP521;

            Assert.AreEqual("ECDSA_P521", algo.Algorithm, "Algorithm");
            Assert.IsTrue(algo.Equals(CngAlgorithm.ECDsaP521), "Equals(static)");
            Assert.IsTrue(Object.ReferenceEquals(algo, CngAlgorithm.ECDsaP521), "ReferenceEquals");
            Check(algo);
        }
Ejemplo n.º 39
0
        public void MD5()
        {
            CngAlgorithm algo = CngAlgorithm.MD5;

            Assert.AreEqual("MD5", algo.Algorithm, "Algorithm");
            Assert.IsTrue(algo.Equals(CngAlgorithm.MD5), "Equals(static)");
            Assert.IsTrue(Object.ReferenceEquals(algo, CngAlgorithm.MD5), "ReferenceEquals");
            Check(algo);
        }
Ejemplo n.º 40
0
        public void Sha512()
        {
            CngAlgorithm algo = CngAlgorithm.Sha512;

            Assert.AreEqual("SHA512", algo.Algorithm, "Algorithm");
            Assert.IsTrue(algo.Equals(CngAlgorithm.Sha512), "Equals(static)");
            Assert.IsTrue(Object.ReferenceEquals(algo, CngAlgorithm.Sha512), "ReferenceEquals");
            Check(algo);
        }
 public ECDiffieHellmanCng(int keySize)
 {
     this.m_hashAlgorithm = CngAlgorithm.Sha256;
     if (!NCryptNative.NCryptSupported)
     {
         throw new PlatformNotSupportedException(System.SR.GetString("Cryptography_PlatformNotSupported"));
     }
     base.LegalKeySizesValue = s_legalKeySizes;
     this.KeySize = keySize;
 }
Ejemplo n.º 42
0
        /// <summary>
        ///     Get all of the keys for a specific algorithm supported by the provider
        /// </summary>
        public static IEnumerable<CngKey> GetKeys(this CngProvider provider,
                                                  CngKeyOpenOptions openOptions,
                                                  CngAlgorithm algorithm)
        {
            if (algorithm == null)
                throw new ArgumentNullException("algorithm");

            return from key in provider.GetKeys(openOptions)
                   where key.Algorithm == algorithm
                   select key;
        }
Ejemplo n.º 43
0
        private static HashAlgorithm HashAlgorithm(CngAlgorithm hash)
        {
            if (hash == CngAlgorithm.Sha256)
                return new SHA256Cng();
            if (hash == CngAlgorithm.Sha384)
                return new SHA384Cng();
            if (hash == CngAlgorithm.Sha512)
                return new SHA512Cng();

            throw new ArgumentException(string.Format("RsaPss expects hash function to be SHA256, SHA384 or SHA512, but was given:{0}",hash));
        }
Ejemplo n.º 44
0
        private static byte[] GetCurveIdentifier(CngAlgorithm algorithm)
        {
            if (algorithm == CngAlgorithm.ECDsaP256)
                return new byte[] {0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07};
            if (algorithm == CngAlgorithm.ECDsaP384)
                return new byte[] {0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22};
            if (algorithm == CngAlgorithm.ECDsaP521)
                return new byte[] {0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23};

            throw new UnsupportedCurveException("Unknown algorithm " + algorithm.Algorithm);
        }
 public static byte[] DeriveKeyMaterial(byte[] privateKey, byte[] otherPublicKey, CngAlgorithm hashAlgorithm)
 {
     #if Mono
     throw new NotSupportedException();
     #else
     using (CngKey ck = CngKey.Import(privateKey, CngKeyBlobFormat.Pkcs8PrivateBlob))
     using (ECDiffieHellmanCng ecdh = new ECDiffieHellmanCng(ck))
     {
         ecdh.HashAlgorithm = hashAlgorithm;
         return ecdh.DeriveKeyMaterial(ECDiffieHellmanCngPublicKey.FromXmlString(Encoding.ASCII.GetString(otherPublicKey)));
     }
     #endif
 }
Ejemplo n.º 46
0
        private static HashAlgorithm HashAlgorithm(CngAlgorithm hash)
        {
            #if NET40
            if (hash == CngAlgorithm.Sha256)
                return new SHA256Cng();
            if (hash == CngAlgorithm.Sha384)
                return new SHA384Cng();
            if (hash == CngAlgorithm.Sha512)
                return new SHA512Cng();

            throw new ArgumentException(string.Format("RsaPss expects hash function to be SHA256, SHA384 or SHA512, but was given:{0}",hash));

            #elif NETSTANDARD1_4
            throw new NotImplementedException("not yet");
            #endif
        }
 private static string GetCurveUrn(CngAlgorithm algorithm)
 {
     if ((algorithm == CngAlgorithm.ECDsaP256) || (algorithm == CngAlgorithm.ECDiffieHellmanP256))
     {
         return "urn:oid:1.2.840.10045.3.1.7";
     }
     if ((algorithm == CngAlgorithm.ECDsaP384) || (algorithm == CngAlgorithm.ECDiffieHellmanP384))
     {
         return "urn:oid:1.3.132.0.34";
     }
     if (!(algorithm == CngAlgorithm.ECDsaP521) && !(algorithm == CngAlgorithm.ECDiffieHellmanP521))
     {
         throw new ArgumentException(System.SR.GetString("Cryptography_UnknownEllipticCurve"), "algorithm");
     }
     return "urn:oid:1.3.132.0.35";
 }
Ejemplo n.º 48
0
        internal BCryptSymmetricAlgorithm(CngAlgorithm algorithm,
                                          CngProvider algorithmProvider,
                                          KeySizes[] legalBlockSizes,
                                          KeySizes[] legalkeySizes)
        {
            Debug.Assert(algorithm != null, "algorithm != null");
            Debug.Assert(algorithmProvider != null, "algorithmProvider != null");
            Debug.Assert(legalBlockSizes != null, "legalBlockSizes != null");
            Debug.Assert(legalkeySizes != null, "legalKeySizes != null");

            m_algorithm = algorithm;
            m_algorithmProvider = algorithmProvider;

            LegalBlockSizesValue = legalBlockSizes;
            LegalKeySizesValue = legalkeySizes;
        }
Ejemplo n.º 49
0
        /// <summary>
        ///     Create an Oid2 object for an OID which has no CAPI algorithm representation
        /// </summary>
        public Oid2(string oid,
                    string friendlyName,
                    OidGroup group,
                    CngAlgorithm cngAlgorithm,
                    CngAlgorithm extraCngAlgorithm)
        {
            if (oid == null)
                throw new ArgumentNullException("oid");
            if (friendlyName == null)
                throw new ArgumentNullException("friendlyName");

            m_oid = oid;
            m_name = friendlyName;
            m_group = group;
            m_cngAlgorithm = cngAlgorithm;
            m_cngExtraAlgorithm = extraCngAlgorithm;
        }
Ejemplo n.º 50
0
        public static byte[] Encrypt(byte[] plainText, CngKey key, CngAlgorithm hash)
        {
            var paddingInfo = new BCrypt.BCRYPT_OAEP_PADDING_INFO(hash.Algorithm);

            uint cipherTextByteSize;
            uint status = NCrypt.NCryptEncrypt(key.Handle, plainText, plainText.Length, ref paddingInfo, null, 0, out cipherTextByteSize, BCrypt.BCRYPT_PAD_OAEP);

            if (status != BCrypt.ERROR_SUCCESS)
                throw new CryptographicException(string.Format("NCrypt.Encrypt() (ciphertext buffer size) failed with status code:{0}", status));

            var cipherText = new byte[cipherTextByteSize];

            status = NCrypt.NCryptEncrypt(key.Handle, plainText, plainText.Length, ref paddingInfo, cipherText, cipherTextByteSize, out cipherTextByteSize, BCrypt.BCRYPT_PAD_OAEP);

            if (status != BCrypt.ERROR_SUCCESS)
                throw new CryptographicException(string.Format("NCrypt.Encrypt() failed with status code:{0}", status));

            return cipherText;
        }
Ejemplo n.º 51
0
		private void Check (CngAlgorithm algo)
		{
			Assert.AreEqual (algo.Algorithm, algo.ToString (), "Algorithm/ToString");
			Assert.AreEqual (algo.GetHashCode (), algo.Algorithm.GetHashCode (), "GetHashCode");
			Assert.IsTrue (algo.Equals (algo), "Equals(self)");
			Assert.IsTrue (algo.Equals ((object)algo), "Equals((object)self)");

			CngAlgorithm copy = new CngAlgorithm (algo.Algorithm);
			Assert.AreEqual (algo.GetHashCode (), copy.GetHashCode (), "Copy");
			Assert.IsTrue (algo.Equals (copy), "Equals(copy)");
			Assert.IsTrue (algo.Equals ((object)copy), "Equals((object)copy)");
			Assert.IsTrue (algo == copy, "algo==copy");
			Assert.IsFalse (algo != copy, "algo!=copy");

			Assert.IsFalse (algo.Equals (mono), "Equals(mono)");
			Assert.IsFalse (algo.Equals ((object)mono), "Equals((object)mono)");
			Assert.IsFalse (algo == mono, "algo==mono");
			Assert.IsTrue (algo != mono, "algo!=mono");
		}
        public BCryptHashAlgorithm(CngAlgorithm algorithm, string implementation) {
            Contract.Requires(algorithm != null);
            Contract.Requires(!String.IsNullOrEmpty(implementation));
            Contract.Ensures(m_algorithmHandle != null && !m_algorithmHandle.IsInvalid && !m_algorithmHandle.IsClosed);
            Contract.Ensures(m_hashHandle != null && !m_hashHandle.IsInvalid && !m_hashHandle.IsClosed);

            // Make sure CNG is supported on this platform
            if (!BCryptNative.BCryptSupported) {
                throw new PlatformNotSupportedException(SR.GetString(SR.Cryptography_PlatformNotSupported));
            }

            if (_algorithmCache == null)
            {
                _algorithmCache = new BCryptAlgorithmHandleCache();
            }

            m_algorithmHandle = _algorithmCache.GetCachedAlgorithmHandle(algorithm.Algorithm, implementation);

            Initialize();
        }
 public ECDiffieHellmanCng(CngKey key)
 {
     this.m_hashAlgorithm = CngAlgorithm.Sha256;
     if (key == null)
     {
         throw new ArgumentNullException("key");
     }
     if (key.AlgorithmGroup != CngAlgorithmGroup.ECDiffieHellman)
     {
         throw new ArgumentException(System.SR.GetString("Cryptography_ArgECDHRequiresECDHKey"), "key");
     }
     if (!NCryptNative.NCryptSupported)
     {
         throw new PlatformNotSupportedException(System.SR.GetString("Cryptography_PlatformNotSupported"));
     }
     base.LegalKeySizesValue = s_legalKeySizes;
     new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert();
     this.Key = CngKey.Open(key.Handle, key.IsEphemeral ? CngKeyHandleOpenOptions.EphemeralKey : CngKeyHandleOpenOptions.None);
     CodeAccessPermission.RevertAssert();
     this.KeySize = this.m_key.KeySize;
 }
Ejemplo n.º 54
0
        //[Fact] - Keeping this test for reference but we don't want to run it as an inner-loop test because 
        //         it creates a key on disk.
        public static void StoredKeyTripleDES()
        {
            CngAlgorithm algname = new CngAlgorithm("3DES");
            string keyName = "CoreFxTest-" + Guid.NewGuid();
            CngKey _cngKey = CngKey.Create(algname, keyName);
            try
            {
                using (TripleDES alg = new TripleDESCng(keyName))
                {
                    int keySize = alg.KeySize;
                    Assert.Equal(192, keySize);

                    // Since this is a stored key, it's not going to surrender the actual key bytes. 
                    Assert.ThrowsAny<CryptographicException>(() => alg.Key);
                }
            }
            finally
            {
                _cngKey.Delete();
            }
        }
Ejemplo n.º 55
0
        // The ephemeral key has already been validated by the AesCipherTests suite.
        // Therefore we can use the ephemeral key to validate the persisted key.
        internal static void VerifyPersistedKey(
            CngAlgorithm algorithm,
            int keySize,
            int plainBytesCount,
            Func<string, SymmetricAlgorithm> persistedFunc,
            Func<SymmetricAlgorithm> ephemeralFunc,
            CipherMode cipherMode,
            PaddingMode paddingMode)
        {
            string keyName = Guid.NewGuid().ToString();
            CngKeyCreationParameters creationParameters = new CngKeyCreationParameters
            {
                Provider = CngProvider.MicrosoftSoftwareKeyStorageProvider,
                ExportPolicy = CngExportPolicies.AllowPlaintextExport,
                Parameters =
                {
                    new CngProperty("Length", BitConverter.GetBytes(keySize), CngPropertyOptions.None),
                }
            };

            CngKey cngKey = CngKey.Create(algorithm, keyName, creationParameters);

            try
            {
                VerifyPersistedKey(
                    keyName,
                    plainBytesCount,
                    persistedFunc,
                    ephemeralFunc,
                    cipherMode,
                    paddingMode);
            }
            finally
            {
                // Delete also Disposes the key, no using should be added here.
                cngKey.Delete();
            }
        }
Ejemplo n.º 56
0
		public void ConstructorCustom ()
		{
			CngAlgorithm algo = new CngAlgorithm ("custom");
			Check (algo);
			Assert.IsFalse (algo.Equals ((CngAlgorithm) null), "Equals((CngAlgorithm)null)");
			Assert.IsFalse (algo.Equals ((object) null), "Equals((object)null)");
		}
 /// <summary>
 /// Verify data which was signed and hashed with the given hash algorithm. This
 /// overload does not use the SignatureHashAlgorithm property.
 /// </summary>
 /// <param name="hash">hash to verify</param>
 /// <param name="signature">signature of the data</param>
 /// <param name="hashAlgorithm">algorithm that hash was hashed with</param>
 /// <returns>true if the signature verifies for the hash, false if it does not</returns>
 /// <exception cref="System.ArgumentNullException">if hash, signature, or hashAlgorithm are null</exception>
 public bool VerifyHash(byte[] hash, byte[] signature, CngAlgorithm hashAlgorithm)
 {
     return _key.VerifyHash(hash, signature, hashAlgorithm);
 }
 /// <summary>
 /// Sign already hashed data, specifying the algorithm it was hashed with. This
 /// method does not use the SignatureHashAlgorithm property.
 /// </summary>
 /// <param name="hash">hash to sign</param>
 /// <param name="hashAlgorithm">algorithm hash was signed with</param>
 /// <exception cref="System.ArgumentNullException">if hash or hashAlgorithm are null</exception>
 /// <exception cref="System.Security.Cryptography.CryptographicException">if data could not be signed</exception>
 public byte[] SignHash(byte[] hash, CngAlgorithm hashAlgorithm)
 {
     return _key.SignHash(hash, hashAlgorithm);
 }
Ejemplo n.º 59
0
        public static void VerifyMachineKey(
            CngAlgorithm algorithm,
            int plainBytesCount,
            Func<string, SymmetricAlgorithm> persistedFunc,
            Func<SymmetricAlgorithm> ephemeralFunc)
        {
            string keyName = Guid.NewGuid().ToString();
            CngKeyCreationParameters creationParameters = new CngKeyCreationParameters
            {
                Provider = CngProvider.MicrosoftSoftwareKeyStorageProvider,
                ExportPolicy = CngExportPolicies.AllowPlaintextExport,
                KeyCreationOptions = CngKeyCreationOptions.MachineKey,
            };

            CngKey cngKey = CngKey.Create(algorithm, keyName, creationParameters);

            try
            {
                VerifyPersistedKey(
                    keyName,
                    plainBytesCount,
                    persistedFunc,
                    ephemeralFunc,
                    CipherMode.CBC,
                    PaddingMode.PKCS7);
            }
            finally
            {
                // Delete also Disposes the key, no using should be added here.
                cngKey.Delete();
            }
        }
Ejemplo n.º 60
-2
        //[Fact] - Keeping this test for reference but we don't want to run it as an inner-loop test because 
        //         it creates a key on disk.
        public static void AesRoundTrip256BitsNoneECBUsingStoredKey()
        {
            CngAlgorithm algname = new CngAlgorithm("AES");
            string keyName = "CoreFxTest-" + Guid.NewGuid();
            CngKey _cngKey = CngKey.Create(algname, keyName);
            try
            {
                using (Aes alg = new AesCng(keyName))
                {
                    try
                    {
                        alg.Padding = PaddingMode.None;
                        alg.Mode = CipherMode.ECB;

                        int keySize = alg.KeySize;

                        byte[] plainText = "15a818701f0f7c99fe4b1b4b860f131b".HexToByteArray();
                        byte[] cipher = alg.Encrypt(plainText);
                        byte[] decrypted = alg.Decrypt(cipher);
                        byte[] expectedDecrypted = "15a818701f0f7c99fe4b1b4b860f131b".HexToByteArray();
                        Assert.Equal<byte>(expectedDecrypted, decrypted);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
                }
            }
            finally
            {
                _cngKey.Delete();
            }
        }