我需要为不支持 SHA256 的旧旧系统生成 SHA1 哈希证书。我很清楚不建议在加密场景中使用 MD5 和 SHA1 哈希,但这是一个外部要求。
我正在使用 .NET Framework 4.7.2 及其新的CertificateRequest类。
这是相关的代码片段:
using (var rsa = RSA.Create(2048))
{
var subjectName = "CN=sampleName";
var certificateRequest = new CertificateRequest(subjectName, rsa, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
var selfSignedCertificate = certificateRequest.CreateSelfSigned(DateTime.UtcNow, DateTime.UtcNow.AddYears(10));
var certAsBytes = selfSignedCertificate.Export(X509ContentType.Pfx, "fakePassword");
File.WriteAllBytes("cert-sha1.pfx", certAsBytes);
}
当certificateRequest.CreateSelfSigned
被调用时,它会抛出以下异常:
'SHA1' is not a known hash algorithm.
Parameter name: hashAlgorithm
Actual value was SHA1.
堆栈跟踪中的相关点是:
...
at System.Security.Cryptography.X509Certificates.RSAPkcs1X509SignatureGenerator.GetSignatureAlgorithmIdentifier(HashAlgorithmName hashAlgorithm)
at System.Security.Cryptography.X509Certificates.TbsCertificate.Encode(X509SignatureGenerator signatureGenerator, HashAlgorithmName hashAlgorithm)
at System.Security.Cryptography.X509Certificates.TbsCertificate.Sign(X509SignatureGenerator signatureGenerator, HashAlgorithmName hashAlgorithm)
at System.Security.Cryptography.X509Certificates.CertificateRequest.Create(X500DistinguishedName issuerName, X509SignatureGenerator generator, DateTimeOffset notBefore, DateTimeOffset notAfter, Byte[] serialNumber)
at System.Security.Cryptography.X509Certificates.CertificateRequest.CreateSelfSigned(DateTimeOffset notBefore, DateTimeOffset notAfter)
at Tests.Sha1Test()
从我正在使用的构造函数的.NET API 浏览器中,即使不推荐,我也看不出为什么这不起作用。使用 MD5 会引发类似的异常。SHA256 及更高版本工作正常。
该类CertificateRequest
也没有显示在参考源中(可能是因为它太新了?)所以我没有想法。