5

我有以下代码在大约 5% 的时间里抛出 CryptographicException 并且我不知道为什么 a) 它没有持续失败和 b) 为什么它完全失败:

// Initialize the new secure keys
var keyGenerator = KeyGenerator.Create();
var keyPair = keyGenerator.GenerateKeyPair();
this._privateKey = keyPair.ToEncryptedPrivateKeyString(privateKeySecret);
this._publicKey = keyPair.ToPublicKeyString();

// Initialize the certificate generation
var certificateGenerator = new X509V3CertificateGenerator();
var serialNo = BigInteger.ProbablePrime(128, new Random());
certificateGenerator.SetSerialNumber(serialNo);
certificateGenerator.SetSubjectDN(GetLicenseeDN());
certificateGenerator.SetIssuerDN(GetLicencerDN());
certificateGenerator.SetNotAfter(DateTime.Now.AddYears(100));
certificateGenerator.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0)));
certificateGenerator.SetSignatureAlgorithm("SHA512withRSA");
certificateGenerator.SetPublicKey(keyPair.PublicKey);
var result = certificateGenerator.Generate(keyPair.PrivateKey);
this._clientCertificate = new X509Certificate2(DotNetUtilities.ToX509Certificate(result));
this._clientCertificate.PrivateKey = DotNetUtilities.ToRSA((RsaPrivateCrtKeyParameters)keyPair.PrivateKey);

堆栈看起来像:

System.Security.Cryptography.CryptographicException: Bad Data.
Result StackTrace:  
at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)
   at System.Security.Cryptography.Utils._ImportKey(SafeProvHandle hCSP, Int32 keyNumber, CspProviderFlags flags, Object cspObject, SafeKeyHandle& hKey)
   at System.Security.Cryptography.RSACryptoServiceProvider.ImportParameters(RSAParameters parameters)
   at Org.BouncyCastle.Security.DotNetUtilities.ToRSA(RsaPrivateCrtKeyParameters privKey) in C:\BouncyCastle\crypto\src\security\DotNetUtilities.cs:line 173
   at EBSConnect.EBSClientBase.InitializeSecurity(String privateKeySecret) in c:\Projects\EBSConnect\Source\EBSConnect\EBSClientBase.cs:line 78

其余时间 (95%),此代码按预期工作,我能够使用此动态生成的证书与联合服务通信。有任何想法吗?

4

1 回答 1

7

假设您使用的是 BouncyCastle C# 1.7,从 BigInteger 到 byte[] 的转换存在一些问题(与前导零有关)。这些已在源代码中修复,但尚未发布。我建议制作最新DotNetUtilities类的本地副本并在您的项目中使用它,直到有新版本可用。

于 2013-07-06T23:30:02.780 回答