Algid 解析错误,不是序列 [英] Algid parse error, not a sequence

查看:40
本文介绍了Algid 解析错误,不是序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When trying to read a RSA private key from a file using the method

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) 调用中.

at the fac.generatePrivate(privKeySpec) call.

这个错误是什么意思?

谢谢

德米特里

推荐答案

这意味着您的密钥不是 PKCS#8 格式.最简单的方法是使用 openssl pkcs8 -topk8 <...other options...> 命令将密钥转换一次.或者,您可以使用 PEMReader<Bouncycastle 轻量级 API 的/a> 类.

It means your key is not in PKCS#8 format. The easiest thing to do is to use the openssl pkcs8 -topk8 <...other options...> command to convert the key once. Alternatively you can use the PEMReader class of the Bouncycastle lightweight API.

这篇关于Algid 解析错误,不是序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆