java 将SubjectPublicKeyInfo格式的公钥转换为RSAPublicKey格式java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14052485/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting A public key in SubjectPublicKeyInfo format to RSAPublicKey format java
提问by Ashish Kumar Shah
The PublicKey.getEncoded(), returns a byte array containing the public key in SubjectPublicKeyInfo (x.509) format, how do i convert it to RSA public key encoding?
PublicKey.getEncoded() 返回一个字节数组,其中包含 SubjectPublicKeyInfo (x.509) 格式的公钥,我如何将其转换为 RSA 公钥编码?
回答by martijno
Use Bouncy Castle's SubjectPublicKeyInfo
, like this:
使用 Bouncy Castle 的SubjectPublicKeyInfo
,如下所示:
byte[] encoded = publicKey.getEncoded();
SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo(
ASN1Sequence.getInstance(encoded));
byte[] otherEncoded = subjectPublicKeyInfo.parsePublicKey().getEncoded();
回答by Michael Webster
Without BouncyCastle:
没有 BouncyCastle:
PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(publicKeyBinary));
回答by Ashish Kumar Shah
The following snippet of code worked for me, had to use BouncyCastle though.
以下代码片段对我有用,但必须使用 BouncyCastle。
byte[] keyBytes = key.getEncoded(); // X.509 for public key
SubjectPublicKeyInfo subPkInfo = new SubjectPublicKeyInfo((ASN1Sequence)ASN1Object.fromByteArray(keyBytes));
byte[] rsaformat = subPkInfo.getPublicKey().getDEREncoded();