Converting a byte array to a X.509 certificate

爷,独闯天下 提交于 2019-12-06 06:35:03

问题


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?


回答1:


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.




回答2:


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!



来源:https://stackoverflow.com/questions/2534127/converting-a-byte-array-to-a-x-509-certificate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!