从.pem文件加载私钥时获取无效的密钥格式异常

时间:2013-03-06 03:00:35

标签: java security pem

我正在尝试从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/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gdQAdEjZJgT7JjCEd1QnvKsBRXy
tDDYLXXZEnZ1xxTQkL0duqIwluHLCGFq3xi156EM8I7mKBEIwBTFRiX5Lh22MAsq
2mwtDnQqKj4yZoqmEKhFZlykl6uZHU+WxZc1tHOfYBmc
-----END CERTIFICATE-----

这是我的stacktrace:

    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

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

1 个答案:

答案 0 :(得分:0)

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

如果要在上面使用,则您的私钥文件应为PKCS#8类型。但您的文件内容为PKCS#1。因此,请使用bountyCastle库或其他方式。

ps。在内容下方,请注意您的私钥文件是PKCS#1类型

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

PKCS#8看起来像

-----BEGIN PRIVATE KEY-----
-----END PRIVATE KEY-----