无法加载 RSA 公钥 [英] Unable to load RSA public key

查看:150
本文介绍了无法加载 RSA 公钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试读取如下所示的 RSA 公钥,但在第 6 行出现异常:java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException: algid parse error, not a sequence

I'm trying to read RSA public key shown below, but I get an exception at line 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-----

我做错了什么?

更新:

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 对象(见此答案 对差异的详细描述).您需要先从一种转换为另一种,然后代码才能工作.

Your problem is caused because your public key is an RSAPublicKey object rather than a SubjectPublicKeyInfo object (see this answer for a good description of the difference). You will need to convert from one to the other before your code will work.

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

BouncyCastle can do the conversion for you. The following code snippet will work, although I dislike it for two reasons:

  1. 它使用不推荐使用的类 <代码>PEMReader.

它需要加载 BouncyCastle 提供程序.

It requires the BouncyCastle provider to be loaded.

代码:

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,总有很多方法可以给猫剥皮.也许有人可以找到比上面更优雅的解决方案?

With BouncyCastle, there is always many ways to skin a cat. Perhaps someone can find a more elegant solution than the one above?

这篇关于无法加载 RSA 公钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆