java.security.spec.invalidkeyspecexception:java.security.invalidkeyexception:密钥格式无效

yizd12fk  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(1269)

我正在尝试用java获取用于jwt令牌验证的rsa公钥,但尝试失败,出现以下异常:java.security.spec.invalidkeyspecexception:java.security.invalidkeyexception:invalid key format。
我的代码:

String publicKeyString = "LS0tLS1CRUdJTiBSU0EgUFVCTElDIEtFWS0tLS0tCk1JSUJJakFOQmdrcWhraUc5dzBCQVFFRkFBT0NBUThBTUlJQkNnS0NBUUVBMk5pKytLeUpVaDhLYklLVU51OG0KUk5lRCtrU2tXZEh6MjBvSFZYK0g0cVd4WHlJSTk0MVdJUFU2WFpPc3lMeE9qZU1hb0ZRanJ6bDFwYnZQekUyRQpwMmhlK1BnQ1JteDNqOFlMVVd3dGpuQTVwTTFLWDhpNG5vTUw4RmlWY1U2NkE5RjRkZmRQR2MzY0tQQ2ZPbnorCmtBbW5qRllzajYzRCsrTThYSDRWaS9Vc0V3T1lzU05FR2RncUd2OTlTNHpVRzFzd2FqZ1NnODhvbTVaOC9Ja1AKY01LT3cvWkpvVHNDN3l1VlJnTC9xa3EwaDVkM2lXVXNNdXl1K0xoblRhTko4bW9WQmpJT2lQQkR0cEQyN1lzNgpCSGs1dEdBa3ZHZDg0N3c4SjVEeTFzYWlQS0pxelltcUx5akg3b3VlcERFczdEZ2UxZUlJeno5a1RnSkhKZHVzCnd3SURBUUFCCi0tLS0tRU5EIFJTQSBQVUJMSUMgS0VZLS0tLS0K";
    PublicKey publicKey = getPublicKey(Base64.getDecoder().decode(publicKeyString), "RSA");

和getpublickey函数:

private static PublicKey getPublicKey(byte[] keyBytes, String algorithm) {
    PublicKey publicKey = null;
    try {
        KeyFactory kf = KeyFactory.getInstance(algorithm);
        EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        System.out.println(keySpec.getFormat());

        publicKey = kf.generatePublic(keySpec);
    } catch (NoSuchAlgorithmException e) {
        System.out.println("Could not reconstruct the public key, the given algorithm could not be found.");
    } catch (InvalidKeySpecException e) {
        e.printStackTrace();
        System.out.println("Could not reconstruct the public key");
    }

    return publicKey;
}

我知道有许多类似的问题处理同一个异常被抛出,我读了很多,并尝试了解决办法,但没有任何工作。如果有任何帮助,我将不胜感激。

pkwftd7m

pkwftd7m1#

您的数据不是java crypto要求的实际x.509公钥块(subjectpublickeyinfo)的base64编码。它实际上是pem文件的base64编码,它本身是结构化和编码的。此外,此pem文件被标记为包含“rsa公钥”,这将是“原始”pkcs1形式,对java来说是错误的,但幸运的是,创建此pem文件的任何内容都有缺陷,并且pem文件的主体实际上是一个x.509 subjectpublickeyinfo,根据rfc7468#13,它应该具有pem标签“公钥”(rfc5280是x.509的配置文件。)
因此,您需要将字符串解码为pem,然后解析pem以获得x.509:

String orig = "LS0tLS1CRUdJTiBSU0EgUFVCTElDIEtFWS0tLS0tCk1JSUJJakFOQmdrcWhraUc5dzBCQVFFRkFBT0NBUThBTUlJQkNnS0NBUUVBMk5pKytLeUpVaDhLYklLVU51OG0KUk5lRCtrU2tXZEh6MjBvSFZYK0g0cVd4WHlJSTk0MVdJUFU2WFpPc3lMeE9qZU1hb0ZRanJ6bDFwYnZQekUyRQpwMmhlK1BnQ1JteDNqOFlMVVd3dGpuQTVwTTFLWDhpNG5vTUw4RmlWY1U2NkE5RjRkZmRQR2MzY0tQQ2ZPbnorCmtBbW5qRllzajYzRCsrTThYSDRWaS9Vc0V3T1lzU05FR2RncUd2OTlTNHpVRzFzd2FqZ1NnODhvbTVaOC9Ja1AKY01LT3cvWkpvVHNDN3l1VlJnTC9xa3EwaDVkM2lXVXNNdXl1K0xoblRhTko4bW9WQmpJT2lQQkR0cEQyN1lzNgpCSGs1dEdBa3ZHZDg0N3c4SjVEeTFzYWlQS0pxelltcUx5akg3b3VlcERFczdEZ2UxZUlJeno5a1RnSkhKZHVzCnd3SURBUUFCCi0tLS0tRU5EIFJTQSBQVUJMSUMgS0VZLS0tLS0K";

        String pem = new String(Base64.getDecoder().decode(orig)); // default cs okay for PEM
        String[] lines = pem.split("\n"); lines[0] = lines[lines.length-1] = ""; String body = String.join("", lines);
        // in general split on "\r?\n" (or delete "\r" and split on "\n")
        //or instead:
        //String body = pem.replaceAll("-----(BEGIN|END) RSA PUBLIC KEY-----\n","").replaceAll("\n", ""); // or "\r?\n"

        KeyFactory kf = KeyFactory.getInstance("RSA");
        PublicKey key = kf.generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(body)));
        // for test only:
        System.out.println ( ((java.security.interfaces.RSAPublicKey)key).getModulus() );

请注意,您的特定数据具有使用单个字符(nl)的pem \n )换行符,但pem通常可以使用nl或crlf( \r\n ); 请看我的评论。

相关问题