我想将pem文件转换为pk8。我可以在终端上使用openssl来做到这一点;
openssl pkcs8 -topk8 -inform PEM -outform DER -in client-key.pem -out client-key.pk8 -nocrypt
但是我需要在Java上以编程方式执行此操作。看起来好像有一个用于加密的软件包,其中包含Bounty Castle的openssl实现,但是我不知道该怎么做。有办法吗?
答案 0 :(得分:0)
Bouncy Castle的测试代码在函数ParserTest.doOpenSslRsaTest中包含如何读取RSA私钥的示例。这是对该示例的略微修改,它可以将加密和未加密的密钥作为输入进行处理(在后一种情况下,将不使用密码短语):
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;
}
在AllTests.encryptedTestNew中可以找到作者侧的示例,大致如下:
private static void pemRSAP8WritePrivateKey(PrivateKey key, String pemfilename, String passphrase)
throws IOException, OperatorCreationException
{
FileWriter writer = new FileWriter(pemfilename);
JcaPEMWriter pemwriter = new JcaPEMWriter(writer);
JceOpenSSLPKCS8EncryptorBuilder encryptorbuilder =
new JceOpenSSLPKCS8EncryptorBuilder(PKCS8Generator.AES_128_CBC).
setProvider("BC").
setPasssword(passphrase.toCharArray());
OutputEncryptor encryptor = encryptorbuilder.build();
PKCS8Generator pkcs8 = new JcaPKCS8Generator(key, encryptor);
pemwriter.writeObject(pkcs8);
pemwriter.close();
writer.close();
}
将其放在一起进行转换:
Security.addProvider(new BouncyCastleProvider());
try {
KeyPair kp = pemRSAP1ReadKeyPair("rsakey_enc.pem", "changeit");
PrivateKey privkey = kp.getPrivate();
if (!(privkey instanceof RSAPrivateKey)) {
System.out.println("PEM input file does not contain an RSA private key");
} else {
pemRSAP8WritePrivateKey(privkey, "rsakey.p8", "abracadabra");
}
} catch (Exception e) {
System.out.println("Caught exception: " + e.getMessage());
}