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开发者_如何学Go 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?
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.
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!
精彩评论