将SubjectPublicKeyInfo格式的公钥转换为RSAPublicKey格式java

时间:2012-12-27 09:40:26

标签: java cryptography rsa pkcs#1

PublicKey.getEncoded()返回一个包含SubjectPublicKeyInfo(x.509)格式的公钥的字节数组,如何将其转换为RSA公钥编码?

3 个答案:

答案 0 :(得分:14)

使用Bouncy Castle的SubjectPublicKeyInfo,如下所示:

byte[] encoded = publicKey.getEncoded();
SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo(
    ASN1Sequence.getInstance(encoded));
byte[] otherEncoded = subjectPublicKeyInfo.parsePublicKey().getEncoded();

答案 1 :(得分:3)

没有BouncyCastle:

PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(publicKeyBinary));                

答案 2 :(得分:0)

以下代码片段对我有用,但不得不使用BouncyCastle。

byte[] keyBytes = key.getEncoded(); // X.509 for public key
SubjectPublicKeyInfo subPkInfo = new SubjectPublicKeyInfo((ASN1Sequence)ASN1Object.fromByteArray(keyBytes));
byte[] rsaformat = subPkInfo.getPublicKey().getDEREncoded();