如何构造一个java.security.interfaces.RSAPublicKey?

how to construct a java.security.interfaces.RSAPublicKey?

我有以下字符串,据我所知是一个 RSA public 密钥:

MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAi+VPTFioJ3Dv/D6aEMqkiESiRkKBnISe3+K7vJDMAMqkTCfGz0jKInS5BXQUW9jRqkgBpSKdwizIWhCBOT3wGmgnm+L3bVwtTML52drqePSmQgfHAiWfcLdZuFGULtpy5nhaOAR5nzuDmDR8L0vumNbhqK+o9jbwSTbm8cfUsf7xHc7RX+bJinu5s566NtxqJ0y8U764BVPg96QLKpOEiNJUELarkdnljjdb12Gvs+631YFKAnUt5V9oHowBS1JDerlbhHKH6kYKEuVZfm5ofvhGQiUU69i9q/hO5Pb0eIZsogazERJmEIIvre8sQLNE71ti0WD3i7QDGlnsoai6EwIDAQAB

我需要从这个字符串构造一个 java.security.interfaces.RSAPublicKey。首先我尝试调用 RSAPublicKeyImpl.newKey(myString.getBytes(StandardCharsets.UTF_8)),但抛出了以下异常:

java.security.InvalidKeyException: invalid key format
"sun.security.x509.X509Key.decode(X509Key.java:387)"
"sun.security.x509.X509Key.decode(X509Key.java:402)"
"sun.security.rsa.RSAPublicKeyImpl.<init>(RSAPublicKeyImpl.java:122)"
"sun.security.rsa.RSAPublicKeyImpl.newKey(RSAPublicKeyImpl.java:72)"
"com.myApp.getPublicKeyRsa(KeyLoader.java:33)"

然后,按照在线指南,我尝试了以下代码:

KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(myString.getBytes(StandardCharsets.UTF_8));
keyFactory.generatePublic(pubSpec);

那引发了一个非常相似的异常,只是包裹在另一个异常中。

我是不是遗漏了什么明显的东西?如何构建 RSAPublicKey?

这个方法可以帮到你

  public static PublicKey stringToPublicKey(String publicKeyString)
        throws NoSuchAlgorithmException,
        NoSuchPaddingException,
        InvalidKeyException,
        IllegalBlockSizeException,
        BadPaddingException {

    try {
        if (publicKeyString.contains("-----BEGIN PUBLIC KEY-----") || publicKeyString.contains("-----END PUBLIC KEY-----"))
            publicKeyString = publicKeyString.replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", "");
        byte[] keyBytes = Base64.decode(publicKeyString, Base64.DEFAULT);
        X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");

        return keyFactory.generatePublic(spec);

    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        e.printStackTrace();

        return null;
    }
}