views:

783

answers:

2

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?

+2  A: 

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.

dtb
A: 

I have encountered a similar issue, and in my case it boiled down to an 'endian' problem.

The solution was simply to reverse the byte array (Array.Reverse in .NET)

I don't have the 2 IDEs in front of me to show a proof, but if you get stuck, give it a try!

amir75
I just tried reversing my byte array and I got the same exception :-/
ddd
OK. The other poster read your question more thoroughly than me!In the Java, you're using a X509EncodedKeySpec, which represents the public key part of the certificate (not the whole certificate).In the C# you're treating the data as a whole certificate. The public key part of an X509Certificate2 is simply called a PublicKey. Maybe you'd have some success constructing a PublicKey object ...http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.publickey.publickey.aspx
amir75