简体   繁体   English

如何将PEM公钥转换为DER公钥?

[英]How to convert PEM public key to DER public key?

I receive a public key from my REST API which is encoded in PEM. 我从REST API接收一个公钥,该公钥在PEM中编码。 Now, I need to change the encoding to DER in order to store it as a PublicKey object. 现在,我需要将编码更改为DER,以便将其存储为PublicKey对象。 However, unfortunately, I get the following error: 但是,遗憾的是,我收到以下错误:

java.lang.IllegalArgumentException: unknown object in getInstance: org.spongycastle.asn1.ASN1Integer java.lang.IllegalArgumentException:getInstance中的未知对象:org.spongycastle.asn1.ASN1Integer

And the error is pointing to this line: 错误指向这一行:

RSAKeyParameters rsa = (RSAKeyParameters) PublicKeyFactory.createKey(pemReader.readPemObject().getContent());

The public key looks like this: 公钥如下所示:

-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEA04XyJ5K4sQCtqapk98yEAR/ECaVC85JYPsqC09GiZboNdSSxQXj3
UNb53Po8iNX24T4elyjjzqQpVcyi+eaFp9Fggg2ZDyK9Re1wTucs0APDQdsGe1Q5
KImT/SBycI7v1RwSgjQ4I6npMg/0lZY8bnw4Q1AaTIII0KFBHmIYBD1oeCSdVPED
JWQWTSXtStQj83Vyj1uSLEEzXLpVYW4fq8e24tH2D/1j6eIBnBw6YpkWE6T9pZlE
wIs8YoeQWt5+lPWI28PST8VKqXsxH6JVzu5Mj6jLw8WTZxyKvNaGgO4B3J/ze/58
zW0LtlhsKMEq48QdLgPJZ+tfac2EhKANrQIDAQAB
-----END RSA PUBLIC KEY-----

Here is my code: 这是我的代码:

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.");
    }
}

Java really wants to see an encoded SubjectPublicKeyInfo object, but you have a simpler PKCS#1 RSAPublicKey object. Java确实希望看到编码的SubjectPublicKeyInfo对象,但是您有一个更简单的PKCS#1 RSAPublicKey对象。

The easiest way I know of is to use the PEMParser class from bouncycastle PKIX library -- there should be an equivalent library from Spongycastle. 我所知道的最简单的方法是使用bouncycastle PKIX库中的PEMParser类 - 应该有一个来自Spongycastle的等效库。 Use this class in lieu of the PemReader class you are currently using, as in: 使用此类代替您当前使用的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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM