use of org.bouncycastle.openssl.jcajce.JcaPKCS8Generator in project graylog2-server by Graylog2.
the class KeyUtil method generatePKCS8FromPrivateKey.
/**
* Build a password-encrypted PKCS8 private key and write it to a PEM file in the temp directory.
* Caller is responsible for ensuring that the temp directory is writable. The file will be deleted
* when the VM exits.
* @param tmpDir path to directory in which to create the
* @param password to protect the key
* @param key encrypt this key
* @return PEM file
* @throws GeneralSecurityException
*/
public static File generatePKCS8FromPrivateKey(Path tmpDir, char[] password, PrivateKey key) throws GeneralSecurityException {
try {
JceOpenSSLPKCS8EncryptorBuilder encryptorBuilder = new JceOpenSSLPKCS8EncryptorBuilder(PKCS8Generator.AES_256_CBC).setRandom(new SecureRandom()).setPasssword(password);
OutputEncryptor encryptor = encryptorBuilder.build();
// construct object to create the PKCS8 object from the private key and encryptor
PemObject pemObj = new JcaPKCS8Generator(key, encryptor).generate();
StringWriter stringWriter = new StringWriter();
try (JcaPEMWriter pemWriter = new JcaPEMWriter(stringWriter)) {
pemWriter.writeObject(pemObj);
}
// write PKCS8 to file
String pkcs8Key = stringWriter.toString();
File tmpFile = Files.createTempFile(tmpDir, "pkcs8", ".key").toFile();
try (FileOutputStream fos = new FileOutputStream(tmpFile)) {
fos.write(pkcs8Key.getBytes(StandardCharsets.UTF_8));
tmpFile.deleteOnExit();
}
return tmpFile;
} catch (IOException | OperatorCreationException e) {
throw new GeneralSecurityException(e);
}
}
Aggregations