Esempio n. 1
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.None, "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.None, 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);
            }
        }
Esempio n. 2
0
        public void TestEcdhKeys()
        {
            // To make sure keys are exportable:
            //    http://stackoverflow.com/questions/20505325/how-to-export-private-key-for-ecdiffiehellmancng/20505976#20505976

            var ecdhKeyParams = new CngKeyCreationParameters
            {
                KeyUsage     = CngKeyUsages.AllUsages,
                ExportPolicy = CngExportPolicies.AllowPlaintextExport
            };
            var ecdhKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP256, null, ecdhKeyParams);
            var ecdh    = new ECDiffieHellmanCng(ecdhKey);

            ecdh.KeySize = 256;


            //Export the keys
            var privateKey = ecdh.Key.Export(CngKeyBlobFormat.EccPrivateBlob);

            // This returns:
            //   [ { MinSize = 256; MaxSize = 384; SkipSize = 128 }
            //     { MinSize = 521; MaxSize = 521; SkipSize = 0   } ]
            var keySizes = ecdh.LegalKeySizes;
            // Example of this:
            //      <ECDHKeyValue xmlns="http://www.w3.org/2001/04/xmldsig-more#">
            //        <DomainParameters>
            //          <NamedCurve URN="urn:oid:1.3.132.0.35" />
            //        </DomainParameters>
            //        <PublicKey>
            //          <X Value="6338036285454860977775086861655185721418051140960904673987863656163882965225521398319125216217757952736756437624751684728661860413862054254572205453827782795" xsi:type="PrimeFieldElemType" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
            //          <Y Value="2429739115523607678822648112222739155064474393176967830414279652115290771735466025346855521196073509912224542851147234378090051353981358078708633637907317343" xsi:type="PrimeFieldElemType" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
            //        </PublicKey>
            //      </ECDHKeyValue>
            var pubKeyXml = ecdh.PublicKey.ToXmlString();
        }
Esempio n. 3
0
        private ECDsaCng CreateECDKey(out byte[] PrivateKey, out byte[] PublicKey, string KeyName, string keyAlias)
        {
            //генерируем точку (ключ) P
            var p = new CngKeyCreationParameters
            {
                //задаем политику экспорта (может экспортироваться несколько раз)
                ExportPolicy = CngExportPolicies.AllowPlaintextExport,
                //параметры (может перезаписываться)
                KeyCreationOptions = CngKeyCreationOptions.OverwriteExistingKey,
                //пользовательский интерфейс (уровень защиты секретный ключ, имя ключа)
                UIPolicy = new CngUIPolicy(CngUIProtectionLevels.ProtectKey, KeyName, null, null, null)
            };
            //создаем ключ (Алгоритм, в котором будет использоваться ключ; имя ключа и p)
            var key = CngKey.Create(CngAlgorithm.ECDsaP521, keyAlias, p);

            using (ECDsaCng dsa = new ECDsaCng(key))
            {
                //используем алгоритм хэша Sha512
                dsa.HashAlgorithm = CngAlgorithm.Sha512;
                //получаем открытые и закрытые ключи
                PublicKey  = dsa.Key.Export(CngKeyBlobFormat.EccPublicBlob);
                PrivateKey = dsa.Key.Export(CngKeyBlobFormat.EccPrivateBlob);
                return(dsa);
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Import the certificate with private key to the machine MY store while force using Software KSP.
        ///
        /// See https://stackoverflow.com/questions/51522330/c-sharp-import-certificate-and-key-pfx-into-cng-ksp
        /// </summary>
        private static void ImportPFX2MachineStore(bool useDebugOutput, string pfxPassword, byte[] issuedPkcs12)
        {
            using X509Certificate2 issuedCertificateAndPrivate = new X509Certificate2(issuedPkcs12, pfxPassword, X509KeyStorageFlags.Exportable);
            RSACng keyFromPFx = new RSACng();

            keyFromPFx.FromXmlString(issuedCertificateAndPrivate.GetRSAPrivateKey().ToXmlString(true));
            var keyData   = keyFromPFx.Key.Export(CngKeyBlobFormat.GenericPrivateBlob);
            var keyParams = new CngKeyCreationParameters
            {
                ExportPolicy       = useDebugOutput ? CngExportPolicies.AllowPlaintextExport : CngExportPolicies.None,
                KeyCreationOptions = CngKeyCreationOptions.MachineKey,
                Provider           = CngProvider.MicrosoftSoftwareKeyStorageProvider
            };

            keyParams.Parameters.Add(new CngProperty(CngKeyBlobFormat.GenericPrivateBlob.Format, keyData, CngPropertyOptions.None));
            CngKey key = CngKey.Create(CngAlgorithm.Rsa, $"KDC-Key-{issuedCertificateAndPrivate.Thumbprint}", keyParams);

            RSACng rsaCNG = new RSACng(key);

            X509Certificate2 certWithCNGKey = new X509Certificate2(issuedCertificateAndPrivate.Export(X509ContentType.Cert));

            certWithCNGKey            = certWithCNGKey.CopyWithPrivateKey(rsaCNG);
            using X509Store storeLmMy = new X509Store(StoreName.My, StoreLocation.LocalMachine, OpenFlags.ReadWrite | OpenFlags.OpenExistingOnly);
            storeLmMy.Add(certWithCNGKey);
            storeLmMy.Close();
        }
Esempio n. 5
0
        Task <D2LSecurityToken> IPrivateKeyProvider.GetSigningCredentialsAsync()
        {
            var creationParams = new CngKeyCreationParameters()
            {
                ExportPolicy = CngExportPolicies.AllowPlaintextExport,
                KeyUsage     = CngKeyUsages.Signing
            };

            byte[] privateBlob;
            using (var cngKey = CngKey.Create(m_algorithm, null, creationParams)) {
                using (ECDsaCng ecDsa = new ECDsaCng(cngKey)) {
                    privateBlob = ecDsa.Key.Export(CngKeyBlobFormat.EccPrivateBlob);
                }
            }

            D2LSecurityToken result = m_d2lSecurityTokenFactory.Create(() => {
                using (var cng = CngKey.Import(privateBlob, CngKeyBlobFormat.EccPrivateBlob)) {
                    // ECDsaCng copies the CngKey, hence the using
                    var ecDsa = new ECDsaCng(cng);
                    var key   = new EcDsaSecurityKey(ecDsa);
                    return(new Tuple <AsymmetricSecurityKey, IDisposable>(key, ecDsa));
                }
            });

            return(Task.FromResult(result));
        }
        public void When_Private_Key_Cannot_Be_Extracted_Then_Exception_Is_Thrown()
        {
            // ARRANGE
            InitializeFakeObjects();
            var keyCreationParameter = new CngKeyCreationParameters
            {
                ExportPolicy = CngExportPolicies.None
            };

            var cnk = CngKey.Create(CngAlgorithm.ECDsaP256, null, keyCreationParameter);
            var isExceptionRaised = false;

            try
            {
                // ACT
                _cngKeySerializer.SerializeCngKeyWithPrivateKey(cnk);
            }
            catch (CryptographicException ex)
            {
                isExceptionRaised = true;
            }

            // ASSERT
            Assert.True(isExceptionRaised);
        }
        public static X509Certificate2 CreateCertificate(string password, string issuer = "CN=Microsoft Azure Powershell Test", string friendlyName = "PSTest")
        {
            var keyCreationParameters = new CngKeyCreationParameters
            {
                ExportPolicy       = CngExportPolicies.AllowExport,
                KeyCreationOptions = CngKeyCreationOptions.None,
                KeyUsage           = CngKeyUsages.AllUsages,
                Provider           = CngProvider.MicrosoftSoftwareKeyStorageProvider
            };

            keyCreationParameters.Parameters.Add(new CngProperty("Length", BitConverter.GetBytes(2048), CngPropertyOptions.None));

            CngKey key = CngKey.Create(CngAlgorithm2.Rsa, null, keyCreationParameters);

            var creationParams = new X509CertificateCreationParameters(new X500DistinguishedName(issuer))
            {
                TakeOwnershipOfKey = true
            };

            X509Certificate2 cert = key.CreateSelfSignedCertificate(creationParams);

            key = null;
            cert.FriendlyName = friendlyName;

            byte[]           bytes      = cert.Export(X509ContentType.Pfx, password);
            X509Certificate2 returnCert = new X509Certificate2();

            returnCert.Import(bytes, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
            return(returnCert);
        }
Esempio n. 8
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();
            }
        }
Esempio n. 9
0
    static void Main()
    {
        try
        {
            CngKey key;
            CngKeyCreationParameters keyparm = new CngKeyCreationParameters();

            // See: https://msdn.microsoft.com/en-us/library/system.security.cryptography.cngexportpolicies(v=vs.110).aspx
            keyparm.ExportPolicy = CngExportPolicies.AllowPlaintextExport;

            keyparm.KeyCreationOptions = CngKeyCreationOptions.OverwriteExistingKey;  //.MachineKey	.None
            keyparm.Provider           = CngProvider.MicrosoftSoftwareKeyStorageProvider;

            // For different algorithms available see: https://msdn.microsoft.com/en-us/library/system.security.cryptography.cngalgorithm(v=vs.110).aspx
            key = CngKey.Create(CngAlgorithm.ECDsaP256, "key1", keyparm);

            // Export public key
            byte[] publkey          = key.Export(CngKeyBlobFormat.GenericPublicBlob);
            String publkeybase64    = Convert.ToBase64String(publkey);
            var    currentDirectory = System.AppDomain.CurrentDomain.BaseDirectory;
            System.IO.File.WriteAllText(currentDirectory + "pkey", publkeybase64);
        }
        catch (ArgumentNullException)
        {
            Console.WriteLine("Error");
        }
    }
Esempio n. 10
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));
        }
Esempio n. 11
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);
        }
Esempio n. 12
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);
            }
        }
Esempio n. 13
0
        public void Create2048RsaCertificate()
        {
            CngKeyCreationParameters keyCreationParameters = new CngKeyCreationParameters();

            keyCreationParameters.ExportPolicy       = CngExportPolicies.AllowExport;
            keyCreationParameters.KeyCreationOptions = CngKeyCreationOptions.None;
            keyCreationParameters.KeyUsage           = CngKeyUsages.AllUsages;
            keyCreationParameters.Provider           = CngProvider.MicrosoftSoftwareKeyStorageProvider;

            int keySize = 2048;

            keyCreationParameters.Parameters.Add(new CngProperty("Length",
                                                                 BitConverter.GetBytes(keySize),
                                                                 CngPropertyOptions.None));
            byte[] pfx = null;
            using (CngKey key = CngKey.Create(CngAlgorithm2.Rsa, null, keyCreationParameters))
            {
                X509Certificate2 cert = key.CreateSelfSignedCertificate(new X500DistinguishedName("CN=TestRSAKey"));
                pfx = cert.Export(X509ContentType.Pfx, "TestPassword");

                Assert.IsTrue(cert.HasPrivateKey);
                Assert.IsTrue(cert.HasCngKey());
            }

            X509Certificate2 rtCert = new X509Certificate2(pfx, "TestPassword");

            Assert.IsTrue(rtCert.HasPrivateKey);
            Assert.IsTrue(rtCert.HasCngKey());

            using (CngKey rtKey = rtCert.GetCngPrivateKey())
            {
                Assert.AreEqual(CngAlgorithm2.Rsa, rtKey.Algorithm);
                Assert.AreEqual(2048, rtKey.KeySize);
            }
        }
Esempio n. 14
0
        public void CreateECDsaCertificate()
        {
            byte[] pfx = null;

            CngKeyCreationParameters keyCreationParameters = new CngKeyCreationParameters();

            keyCreationParameters.ExportPolicy = CngExportPolicies.AllowExport;
            keyCreationParameters.KeyUsage     = CngKeyUsages.Signing;

            using (CngKey key = CngKey.Create(CngAlgorithm.ECDsaP256, null, keyCreationParameters))
            {
                X509CertificateCreationParameters creationParams = new X509CertificateCreationParameters(new X500DistinguishedName("CN=TestECDSACert"));
                creationParams.SignatureAlgorithm = X509CertificateSignatureAlgorithm.ECDsaSha256;

                X509Certificate2 cert = key.CreateSelfSignedCertificate(creationParams);
                pfx = cert.Export(X509ContentType.Pfx, "TestPassword");

                Assert.IsTrue(cert.HasPrivateKey);
                Assert.IsTrue(cert.HasCngKey());
            }

            X509Certificate2 rtCert = new X509Certificate2(pfx, "TestPassword");

            Assert.IsTrue(rtCert.HasPrivateKey);
            Assert.IsTrue(rtCert.HasCngKey());

            using (CngKey rtKey = rtCert.GetCngPrivateKey())
            {
                Assert.AreEqual(CngAlgorithmGroup.ECDsa, rtKey.AlgorithmGroup);
                Assert.AreEqual(256, rtKey.KeySize);
            }
        }
        public UserAccount()
        {
            CngKeyCreationParameters keyCreationParameters = new CngKeyCreationParameters();

            keyCreationParameters.ExportPolicy = CngExportPolicies.AllowPlaintextExport;
            keyCreationParameters.KeyUsage     = CngKeyUsages.Signing;

            CngKey key = CngKey.Create(CngAlgorithm.ECDsaP256, null, keyCreationParameters);



            ECDsaCng dsa = new ECDsaCng(key); //dsa = Digital Signature Algorithm

            byte[] privateKey = dsa.Key.Export(CngKeyBlobFormat.EccPrivateBlob);

            ECDSAPrivateKey = BitConverter.ToString(privateKey).Replace("-", String.Empty);



            //create public key
            byte[] publicKey = dsa.Key.Export(CngKeyBlobFormat.EccPublicBlob);

            ECSDAPublicKey = BitConverter.ToString(publicKey).Replace("-", String.Empty);



            //we calculate the hashvalue by slicing the end off of the public key
            string hashValue = ECDSAOperations.GetHashValue(publicKey);

            int hashLength = hashValue.Length;

            UserAddress = "0x" + hashValue.Substring(hashLength - ADDRESS_LENGTH);
        }
Esempio n. 16
0
        public static void AssociatePersistedKey_CNG_DSA()
        {
            const string KeyName = nameof(AssociatePersistedKey_CNG_DSA);

            CngKey            cngKey        = null;
            HashAlgorithmName hashAlgorithm = HashAlgorithmName.SHA256;

            byte[] signature;

            try
            {
                CngKeyCreationParameters creationParameters = new CngKeyCreationParameters()
                {
                    ExportPolicy       = CngExportPolicies.None,
                    Provider           = CngProvider.MicrosoftSoftwareKeyStorageProvider,
                    KeyCreationOptions = CngKeyCreationOptions.OverwriteExistingKey,
                    Parameters         =
                    {
                        new CngProperty("Length", BitConverter.GetBytes(1024), CngPropertyOptions.None),
                    }
                };

                cngKey = CngKey.Create(new CngAlgorithm("DSA"), KeyName, creationParameters);

                using (DSACng dsaCng = new DSACng(cngKey))
                {
                    X509SignatureGenerator dsaGen = new DSAX509SignatureGenerator(dsaCng);

                    CertificateRequest request = new CertificateRequest(
                        new X500DistinguishedName($"CN={KeyName}"),
                        dsaGen.PublicKey,
                        HashAlgorithmName.SHA256);

                    DateTimeOffset now = DateTimeOffset.UtcNow;

                    using (X509Certificate2 cert = request.Create(request.SubjectName, dsaGen, now, now.AddDays(1), new byte[1]))
                        using (X509Certificate2 certWithPrivateKey = cert.CopyWithPrivateKey(dsaCng))
                            using (DSA dsa = certWithPrivateKey.GetDSAPrivateKey())
                            {
                                signature = dsa.SignData(Array.Empty <byte>(), hashAlgorithm);

                                Assert.True(dsaCng.VerifyData(Array.Empty <byte>(), signature, hashAlgorithm));
                            }
                }

                // Some certs have disposed, did they delete the key?
                using (CngKey stillPersistedKey = CngKey.Open(KeyName, CngProvider.MicrosoftSoftwareKeyStorageProvider))
                    using (DSACng dsaCng = new DSACng(stillPersistedKey))
                    {
                        dsaCng.SignData(Array.Empty <byte>(), hashAlgorithm);
                    }
            }
            finally
            {
                cngKey?.Delete();
            }
        }
Esempio n. 17
0
        CngKeyCreationParameters GetKeyParameters()
        {
            var parameters = new CngKeyCreationParameters();

            parameters.ExportPolicy = CngExportPolicies.AllowPlaintextExport;
            // Tell IIS to use Machine Key store or creation of ECDH service provider will fail.
            parameters.KeyCreationOptions |= CngKeyCreationOptions.MachineKey;
            return(parameters);
        }
Esempio n. 18
0
        public static CngKey Create()
        {
            var keyCreationParameters = new CngKeyCreationParameters
            {
                ExportPolicy = CngExportPolicies.AllowPlaintextExport, KeyUsage = CngKeyUsages.Signing
            };

            return(CngKey.Create(CngAlgorithm.ECDsaP256, null, keyCreationParameters));
        }
Esempio n. 19
0
        public static string GenerateAESKey()
        {
            string keyName = RandomKeyName();
            CngKeyCreationParameters keyCreationParams = new CngKeyCreationParameters();

            keyCreationParams.Provider = CngProvider.MicrosoftSoftwareKeyStorageProvider;
            CngKey key = CngKey.Create(new CngAlgorithm("AES"), keyName, keyCreationParams);

            return(keyName);
        }
Esempio n. 20
0
        public X509Certificate2 CreateNamedKeyCertificate(CertData data)
        {
            try
            {
                CngKeyCreationParameters keyCreationParameters
                    = new CngKeyCreationParameters
                    {
                    ExportPolicy =
                        CngExportPolicies.AllowExport |
                        CngExportPolicies.AllowPlaintextExport |
                        CngExportPolicies.AllowPlaintextArchiving |
                        CngExportPolicies.AllowArchiving,
                    KeyUsage = CngKeyUsages.AllUsages
                    };

                X509Certificate2 cert;
                X509CertificateCreationParameters configCreate
                    = new X509CertificateCreationParameters(new X500DistinguishedName(data.DistinguishedName))
                    {
                    EndTime =
                        DateTime.Parse("01/01/2020",
                                       System.Globalization.
                                       DateTimeFormatInfo.
                                       InvariantInfo),
                    StartTime =
                        DateTime.Parse("01/01/2010",
                                       System.Globalization.
                                       DateTimeFormatInfo.
                                       InvariantInfo)
                    };

                using (CngKey namedKey = CngKey.Create(CngAlgorithm2.Rsa, data.Key, keyCreationParameters))
                {
                    cert = namedKey.CreateSelfSignedCertificate(configCreate);
                    cert.FriendlyName = data.Friendlyname;
                    Assert.True(cert.HasPrivateKey);
                    Assert.True(cert.HasCngKey());
                    using (CngKey certKey = cert.GetCngPrivateKey())
                    {
                        Assert.Equal(CngAlgorithm2.Rsa, certKey.Algorithm);
                    }
                }
                return(cert);
            }
            finally
            {
                if (CngKey.Exists(data.Key))
                {
                    using (CngKey key = CngKey.Open(data.Key))
                    {
                        key.Delete();
                    }
                }
            }
        }
Esempio n. 21
0
        public CngKey GetOrGenerateKey(ECCurve?curve)
        {
            ThrowIfDisposed();

            if (_lazyKey != null)
            {
                return(_lazyKey);
            }

            // We don't have a key yet so generate
            Debug.Assert(curve.HasValue);

            CngKeyCreationParameters creationParameters = new CngKeyCreationParameters()
            {
                ExportPolicy = CngExportPolicies.AllowPlaintextExport,
            };

            if (curve.Value.IsNamed)
            {
                creationParameters.Parameters.Add(CngKey.GetPropertyFromNamedCurve(curve.Value));
            }
            else if (curve.Value.IsPrime)
            {
                ECCurve     eccurve        = curve.Value;
                byte[]      parametersBlob = ECCng.GetPrimeCurveParameterBlob(ref eccurve);
                CngProperty prop           = new CngProperty(
                    Interop.BCrypt.BCryptPropertyStrings.BCRYPT_ECC_PARAMETERS,
                    parametersBlob,
                    CngPropertyOptions.None);
                creationParameters.Parameters.Add(prop);
            }
            else
            {
                throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_CurveNotSupported, curve.Value.CurveType.ToString()));
            }

            try
            {
                _lazyKey = CngKey.Create(DefaultKeyType ?? CngAlgorithm.ECDsa, null, creationParameters);
            }
            catch (CryptographicException e)
            {
                // Map to PlatformNotSupportedException if appropriate
                ErrorCode errorCode = (ErrorCode)e.HResult;

                if (curve.Value.IsNamed &&
                    errorCode == ErrorCode.NTE_INVALID_PARAMETER || errorCode == ErrorCode.NTE_NOT_SUPPORTED)
                {
                    throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_CurveNotSupported, curve.Value.Oid.FriendlyName), e);
                }
                throw;
            }

            return(_lazyKey);
        }
Esempio n. 22
0
        // © 2017 Daniel Lerch
        /// <summary>
        /// Generates an ECDH keypair that can be used for key-derivation-operations.
        /// </summary>
        /// <param name="privateKey">The private key in EccPrivateBlob-format.</param>
        /// <param name="publicKey">The public key in EccPublicBlob-format.</param>
        public static void GenerateKey(out byte[] privateKey, out byte[] publicKey)
        {
            CngKeyCreationParameters param = new CngKeyCreationParameters();

            param.ExportPolicy = CngExportPolicies.AllowPlaintextExport;
            using (CngKey key = CngKey.Create(CngAlgorithm.ECDiffieHellmanP521, null, param))
            {
                privateKey = key.Export(CngKeyBlobFormat.EccPrivateBlob);
                publicKey  = key.Export(CngKeyBlobFormat.EccPublicBlob);
            }
        }
Esempio n. 23
0
        public static void AssociatePersistedKey_CNG_RSA()
        {
            const string KeyName = nameof(AssociatePersistedKey_CNG_RSA);

            CngKey            cngKey        = null;
            HashAlgorithmName hashAlgorithm = HashAlgorithmName.SHA256;

            byte[] signature;

            try
            {
                CngKeyCreationParameters creationParameters = new CngKeyCreationParameters()
                {
                    ExportPolicy       = CngExportPolicies.None,
                    Provider           = CngProvider.MicrosoftSoftwareKeyStorageProvider,
                    KeyCreationOptions = CngKeyCreationOptions.OverwriteExistingKey,
                };

                cngKey = CngKey.Create(CngAlgorithm.Rsa, KeyName, creationParameters);

                using (RSACng rsaCng = new RSACng(cngKey))
                {
                    CertificateRequest request = new CertificateRequest(
                        $"CN={KeyName}",
                        rsaCng,
                        HashAlgorithmName.SHA256,
                        RSASignaturePadding.Pkcs1);

                    DateTimeOffset now = DateTimeOffset.UtcNow;

                    using (X509Certificate2 cert = request.CreateSelfSigned(now, now.AddDays(1)))
                        using (RSA rsa = cert.GetRSAPrivateKey())
                        {
                            signature = rsa.SignData(Array.Empty <byte>(), hashAlgorithm, RSASignaturePadding.Pkcs1);

                            Assert.True(
                                rsaCng.VerifyData(Array.Empty <byte>(), signature, hashAlgorithm, RSASignaturePadding.Pkcs1));
                        }
                }

                // Some certs have disposed, did they delete the key?
                using (CngKey stillPersistedKey = CngKey.Open(KeyName, CngProvider.MicrosoftSoftwareKeyStorageProvider))
                    using (RSACng rsaCng = new RSACng(stillPersistedKey))
                    {
                        byte[] signature2 = rsaCng.SignData(Array.Empty <byte>(), hashAlgorithm, RSASignaturePadding.Pkcs1);

                        Assert.Equal(signature, signature2);
                    }
            }
            finally
            {
                cngKey?.Delete();
            }
        }
Esempio n. 24
0
        public void CreateCertificateReuseKey()
        {
            CngKeyCreationParameters keyCreationParameters = new CngKeyCreationParameters();

            keyCreationParameters.ExportPolicy = CngExportPolicies.AllowExport;

            using (CngKey key = CngKey.Create(CngAlgorithm2.Rsa, null, keyCreationParameters))
            {
                key.CreateSelfSignedCertificate(new X500DistinguishedName("CN=TestCert"));
                CngAlgorithm algorithm = key.Algorithm;
            }
        }
Esempio n. 25
0
    private static void partyBKey()
    {
        CngProvider ms                 = new CngProvider("SafeNet Key Storage Provider");
        string      keyLabel           = "AnotherTest";
        CngKeyCreationParameters param = new CngKeyCreationParameters();

        param.Provider           = ms;
        param.KeyUsage           = CngKeyUsages.AllUsages;
        param.KeyCreationOptions = CngKeyCreationOptions.OverwriteExistingKey;
        softKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP256, keyLabel, param);
        Console.WriteLine(softKey.Handle);
    }
Esempio n. 26
0
        private X509Certificate2 _GetSelfSignedCert(string subjectName)
        {
            var keyParam = new CngKeyCreationParameters
            {
                ExportPolicy       = CngExportPolicies.AllowExport,
                KeyCreationOptions = CngKeyCreationOptions.MachineKey | CngKeyCreationOptions.OverwriteExistingKey,
                KeyUsage           = CngKeyUsages.AllUsages,
                Provider           = CngProvider.MicrosoftSoftwareKeyStorageProvider,
            };

            keyParam.Parameters.Add(new CngProperty("Length", BitConverter.GetBytes(2048), CngPropertyOptions.None));

            CngKey key;

            try
            {
                key = CngKey.Create(CngAlgorithm2.Rsa, Guid.NewGuid().ToString(), keyParam);
            }
            catch (PlatformNotSupportedException)
            {
                try
                {
                    key = CngKey.Create(CngAlgorithm2.Aes, Guid.NewGuid().ToString(), keyParam);
                }
                catch (PlatformNotSupportedException)
                {
                    return(null);
                }
            }

            X509CertificateCreationParameters param = new X509CertificateCreationParameters(new X500DistinguishedName(subjectName))
            {
                SubjectName = new X500DistinguishedName(subjectName),
                EndTime     = DateTime.Today.AddYears(20) //,SignatureAlgorithm = X509CertificateSignatureAlgorithm.RsaSha512
            };

            OidCollection oc = new OidCollection {
                new Oid("1.3.6.1.5.5.7.3.1")
            };
            X509Extension eku = new X509EnhancedKeyUsageExtension(oc, true);

            param.Extensions.Add(eku);

            param.TakeOwnershipOfKey = true;

            byte[] rawData = key.CreateSelfSignedCertificate(param).Export(X509ContentType.Pfx, "");
            var    cert    = new X509Certificate2(rawData, "", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet)
            {
                FriendlyName = _RuleName + " Server Certificate"
            };

            return(cert);
        }
Esempio n. 27
0
 public ECDsaProvider(string newKeyName, string nullAble)
 {
     if (CngKey.Exists(newKeyName))
     {
         instance = new ECDsaCng(CngKey.Open(newKeyName));
     }
     else
     {
         CngKeyCreationParameters p = new CngKeyCreationParameters();
         p.ExportPolicy = CngExportPolicies.AllowExport;
         instance       = new ECDsaCng(CngKey.Create(CngAlgorithm.ECDsaP521, newKeyName, p));
     }
 }
Esempio n. 28
0
        public static void AddKeyToCng(string providerName, string containerName)
        {
            CngKeyCreationParameters keyParams = new CngKeyCreationParameters();

            keyParams.Provider           = new CngProvider(providerName);
            keyParams.KeyCreationOptions = CngKeyCreationOptions.OverwriteExistingKey;

            CngProperty keySizeProperty = new CngProperty("Length", BitConverter.GetBytes(2048), CngPropertyOptions.None);

            keyParams.Parameters.Add(keySizeProperty);

            CngKey mycngKey = CngKey.Create(CngAlgorithm.Rsa, containerName, keyParams);
        }
Esempio n. 29
0
        private static CngKey GetKeyForCng()
        {
            var ckcp = new CngKeyCreationParameters
            {
                KeyUsage     = CngKeyUsages.AllUsages,
                ExportPolicy = CngExportPolicies.AllowPlaintextExport | CngExportPolicies.AllowExport | CngExportPolicies.AllowArchiving | CngExportPolicies.AllowPlaintextArchiving,
            };

            ckcp.Parameters.Add(new CngProperty("Length", BitConverter.GetBytes(2048), CngPropertyOptions.None));
            var key = CngKey.Create(CngAlgorithm.Rsa, null, ckcp);

            return(key);
        }
Esempio n. 30
0
        public void OpenSubscriber()
        {
            try
            {
                if (IsListening())
                {
                    return;
                }

                log.InfoFormat("Opening subscriber endpoint at {0}", netTcpAddress);

                log.InfoFormat("Opening http subscriber endpoint at {0}", httpAddress);

                NotificationSubscriber notificationSubscriber = new NotificationSubscriber();
                notificationSubscriber.IndicationReceived += OnIndication;

                CngKeyCreationParameters keyCreationParameters = new CngKeyCreationParameters();
                keyCreationParameters.ExportPolicy = CngExportPolicies.AllowExport | CngExportPolicies.AllowPlaintextExport | CngExportPolicies.AllowPlaintextArchiving | CngExportPolicies.AllowArchiving;
                keyCreationParameters.KeyUsage     = CngKeyUsages.AllUsages;

                X509CertificateCreationParameters configCreate = new X509CertificateCreationParameters(new X500DistinguishedName("CN=SolarWinds-SwqlStudio"));
                configCreate.EndTime   = DateTime.Now.AddYears(1);
                configCreate.StartTime = DateTime.Now;

                using (CngKey cngKey = CngKey.Create(CngAlgorithm2.Rsa))
                {
                    X509Certificate2 certificate = cngKey.CreateSelfSignedCertificate(configCreate);
                    ServiceHost      host        = new ServiceHost(notificationSubscriber, new Uri(netTcpAddress), new Uri(httpAddress));
                    host.Credentials.ServiceCertificate.Certificate = certificate;
                    // SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindBySubjectDistinguishedName, "CN=SolarWinds-Orion");
                    host.Open();
                    subscriberHosts.Add(host);
                }

                log.Info("Http Subscriber endpoint opened");
            }
            catch (Exception ex)
            {
                log.ErrorFormat("Exception opening subscriber host with address {0}.\n{1}", httpAddress, ex);
            }

            foreach (ServiceHost serviceHost in subscriberHosts)
            {
                foreach (ChannelDispatcherBase channelDispatcher in serviceHost.ChannelDispatchers)
                {
                    log.InfoFormat("Listening on {0}", channelDispatcher.Listener.Uri.AbsoluteUri);
                }
            }

            ListenerOpened?.Invoke();
        }
Esempio n. 31
0
        /// <summary>
        /// Windows Azure Service Management API requires 2048bit RSA keys.
        /// The private key needs to be exportable so we can save it to .pfx for sharing with team members.
        /// </summary>
        /// <returns>A 2048 bit RSA key</returns>
        private static CngKey Create2048RsaKey()
        {
            var keyCreationParameters = new CngKeyCreationParameters
            {
                ExportPolicy       = CngExportPolicies.AllowExport,
                KeyCreationOptions = CngKeyCreationOptions.None,
                KeyUsage           = CngKeyUsages.AllUsages,
                Provider           = new CngProvider(MsEnhancedProv)
            };

            keyCreationParameters.Parameters.Add(new CngProperty("Length", BitConverter.GetBytes(KeySize2048), CngPropertyOptions.None));

            return(CngKey.Create(CngAlgorithm2.Rsa, null, keyCreationParameters));
        }
Esempio n. 32
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();
            }
        }
Esempio n. 33
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();
            }
        }