.pem
我想从Java 中的字符串(文件)生成私钥。
private static final String test = "-----BEGIN RSA PRIVATE KEY-----\n" +
"MIIEpAIBAAKCAQEAvcCH8WsT1xyrZqq684VPJzOF3hN5DNbowZ96Ie//PN0BtRW2\n" +
// and so on
"-----END RSA PRIVATE KEY-----";
try {
String privKeyPEM = test.replace("-----BEGIN RSA PRIVATE KEY-----\n", "");
privKeyPEM = privKeyPEM.replace("-----END RSA PRIVATE KEY-----", "");
byte [] encoded = Base64.decode(privKeyPEM);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey privKey = kf.generatePrivate(keySpec);
}
catch (Exception e) {
e.printStackTrace();
}
最后一行(generatePrivate 函数)抛出此异常:
java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : algid parse error, not a sequence
at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(Unknown Source)
at java.security.KeyFactory.generatePrivate(Unknown Source)
at Test.main(Test.java:52)
Caused by: java.security.InvalidKeyException: IOException : algid parse error, not a sequence
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)
... 3 more
如果我将私钥更改为文件中的值,.der
它可以正常工作,但我需要从文件中生成私钥.pem
文件。
我附上了打印为字符串的字节截图(一次用 \n 硬编码,一次用 \n 硬编码),一次来自文件。
奇怪的是文件的输出与字符串的输出不同。
如果我尝试.der
使用 Base64 对文件进行编码,则结果与.pem
文件中的字符串不同。为什么呢?