【问题标题】:InvalidKeySpecExeption when loadding the RSA private key from file从文件加载 RSA 私钥时出现 InvalidKeySpecException
【发布时间】:2013-04-20 11:24:23
【问题描述】:

我正在尝试从 java 中的文件加载私钥。此密钥由 ssh-agent 生成。我实际上正在使用下面的代码:

     public PrivateKey getPrivateKeyFromFile() {
    try {
        //String privateKey = readFileAsString(System.getProperty("user.dir")+"/clefs/"+privateKeyName);
        //byte[] encodePrivateKey = privateKey.getBytes();
        File filePrivateKey = new File(System.getProperty("user.dir")+"/clefs/"+privateKeyName);
        FileInputStream fis = new FileInputStream(System.getProperty("user.dir")+"/clefs/"+privateKeyName);
        byte[] encodePrivateKey = new byte[(int) filePrivateKey.length()];
        fis.read(encodePrivateKey);
        fis.close();

        java.security.KeyFactory keyFactory = java.security.KeyFactory.getInstance("RSA");
        PKCS8EncodedKeySpec privatekeySpec = new PKCS8EncodedKeySpec(encodePrivateKey);
        PrivateKey prikey = (PrivateKey) keyFactory.generatePrivate(privatekeySpec);
        return prikey;

    } catch (NoSuchAlgorithmException ne) {
        ne.printStackTrace();
    } catch (InvalidKeySpecException is) {
        is.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;

}

但它产生了这个异常:

 java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format
at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:217)
at java.security.KeyFactory.generatePrivate(KeyFactory.java:372)
at com.nguyenkim.cea.signature.SignChallenge.getPrivateKeyFromFile(SignChallenge.java:53)
at com.nguyenkim.cea.signature.SignChallenge.main(SignChallenge.java:128)
 Caused by: java.security.InvalidKeyException: invalid key format
at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:341)
at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:367)
at sun.security.rsa.RSAPrivateCrtKeyImpl.<init>(RSAPrivateCrtKeyImpl.java:91)
at sun.security.rsa.RSAPrivateCrtKeyImpl.newKey(RSAPrivateCrtKeyImpl.java:75)
at sun.security.rsa.RSAKeyFactory.generatePrivate(RSAKeyFactory.java:316)
at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:213)
... 3 more

这是私钥:

   -----BEGIN RSA PRIVATE KEY-----
  MIIEowIBAAKCAQEAszReSzBumVb9GR/f3ClgykWE4UsONan1Ywk/H4+Wbi4HpcwB
  8Lm9B+zJ94WdRtD8iQYmbUZFoHwFqTjRPtmQfFXcmxfuI7v64bg0csIw8hz1Af2r
  xo7HBUoVcrTG5k3YrIkjeni/vD9uK6OZ1/lb+/TIvoEp9za577GJxv1omQ6GX7kv
  baMe2GkfpJmrXnA706OEdyi3Ibdcng/V4lbJ9cm+TIBU2jLBqwEukwpL5VNghuQi
  3YfpGhnPDBEnh4h5euFs4DGs4FnCgb+00yCuEgJSPvO5HsTnGbwTtEUnkxjtg8vD
  plD7WenPsyiZqib/rLkNcpfEHKVC6G3QjEuO8QIDAQABAoIBAGliRoFY/fFW4og/
  .............................
  -----END RSA PRIVATE KEY-----

有什么建议吗? 谢谢。

【问题讨论】:

标签: java


【解决方案1】:

你确定它的 RSA 吗?您还确定密钥格式正确吗?

如果两个问题的答案都是肯定的,您可以尝试使用bouncycastle lib

编辑:尝试从键中删除这些行:

-----BEGIN RSA PRIVATE KEY-----
.............................
-----END RSA PRIVATE KEY-----

更新:确保您的私钥是 PKCS8 格式,否则您需要像 here 那样转换它

【讨论】:

  • 是的,密钥是由 ssh-agent 使用命令生成的:ssh-keygen -t rsa -C "my_email@example.com"。我很确定它的格式正确(请参阅上面编辑的问题)。实际上,我知道一种使用充气城堡生成一对密钥的方法,但是当您总是必须加载从文件生成的密钥时,它不会有什么不同。
  • 我删除了这两行,结果没有改变。问题出在这一行: PrivateKey prikey = (PrivateKey) keyFactory.generatePrivate(privatekeySpec);我怀疑 PKCS8 编码存在错误
  • 或者使用 Bouncy 中的 PEM 实用程序来剥离行并执行 base64 解码。不需要自己做所有这些。
【解决方案2】:

您可以使用 BouncyCastle 的 Pemreader,而不是从私钥文件中删除页眉和页脚。

 private PrivateKey getPrivateKeyFromFile(String keyFile) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    final InputStream inputStream = getClass().getClassLoader().getResourceAsStream(keyFile);
    String privateKeySTr = IOUtils.toString(inputStream, String.valueOf(StandardCharsets.UTF_8));

    PemObject pem = new PemReader(new StringReader(privateKeySTr)).readPemObject();
    byte[] der = pem.getContent();
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(der);
    RSAPrivateKey privKey = (RSAPrivateKey) keyFactory.generatePrivate(ks);
    return privKey;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-22
    • 2019-06-07
    • 1970-01-01
    • 2012-07-09
    • 2010-12-17
    • 1970-01-01
    • 2015-07-22
    相关资源
    最近更新 更多