编程语言
首页 > 编程语言> > java – 无法加载RSA公钥

java – 无法加载RSA公钥

作者:互联网

我正在尝试阅读下面显示的RSA公钥,但我在第6行遇到异常:java.security.spec.InvalidKeySpecException:java.security.InvalidKeyException:IOException:algid parse error,not a sequence

我的代码:

String rsaPublicKey = rsaPublicKeyString.replace(
    "-----BEGIN RSA PUBLIC KEY-----\n", "");
rsaPublicKey = rsaPublicKey.replace("\n-----END RSA PUBLIC KEY-----", "");
byte[] bytes = EncryptionUtils.decodeBase64(rsaPublicKey);

KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
pubKey = (RSAPublicKey)keyFactory.generatePublic(keySpec);

RSA公钥:

-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEAwVACPi9w23mF3tBkdZz+zwrzKOaaQdr01vAbU4E1pvkfj4sqDsm6
lyDONS789sVoD/xCS9Y0hkkC3gtL1tSfTlgCMOOul9lcixlEKzwKENj1Yz/s7daS
an9tqw3bfUV/nqgbhGX81v/+7RFAEd+RwFnK7a+XYl9sluzHRyVVaTTveB2GazTw
Efzk2DWgkBluml8OREmvfraX3bkHZJTKX4EQSjBbbdJ2ZXIsRrYOXfaA+xayEGB+
8hdlLmAjbCVfaigxX0CDqWeR1yFL9kwd9P0NsZRPsmoqVwMbMu7mStFai6aIhc3n
Slv8kg9qv1m6XHVQY3PnEw+QQtqSIXklHwIDAQAB
-----END RSA PUBLIC KEY-----

我究竟做错了什么?

UPD:

public static byte[] decodeBase64(String data) throws EncryptionException {
    try {
        BASE64Decoder decoder = new BASE64Decoder();
        return decoder.decodeBuffer(data);
    } catch (Exception e) {
        throw new EncryptionException(e);
    }
}

解决方法:

导致您的问题是因为您的公钥是RSAPublicKey对象而不是SubjectPublicKeyInfo对象(有关差异的详细描述,请参阅this answer).在代码运行之前,您需要从一个转换为另一个.

BouncyCastle可以为您进行转换.以下代码片段可以使用,但我不喜欢它有两个原因:

>它使用了弃用的类PEMReader.
>它需要加载BouncyCastle提供程序.

码:

Security.addProvider(new BouncyCastleProvider());    
PEMReader reader = new PEMReader(new StringReader(rsaPublicKeyString));    
BCRSAPublicKey key = (BCRSAPublicKey) reader.readObject();
bytes[] = key.getEncoded(); // now in SubjectPublicKeyInfo format.

// as before...

有了BouncyCastle,总有很多方法可以给猫皮肤涂抹.也许有人可以找到比上面更优雅的解决方案?

标签:java,rsa,public-key
来源: https://codeday.me/bug/20190629/1326190.html