Converting a byte array to a X.509 certificate

Posted by ddd on Stack Overflow See other posts from Stack Overflow or by ddd
Published on 2010-03-28T19:03:48Z Indexed on 2010/03/28 19:13 UTC
Read the original article Hit count: 1927

Filed under:
|
|
|
|

I'm trying to port a piece of Java code into .NET that takes a Base64 encoded string, converts it to a byte array, and then uses it to make a X.509 certificate to get the modulus & exponent for RSA encryption.

This is the Java code I'm trying to convert:

byte[] externalPublicKey = Base64.decode("base 64 encoded string");
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(externalPublicKey);
Key publicKey = keyFactory.generatePublic(publicKeySpec);
RSAPublicKey pbrtk = (java.security.interfaces.RSAPublicKey) publicKey;
BigInteger modulus = pbrtk.getModulus();
BigInteger pubExp = pbrtk.getPublicExponent();

I've been trying to figure out the best way to convert this into .NET. So far, I've come up with this:

byte[] bytes = Convert.FromBase64String("base 64 encoded string");
X509Certificate2 x509 = new X509Certificate2(bytes);
RSA rsa = (RSA)x509.PrivateKey;
RSAParameters rsaParams = rsa.ExportParameters(false);
byte[] modulus = rsaParams.Modulus;
byte[] exponent = rsaParams.Exponent;

Which to me looks like it should work, but it throws an exception when I use the base 64 encoded string from the Java code to generate the X509 certificate.

Is Java's X.509 implementation just incompatible with .NET's, or am I doing something wrong in my conversion from Java to .NET?

Or is there simply no conversion from Java to .NET in this case?

© Stack Overflow or respective owner

Related posts about cryptography

Related posts about x509certificate2