I have the following code which is throwing a CryptographicException about 5% of the time and I can't figure out why a) it doesn't fail consistently and b) why it's failing at all:
// 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);
The stack looks like:
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
The rest of the time (95%), this code works as expected and I'm able to communicate with a federated service using this dynamically generated certificate. Any ideas?
Assuming you are using BouncyCastle C# 1.7, there were some problems with the conversion from BigInteger to byte[] (to do with leading zeroes). These have been fixed in the source code, but not yet released. I suggest making a local copy of the latest DotNetUtilities class and using that in your project until a new release is available.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With