예제 #1
0
 protected override void Dispose(bool disposing)
 {
     if (disposing && m_key != null)
     {
         m_key.Dispose();
     }
 }
        protected CngKey GetPrivateKey(X509Certificate2 cert)
        {
            var rsakey = cert.GetRSAPrivateKey() as RSACng;

            if (rsakey != null)
            {
                return(rsakey.Key);
            }

            CngKey cngkey = null;

            try
            {
                var provider = new CngProvider(CSPName);
                cngkey = CngKey.Open(KeyContainer, provider, CngKeyOpenOptions.MachineKey);

                if (cngkey == null)
                {
                    throw new InvalidOperationException(NuGetMSSignCommand.MSSignCommandNoCngKeyException);
                }

                if (cngkey.AlgorithmGroup != CngAlgorithmGroup.Rsa)
                {
                    cngkey.Dispose();
                    throw new InvalidOperationException(NuGetMSSignCommand.MSSignCommandInvalidCngKeyException);
                }

                return(cngkey);
            }
            catch (CryptographicException)
            {
                cngkey?.Dispose();
                throw new InvalidOperationException(NuGetMSSignCommand.MSSignCommandNoCngKeyException);
            }
        }
예제 #3
0
        private static X509Certificate2 CreateSelfSignedCertificate(CngKey key, X500DistinguishedName subjectName)
        {
            using (SafeCertContextHandle selfSignedCertHandle = CreateSelfSignedCertificate(key,
                                                                                            true,
                                                                                            subjectName.RawData,
                                                                                            X509CertificateCreationOptions.None, // NONE
                                                                                            RsaSha1Oid,
                                                                                            DateTime.UtcNow,
                                                                                            DateTime.UtcNow.AddYears(1)))
            {
                X509Certificate2 certificate = null;
                bool             addedRef    = false;
                RuntimeHelpers.PrepareConstrainedRegions();
                try
                {
                    selfSignedCertHandle.DangerousAddRef(ref addedRef);
                    certificate = new X509Certificate2(selfSignedCertHandle.DangerousGetHandle());
                }
                finally
                {
                    if (addedRef)
                    {
                        selfSignedCertHandle.DangerousRelease();
                    }
                }

                key.Dispose();

                return(certificate);
            }
        }
예제 #4
0
        public static X509Certificate2 CreateSelfSignedCertificate(this CngKey key,
                                                                   X509Certificates.X509CertificateCreationParameters creationParameters)
        {
            if (creationParameters == null)
            {
                throw new ArgumentNullException("creationParameters");
            }

            // If we are not being asked to hand ownership of the key over to the certificate, then we need
            // ensure that we are running in a trusted context as we have no way to ensure that the caller
            // will not force the key to be cleaned up and then continue to use the dangling handle left in
            // the certificate.
            if (!creationParameters.TakeOwnershipOfKey)
            {
                new PermissionSet(PermissionState.Unrestricted).Demand();
            }

            using (SafeCertContextHandle selfSignedCertHandle =
                       X509Native.CreateSelfSignedCertificate(key,
                                                              creationParameters.TakeOwnershipOfKey,
                                                              creationParameters.SubjectName.RawData,
                                                              creationParameters.CertificateCreationOptions,
                                                              X509Native.MapCertificateSignatureAlgorithm(creationParameters.SignatureAlgorithm),
                                                              creationParameters.StartTime,
                                                              creationParameters.EndTime,
                                                              creationParameters.ExtensionsNoDemand))
            {
                // We need to get the raw handle out of the safe handle because X509Certificate2 only
                // exposes an IntPtr constructor.  To do that we'll temporarially bump the ref count on
                // the handle.
                //
                // X509Certificate2 will duplicate the handle value in the .ctor, so once we've created
                // the certificate object, we can safely drop the ref count and dispose of our handle.
                X509Certificate2 certificate = null;
                bool             addedRef    = false;
                RuntimeHelpers.PrepareConstrainedRegions();
                try
                {
                    selfSignedCertHandle.DangerousAddRef(ref addedRef);
                    certificate = new X509Certificate2(selfSignedCertHandle.DangerousGetHandle());
                }
                finally
                {
                    if (addedRef)
                    {
                        selfSignedCertHandle.DangerousRelease();
                    }
                }

                // If we passed ownership of the key to the certificate, than destroy the key
                // now so that we don't continue to use it beyond the liftime of the cert.
                if (creationParameters.TakeOwnershipOfKey)
                {
                    key.Dispose();
                }

                return(certificate);
            }
        }
예제 #5
0
 public void DisposeKey()
 {
     if (_lazyKey != null)
     {
         _lazyKey.Dispose();
         _lazyKey = null;
     }
 }
예제 #6
0
파일: signtool.cs 프로젝트: wangfei0/NeoDun
        /// <summary>
        /// 使用私钥签名
        /// </summary>
        public static byte[] SignData(byte[] data, string keyName)
        {
            // 打开密钥
            CngKey cngKey = CngKey.Open(keyName);
            // 签名
            ECDsaCng ecdsa = new ECDsaCng(cngKey);

            byte[] signature = ecdsa.SignData(data);
            ecdsa.Clear();
            cngKey.Dispose();
            return(signature);
        }
예제 #7
0
파일: signtool.cs 프로젝트: wangfei0/NeoDun
        /// <summary>
        /// 使用公钥验证签名
        /// </summary>
        public static bool VerifyData(byte[] data, byte[] signature, byte[] publicKey)
        {
            bool verified = false;
            // 导入公钥
            CngKey cngKey = CngKey.Import(publicKey, CngKeyBlobFormat.EccPublicBlob);
            // 验证签名
            ECDsaCng ecdsa = new ECDsaCng(cngKey);

            verified = ecdsa.VerifyData(data, signature);
            ecdsa.Clear();
            cngKey.Dispose();
            return(verified);
        }
예제 #8
0
        private void ImportKeyBlob(byte[] rsaBlob, bool includePrivate)
        {
            CngKeyBlobFormat blobFormat = includePrivate ? s_rsaPrivateBlob : s_rsaPublicBlob;

            CngKey newKey = CngKey.Import(rsaBlob, blobFormat);

            try
            {
                newKey.ExportPolicy |= CngExportPolicies.AllowPlaintextExport;
                Key = newKey;
            }
            catch
            {
                newKey.Dispose();
                throw;
            }
        }
예제 #9
0
        private void ImportKeyBlob(byte[] dsaBlob, bool includePrivate)
        {
            // Use generic blob type for multiple version support
            CngKeyBlobFormat blobFormat = includePrivate ?
                                          CngKeyBlobFormat.GenericPrivateBlob :
                                          CngKeyBlobFormat.GenericPublicBlob;

            CngKey newKey = CngKey.Import(dsaBlob, blobFormat);

            try
            {
                newKey.ExportPolicy |= CngExportPolicies.AllowPlaintextExport;
                Key = newKey;
            }
            catch
            {
                newKey.Dispose();
                throw;
            }
        }
예제 #10
0
        public static void ExportDoesNotCorruptPrivateKeyMethods()
        {
            string    keyName = $"clrtest.{Guid.NewGuid():D}";
            X509Store cuMy    = new X509Store(StoreName.My, StoreLocation.CurrentUser);

            cuMy.Open(OpenFlags.ReadWrite);
            X509Certificate2 createdCert = null;
            X509Certificate2 foundCert   = null;
            X509Certificate2 foundCert2  = null;

            try
            {
                string commonName = nameof(ExportDoesNotCorruptPrivateKeyMethods);
                string subject    = $"CN={commonName},OU=.NET";

                using (ImportedCollection toClean = new ImportedCollection(cuMy.Certificates))
                {
                    X509Certificate2Collection coll = toClean.Collection;

                    using (ImportedCollection matches =
                               new ImportedCollection(coll.Find(X509FindType.FindBySubjectName, commonName, false)))
                    {
                        foreach (X509Certificate2 cert in matches.Collection)
                        {
                            cuMy.Remove(cert);
                        }
                    }
                }

                foreach (X509Certificate2 cert in cuMy.Certificates)
                {
                    if (subject.Equals(cert.Subject))
                    {
                        cuMy.Remove(cert);
                    }

                    cert.Dispose();
                }

                CngKeyCreationParameters options = new CngKeyCreationParameters
                {
                    ExportPolicy = CngExportPolicies.AllowExport | CngExportPolicies.AllowPlaintextExport,
                };

                using (CngKey key = CngKey.Create(CngAlgorithm.Rsa, keyName, options))
                    using (RSACng rsaCng = new RSACng(key))
                    {
                        CertificateRequest certReq = new CertificateRequest(
                            subject,
                            rsaCng,
                            HashAlgorithmName.SHA256,
                            RSASignaturePadding.Pkcs1);

                        DateTimeOffset now = DateTimeOffset.UtcNow.AddMinutes(-5);
                        createdCert = certReq.CreateSelfSigned(now, now.AddDays(1));
                    }

                cuMy.Add(createdCert);

                using (ImportedCollection toClean = new ImportedCollection(cuMy.Certificates))
                {
                    X509Certificate2Collection matches = toClean.Collection.Find(
                        X509FindType.FindBySubjectName,
                        commonName,
                        validOnly: false);

                    Assert.Equal(1, matches.Count);
                    foundCert = matches[0];
                }

                Assert.False(HasEphemeralKey(foundCert));
                foundCert.Export(X509ContentType.Pfx, "");
                Assert.False(HasEphemeralKey(foundCert));

                using (ImportedCollection toClean = new ImportedCollection(cuMy.Certificates))
                {
                    X509Certificate2Collection matches = toClean.Collection.Find(
                        X509FindType.FindBySubjectName,
                        commonName,
                        validOnly: false);

                    Assert.Equal(1, matches.Count);
                    foundCert2 = matches[0];
                }

                Assert.False(HasEphemeralKey(foundCert2));
            }
            finally
            {
                if (createdCert != null)
                {
                    cuMy.Remove(createdCert);
                    createdCert.Dispose();
                }

                cuMy.Dispose();

                foundCert?.Dispose();
                foundCert2?.Dispose();

                try
                {
                    CngKey key = CngKey.Open(keyName);
                    key.Delete();
                    key.Dispose();
                }
                catch (Exception)
                {
                }
            }

            bool HasEphemeralKey(X509Certificate2 c)
            {
                using (RSA key = c.GetRSAPrivateKey())
                {
                    // This code is not defensive against the type changing, because it
                    // is in the source tree with the code that produces the value.
                    // Don't blind-cast like this in library or application code.
                    RSACng rsaCng = (RSACng)key;
                    return(rsaCng.Key.IsEphemeral);
                }
            }
        }
예제 #11
0
 public override void Dispose()
 {
     m_cng?.Dispose();
     m_key?.Dispose();
 }
예제 #12
0
 public void Dispose()
 {
     _cngKey.Dispose();
 }
예제 #13
0
파일: CngPkcs8.cs 프로젝트: z77ma/runtime
 internal void FreeKey()
 {
     Key.Dispose();
 }