简体   繁体   English

将字节数组转换为X.509证书

[英]Converting a byte array to a X.509 certificate

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. 我正在尝试将一段Java代码移植到.NET中,该代码采用Base64编码的字符串,将其转换为字节数组,然后使用其制作X.509证书以获得RSA加密的模数和指数。

This is the Java code I'm trying to convert: 这是我要转换的Java代码:

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. 我一直在尝试找出将其转换为.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. 在我看来,它应该可以工作,但是当我使用Java代码中以base 64编码的字符串生成X509证书时,它将引发CryptographicException 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? Java的X.509实现只是与.NET不兼容,还是我从Java转换为.NET时做错了什么?

Or is there simply no conversion from Java to .NET in this case? 还是在这种情况下根本就没有从Java到.NET的转换?

It seems your base64-encoded data does not represent an X.509 certificate: 看来您的base64编码数据不代表X.509证书:

[The X509EncodedKeySpec class ] represents the ASN.1 encoding of a public key [ X509EncodedKeySpec类 ]表示公钥的ASN.1编码

Export the whole X.509 certificate in Java, or try to find an equivalent of the X509EncodedKeySpec class in the .NET framework. 用Java导出整个X.509证书,或尝试在.NET框架中找到等效的X509EncodedKeySpec类。

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) 解决方案就是简单地反转字节数组(.NET中的Array.Reverse)。

I don't have the 2 IDEs in front of me to show a proof, but if you get stuck, give it a try! 我面前没有2个IDE来显示证明,但是如果您遇到困难,请尝试一下!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM