1

我正在尝试从 pem 文件加载私钥。我受到限制,因为我不允许使用任何外部库,例如 Bouncy Castle。

我的一段代码:

    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    File privKeyFile = new File(privateKeyPath);
    byte[] privKeyBytes = new byte[(int)privKeyFile.length()];
    KeySpec ks = new PKCS8EncodedKeySpec(privKeyBytes);
    PrivateKey privKey = (PrivateKey) keyFactory.generatePrivate(ks);

最后一行出现异常。我还尝试使用 openssl 将 pem 文件转换为 PKCS#8:

openssl pkcs8 -topk8 -inform PEM -output DER -in mycert.pem -nocrypt > mynewcert.pk8

但我仍然收到“无效的密钥格式”异常

我认为这可能是我的 pem 文件有问题,但是在使用 openssl 生成新文件后:

openssl req -config "C:\Program Files\GnuWin32\bin\openssl.conf" -x509 -nodes -days 365 -newkey rsa:1024 -keyout mycert.pem -out mycert.pem

我仍然得到相同的结果。

这是我的 pem 文件的内容:

-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQCq4Do244NSSP+acHy3SRYMateNfM2LWnfvLmoDPkWrA2u+ZygT
5f1amkZED7o9UMmAK2zif8xQgIyl5olJ++OZfFJdFqCJ/yw4NGyrApYAkmi91Dms
e0JbjPZ4yVKaj1tnECJb4xfdHRk818IP+X4HTWmZG3LeZ3Z3o63dL+OscwIDAQAB
AoGAUBFzlca0ATmtc7uj5Op9R2JFEMpbMiI5Mr1H9a8XTBP1R6nksLZDKlJB/KB1
/0c8tC8k/Vku7sXdodtNl3pNYhks9vi23lGgf47qwx05kst7hPJB4D0Kaiigy61S
yEfl2FLXpcahmVpAt7VRNfEOd0Ogvvx3NJJsncDVbiCHCoECQQDYXpsQQHNPamCj
nl9NHGncMAw5o63AoghxlbN41ZChbScyED5qkiU3IOfx1HG2zISjlocEMADGLUg/
N3E6vAJBAkEAyix114sSBb1QWv4DN2QH5L5r4Xia+jGO7ZIApJs8eaV0dJ/6OPaP
E5xdnh6s3zIv6HBBUpsY1m/KBOB35UXZswJAD5wDo9CCgSAziJpMVcvO90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YLXXZEnZ1xxTQkL0duqIwluHLCGFq3xi156EM8I7mKBEIwBTFRiX5Lh22MAsq
2mwtDnQqKj4yZoqmEKhFZlykl6uZHU+WxZc1tHOfYBmc
-----END CERTIFICATE-----

这是我的堆栈跟踪:

    java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format
    at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(Unknown Source)
    at java.security.KeyFactory.generatePrivate(Unknown Source)
    at Crypto.loadKeyPair(Crypto.java:165)
    at Crypto.signXML(Crypto.java:202)
    at Main.main(Main.java:12)
Caused by: java.security.InvalidKeyException: invalid key format
    at sun.security.pkcs.PKCS8Key.decode(Unknown Source)
    at sun.security.pkcs.PKCS8Key.decode(Unknown Source)
    at sun.security.rsa.RSAPrivateCrtKeyImpl.<init>(Unknown Source)
    at sun.security.rsa.RSAPrivateCrtKeyImpl.newKey(Unknown Source)
    at sun.security.rsa.RSAKeyFactory.generatePrivate(Unknown Source)
    ... 5 more

经过一番搜索,我找不到任何进一步的信息。现在我被卡住了,不知道下一步该怎么做。请给点灯,我真的需要一些帮助。谢谢!

4

1 回答 1

0
KeySpec ks = new PKCS8EncodedKeySpec(privKeyBytes);
PrivateKey privKey = (PrivateKey) keyFactory.generatePrivate(ks);

如果你想在上面使用,那么你的私钥文件应该是 PKCS#8 类型。但您的文件内容是 PKCS#1。所以,使用 bountyCastle 库或其他方式。

附言。下面的内容请注意,您的私钥文件是 PKCS#1 类型

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

PKCS#8 看起来像

-----BEGIN PRIVATE KEY-----
-----END PRIVATE KEY-----
于 2019-11-11T02:52:14.847 回答