public static String pemEncodePrivateKey(PrivateKey key, char[] password)
    throws IOException, OperatorCreationException {
    StringWriter stringWriter = new StringWriter();
    JcaPEMWriter pemWriter = new JcaPEMWriter(stringWriter);
    OutputEncryptor encryptor = null;
    if (password != null && password.length > 0) {
      encryptor =
        new JceOpenSSLPKCS8EncryptorBuilder(PKCSObjectIdentifiers.pbeWithSHAAnd3_KeyTripleDES_CBC)
          .setProvider(BouncyCastleProvider.PROVIDER_NAME).setRandom(PRNG).setPasssword(password)
          .build();
    }
    pemWriter.writeObject(new JcaPKCS8Generator(key, encryptor));
    pemWriter.close();
    return stringWriter.toString();
  }
PEM-encodes the given private key (compatible with OpenSSL), optionally protecting it with a
password, and returns the result as a String.
@param key      the private key.
@param password an optional key password. If empty or null, the private key will not be
                encrypted.
@return a String containing the PEM encoding of the private key.
@throws IOException               if converting the key to PEM format fails.
@throws OperatorCreationException if constructing the encryptor from the given password fails.
hbase-common/src/test/java/org/apache/hadoop/hbase/io/crypto/tls/X509TestHelpers.java