Converting a byte array to a X.509 certificate

ddd picture ddd · Mar 28, 2010 · Viewed 12.3k times · Source

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 a CryptographicException when I use the base 64 encoded string from the Java code to generate the X509 certificate. The exact message I receive is:

Cannot find the requested object.

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?

Answer

dtb picture dtb · Mar 28, 2010

It seems your base64-encoded data does not represent an X.509 certificate:

[The X509EncodedKeySpec class] represents the ASN.1 encoding of a public key

Export the whole X.509 certificate in Java, or try to find an equivalent of the X509EncodedKeySpec class in the .NET framework.