我从我的 REST API 收到一个公钥,该公钥以 PEM 编码。现在,我需要将编码更改为 DER 以便将其存储为PublicKey
对象。但是,不幸的是,我收到以下错误:
java.lang.IllegalArgumentException:getInstance 中的未知对象:org.spongycastle.asn1.ASN1Integer
错误指向这一行:
RSAKeyParameters rsa = (RSAKeyParameters) PublicKeyFactory.createKey(pemReader.readPemObject().getContent());
公钥如下所示:
-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEA04XyJ5K4sQCtqapk98yEAR/ECaVC85JYPsqC09GiZboNdSSxQXj3
UNb53Po8iNX24T4elyjjzqQpVcyi+eaFp9Fggg2ZDyK9Re1wTucs0APDQdsGe1Q5
KImT/SBycI7v1RwSgjQ4I6npMg/0lZY8bnw4Q1AaTIII0KFBHmIYBD1oeCSdVPED
JWQWTSXtStQj83Vyj1uSLEEzXLpVYW4fq8e24tH2D/1j6eIBnBw6YpkWE6T9pZlE
wIs8YoeQWt5+lPWI28PST8VKqXsxH6JVzu5Mj6jLw8WTZxyKvNaGgO4B3J/ze/58
zW0LtlhsKMEq48QdLgPJZ+tfac2EhKANrQIDAQAB
-----END RSA PUBLIC KEY-----
这是我的代码:
public void setPublicKey(String publicKey) {
try {
PemReader pemReader = new PemReader(new StringReader(publicKey));
RSAKeyParameters rsa = (RSAKeyParameters) PublicKeyFactory.createKey(pemReader.readPemObject().getContent());
pemReader.close();
RSAPublicKeySpec rsaSpec = new RSAPublicKeySpec(rsa.getModulus(), rsa.getExponent());
KeyFactory kf = KeyFactory.getInstance("RSA/ECB/PKCS1Padding");
this.publicKey = kf.generatePublic(rsaSpec);
} catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException ex) {
ex.printStackTrace();
throw new IllegalStateException("Cannot set public key.");
}
}