无法加载 RSA 公钥

aft*_*why 5 java rsa public-key

我正在尝试读取如下所示的 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);
Run Code Online (Sandbox Code Playgroud)

RSA 公钥:

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);
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

更新:

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

Dun*_*nes 2

你的问题是因为你的公钥是一个RSAPublicKey对象而不是一个SubjectPublicKeyInfo对象而引起的(有关差异的详细描述,请参阅此答案)。在代码运行之前,您需要从一种转换为另一种。

BouncyCastle 可以为您进行转换。下面的代码片段可以工作,尽管我不喜欢它有两个原因:

  1. 它使用了一个已弃用的类PEMReader

  2. 它需要加载 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...
Run Code Online (Sandbox Code Playgroud)

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