【问题标题】:Why am I getting a Bad Data exception only 5% of the time?为什么我只有 5% 的时间会收到错误数据异常?
【发布时间】:2013-07-03 18:08:39
【问题描述】:

我有以下代码,它在大约 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%),此代码按预期工作,我能够使用此动态生成的证书与联合服务通信。有什么想法吗?

【问题讨论】:

  • 请注明您使用的代码和库。当我寻找ToEncryptedPrivateKeyString(仅举一个例子)时,我得到零点击。
  • 对不起@owlstead,我不认为这很重要。我试图指出的问题是 DotNetUtilities.ToRSA 的使用,它引发了异常。
  • 不,我想我在那里忽略了 BouncyCastle 标签:(

标签: c# .net encryption cryptography bouncycastle


【解决方案1】:

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

【讨论】:

  • 谢谢彼得,看起来好多了。看起来您正在将存储库移动到 github?
  • 我们已将源代码移至内部 git 存储库,该存储库镜像在 github 上。 CVS 存储库不会更新,但它仍会存在一段时间。
  • @zaitsman 我假设更改已经发布,因为我看到 1.8.0 和 1.8.1 已经发布。
  • 它们已被释放。请注意,对于此问题的新查看者,不再需要此解决方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-18
相关资源
最近更新 更多