我从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.");
}
}
答案 0 :(得分:3)
Java确实希望看到编码的SubjectPublicKeyInfo对象,但您有一个更简单的PKCS#1 RSAPublicKey对象。
我所知道的最简单的方法是使用bouncycastle PKIX库中的PEMParser类 - 应该有一个来自Spongycastle的等效库。使用此类代替您当前使用的PemReader类,如:
PEMParser pemParser = new PEMParser(new StringReader(publicKey));
SubjectPublicKeyInfo spki = (SubjectPublicKeyInfo) pemParser.readObject();
pemParser.close();
byte [] spkiEncoded = spki.getEncoded();
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(spkiEncoded);
KeyFactory kf = KeyFactory.getInstance("RSA");
this.publicKey = kf.generatePublic(keySpec);