Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

java - Algid parse error, not a sequence

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

I get the exception

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]

at the fac.generatePrivate(privKeySpec) call.

What does this error mean?

Thanks

Dmitri

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I was having this same issue, and the format of the key was NOT the actual problem.
All I had to do to get rid of that exception was to call

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


and everything worked


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...