我想在Java中从字符串(一个.pem
文件)生成私钥。
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,以及一次从文件中读取)。 更大的图片 文件的输出结果与字符串的输出结果不同,这很奇怪。
如果我试图使用Base64对一个.der文件进行编码,结果与.pem文件中的字符串不同。为什么会这样?