Algid 解析错误,不是序列

问题描述 投票:0回答:4

当尝试使用该方法从文件中读取 RSA 私钥时

public PrivateKey getPrivateKey()
        throws NoSuchAlgorithmException,
        InvalidKeySpecException, IOException {

    final InputStream inputStream = getClass().getClassLoader()
                    .getResourceAsStream("privatekey");
    byte[] privKeyBytes = null;
    try {
        privKeyBytes = IOUtils.toByteArray(inputStream);
    } catch (final IOException exception) {
        LOGGER.error("", exception);
        IOUtils.closeQuietly(inputStream);
    }

    LOGGER.debug("privKeyBytes: {}", privKeyBytes);

    String BEGIN = "-----BEGIN RSA PRIVATE KEY-----";
    String END = "-----END RSA PRIVATE KEY-----";
    String str = new String(privKeyBytes);
    if (str.contains(BEGIN) && str.contains(END)) {
        str = str.substring(BEGIN.length(), str.lastIndexOf(END));
    }

    KeyFactory fac = KeyFactory.getInstance("RSA");
    EncodedKeySpec privKeySpec =
            new PKCS8EncodedKeySpec(Base64.decode(str.getBytes()));
    return fac.generatePrivate(privKeySpec);
}

我得到了例外

java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : algid parse error, not a sequence
    at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:200) ~[na:1.6.0_23]
    at java.security.KeyFactory.generatePrivate(KeyFactory.java:342) ~[na:1.6.0_23]

在 fac.generatePrivate(privKeySpec) 调用中。

这个错误是什么意思?

谢谢

德米特里

java security rsa
4个回答
162
投票

我遇到了同样的问题,密钥的格式不是实际的问题。
要摆脱这个异常,我所要做的就是打电话

java.security.Security.addProvider(
         new org.bouncycastle.jce.provider.BouncyCastleProvider()
);


一切顺利


108
投票

这意味着您的密钥不是 PKCS#8 格式。最简单的方法是使用

openssl pkcs8 -topk8 <...other options...>
命令转换一次密钥。或者,您可以使用 Bouncycastle 轻量级 API
PEMReader 类。


90
投票

您必须使用您的私钥制作 PCKS8 文件!

private.pem => 私钥文件名称

openssl genrsa -out private.pem 1024

public_key.pem => 公钥文件名称

openssl rsa -in private.pem -pubout -outform PEM -out public_key.pem

private_key.pem => PCKS8 格式的私钥名称!你可以在java中读取这种格式

openssl pkcs8 -topk8 -inform PEM -in private.pem -out private_key.pem -nocrypt

0
投票

我在 Spring Boot REST API 中遇到了类似的问题。我从 Spring Boot 代码调用 DocuSign API。在本地环境中运行良好,但是在 Tomcat 9 服务器中部署 war 文件后,它开始抛出错误:

java.security.InvalidKeyException: IOException : algid parse error, not a sequence

然后我重新启动了 Tomcat 服务,它开始按预期工作。也许 Tomcat 无法将

BouncyCastleProvider
加载到类路径中。

我希望这对将来访问此问题的人有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.