예제 #1
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();
            }
        }
예제 #2
0
 public byte[] CreateSignature(byte[] data)
 {
     return(dsaService.SignData(data, HashAlgorithmName.SHA256));
 }