Further to Julien Kronegg's answer, if you are getting this error because your file has a PKCS#1 format, you can use the following steps to convert it to a PKCS#8 file.
First, save your PKCS#1 key file to a file called priv1.pem
:
-----BEGIN RSA PRIVATE KEY-----
[...]
-----END RSA PRIVATE KEY-----
Then, execute the following command:
openssl pkcs8 -topk8 -inform PEM -outform PEM -in priv1.pem -out priv8.pem -nocrypt
This produces a file called priv8.pem
, which is your key file in PKCS#8 format:
-----BEGIN PRIVATE KEY-----
[...]
-----END PRIVATE KEY-----
I use this from Java as follows:
String PRIVATE_RSA_KEY_PKCS8 =
"-----BEGIN PRIVATE KEY-----
" +
"MDSTofml23d....
" +
[...] +
"-----END PRIVATE KEY-----
";
String key = PRIVATE_RSA_KEY_PKCS8
.replace("-----BEGIN PRIVATE KEY-----
", "")
.replace("
-----END PRIVATE KEY-----
", "");
PKCS8EncodedKeySpec keySpec =
new PKCS8EncodedKeySpec(DatatypeConverter.parseBase64Binary(key));
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] bytes = parseBase64Binary(encryptedNodeIdentifier);
byte[] decryptedData = cipher.doFinal(bytes);
return new String(decryptedData);
} catch (GeneralSecurityException e) {
return "";
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…