Converting A public key in SubjectPublicKeyInfo fo

2020-02-09 10:04发布

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?

3条回答
我只想做你的唯一
2楼-- · 2020-02-09 10:50

The following snippet of code worked for me, had to use BouncyCastle though.

byte[] keyBytes = key.getEncoded(); // X.509 for public key
SubjectPublicKeyInfo subPkInfo = new SubjectPublicKeyInfo((ASN1Sequence)ASN1Object.fromByteArray(keyBytes));
byte[] rsaformat = subPkInfo.getPublicKey().getDEREncoded();
查看更多
小情绪 Triste *
3楼-- · 2020-02-09 10:51

Without BouncyCastle:

PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(publicKeyBinary));                
查看更多
Emotional °昔
4楼-- · 2020-02-09 10:56

Use Bouncy Castle's SubjectPublicKeyInfo, like this:

byte[] encoded = publicKey.getEncoded();
SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo(
    ASN1Sequence.getInstance(encoded));
byte[] otherEncoded = subjectPublicKeyInfo.parsePublicKey().getEncoded();
查看更多
登录 后发表回答