我需要生成我自己的DSA密鑰對,並使用C#將它作爲一組私鑰和證書存儲在.p12文件中。如何在C#中爲DSA密鑰對創建帶有自簽名證書的PKCS12 p12文件?
這個問題
How do I create a PKCS12 .p12 file in C#?
似乎非常相似,但它並不能幫助我,不幸的是,因爲有一些顯著的差異(RSA VS DSA等)
我嘗試使用System.Security.Cryptography.DSACryptoServiceProvider生成密鑰對,然後使用Bouncy Castle生成X509證書:
using (DSACryptoServiceProvider csp = new DSACryptoServiceProvider(1024))
{
privKeyDSA = csp.ExportParameters(true);
pubKeyDSA = csp.ExportParameters(false);
var keypair = DotNetUtilities.GetDsaKeyPair(privKeyDSA);
var gen = new X509V3CertificateGenerator();
var CN = new X509Name("CN=" + "TEST");
var SN = BigInteger.ProbablePrime(120, new Random());
gen.SetSerialNumber(SN);
gen.SetSubjectDN(CN);
gen.SetIssuerDN(CN);
gen.SetNotAfter(DateTime.MaxValue);
gen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0)));
gen.SetSignatureAlgorithm("sha1WithDSA");
gen.SetPublicKey(DotNetUtilities.GetDsaPublicKey(pubKeyDSA));
var newCert = gen.Generate(keypair.Private);
certificateDSA = new X509Certificate2(DotNetUtilities.ToX509Certificate((Org.BouncyCastle.X509.X509Certificate)newCert));
certificateDSA.PrivateKey = csp;
StringBuilder builder = new StringBuilder();
builder.AppendLine("-----BEGIN CERTIFICATE-----");
builder.AppendLine(Convert.ToBase64String(certificateDSA.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks));
builder.AppendLine("-----END CERTIFICATE-----");
string result = builder.ToString();
byte[] pkcsData = certificateDSA.Export(X509ContentType.Pfx, "changeit");
}
但是,行certificateDSA.PrivateKey = csp;
拋出CryptographicUnexpectedOperationException
與消息:"The public key of the certificate does not match the value specified."
我真的不明白髮生了什麼事。我究竟做錯了什麼?謝謝!
它現在有效,證書看起來不錯,我會測試它是否可以。做得好!謝謝! – vojta