Reading DER Private Key in C # Using BouncyCastle

I am trying to read the RSA private key in .Net using BouncyCastle to verify the data I previously encrypted. The encrypted data works fine using the public key and Bouncy Castle, and I also used the same private key as below (which is DER format) to successfully decrypt my data in a PHP application, but I don't know why I cannot create .Net private key to do the same:

byte[] privatekey = File.ReadAllBytes(@"C:\Users\Luke\privkey.der");
var rsaKeyParameters = (RsaKeyParameters)PrivateKeyFactory.CreateKey(privatekey);

The second line throws an exception:

"unknown object in factory: DerInteger \ r \ nParameter: obj"

I also tried using a stream instead of a byte array and the same error. The key pair was created using OpenSSL, and as already mentioned, decryption works in PHP using openssl_private_decrypt () and the same key as in the .Net code. I also tried the PEM format of the same key, and that didn't work either (but I don't think BC supports PEM directly)

Has anyone done this before? Thanks

+4
source share
1 answer

The problem was that I suggested that PublicKeyFactory and PrivateKeyFactory are free, as they are in the same namespace. They are not!

To decode the private key, I need the following alternative code:

var privKeyObj = Asn1Object.FromStream(privatekey);
var privStruct = new RsaPrivateKeyStructure((Asn1Sequence)privKeyObj);

// Conversion from BouncyCastle to .Net framework types
var rsaParameters = new RSAParameters();
rsaParameters.Modulus = privStruct.Modulus.ToByteArrayUnsigned();
rsaParameters.Exponent = privStruct.PublicExponent.ToByteArrayUnsigned();
rsaParameters.D = privStruct.PrivateExponent.ToByteArrayUnsigned();
rsaParameters.P = privStruct.Prime1.ToByteArrayUnsigned();
rsaParameters.Q = privStruct.Prime2.ToByteArrayUnsigned();
rsaParameters.DP = privStruct.Exponent1.ToByteArrayUnsigned();
rsaParameters.DQ = privStruct.Exponent2.ToByteArrayUnsigned();
rsaParameters.InverseQ = privStruct.Coefficient.ToByteArrayUnsigned();
var rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(rsaParameters);
return Encoding.UTF8.GetString(rsa.Decrypt(Convert.FromBase64String(ciphertext), true));

A .

+7

All Articles