Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting a Bad Data exception only 5% of the time?

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?

like image 816
djbyter Avatar asked Jul 05 '13 15:07

djbyter


1 Answers

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.

like image 120
Peter Dettman Avatar answered Nov 10 '22 01:11

Peter Dettman