以编程方式将PEM文件转换为PKCS8 [英] Converting PEM file to PKCS8 programmatically
问题描述
我想将pem文件转换为pk8.我可以在终端上使用openssl来做到这一点;
I want to convert pem file to pk8. I can do this with openssl on terminal as ;
openssl pkcs8 -topk8 -inform PEM -outform DER -in client-key.pem -out client-key.pk8 -nocrypt
但是我需要在Java上以编程方式执行此操作.看起来好像有一个用于加密的软件包,其中包含openssl实现,例如 Bounty Castle ,但我不知道如何执行此转换过程.有办法吗?
But I need to do this programmatically on java. Its look like there is a package for cryptography which contains openssl implementation as Bounty Castle but I couldn't figure out how can do this converting process. Is there a way for doing that ?
推荐答案
The test code of Bouncy Castle contains an example of how to read an RSA Private key, in the function ParserTest.doOpenSslRsaTest. Here is a slight modification of that example, it can handle both encrypted and non-encrypted keys as input (and in the latter case, the passphrase will not be used):
private static KeyPair pemRSAP1ReadKeyPair(String pemfilename, String passphrase)
throws FileNotFoundException, IOException
{
KeyPair result = null;
FileReader reader = new FileReader(pemfilename);
PEMParser parser = new PEMParser(reader);
Object pemobj = parser.readObject();
parser.close();
reader.close();
if (pemobj == null ||
!((pemobj instanceof PEMKeyPair) || (pemobj instanceof PEMEncryptedKeyPair))) {
System.out.println("Unable to read key pair");
} else {
PEMKeyPair pemkp;
if (pemobj instanceof PEMEncryptedKeyPair) {
PEMEncryptedKeyPair kp = (PEMEncryptedKeyPair)pemobj;
PEMDecryptorProvider decprov = new BcPEMDecryptorProvider(passphrase.toCharArray());
pemkp = kp.decryptKeyPair(decprov);
} else {
pemkp = (PEMKeyPair)pemobj;
}
result = new JcaPEMKeyConverter().setProvider("BC").getKeyPair(pemkp);
}
return result;
}