Converting A public key in SubjectPublicKeyInfo format to RSAPublicKey format java

时光总嘲笑我的痴心妄想 提交于 2019-11-29 02:05:32
martijno

Use Bouncy Castle's SubjectPublicKeyInfo, like this:

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

Without BouncyCastle:

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

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