当用户提供密钥库时,密钥库通常包含密钥对(RSA加密的私钥,x.509证书)和CA证书。
我想提取密钥库的内容并将它们写入另一个文件中。
我能够毫无问题地读取证书的内容,但是当尝试读取密钥并写入文件时,内容是未加密的形式。
如何从自身加密写入私钥文件的内容?
我已经获取了密钥和证书,如下所示:
key = (PrivateKey)keyStore.getKey(keyAlias, password.toCharArray());
cert = keyStore.getCertificate(keyAlias);
我也尝试过使用Bouncycastle。
使用Java库:
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(key.getEncoded());
byte[] privatekey = encoder.encode(pkcs8EncodedKeySpec.getEncoded());
使用bouncycastle:
JceOpenSSLPKCS8EncryptorBuilder encryptorBuilder = new JceOpenSSLPKCS8EncryptorBuilder(PKCS8Generator.PBE_SHA1_RC2_128);
encryptorBuilder.setRandom(new SecureRandom());
encryptorBuilder.setPasssword("abcde".toCharArray()); // password
OutputEncryptor encryptor = encryptorBuilder.build();
JcaPKCS8Generator gen2 = new JcaPKCS8Generator(key, encryptor);
PemObject obj2 = gen2.generate();
StringWriter sw2 = new StringWriter();
try (JcaPEMWriter pw = new JcaPEMWriter(sw2)) {
pw.writeObject(obj2);
}
String pkcs8Key2 = sw2.toString();
FileOutputStream fos2 = new FileOutputStream(privateKeyLocation);
fos2.write(pkcs8Key2.getBytes());
fos2.flush();
fos2.close();
当使用纯Java库时,内容将被解密,我可能想附加header和footer标签。
当使用充气城堡时,我在
-----BEGIN ENCRYPTED PRIVATE KEY-----
和-----END ENCRYPTED PRIVATE KEY-----
中得到了一些数据,但是内容与原始文件不同。我也尝试过使用其他PKCS8Gnerator.algorithms无效。
最佳答案
使用库org.apache.commons.codec.binary.Base64
并执行以下操作。
String encodedValue = Base64.encodeBase64String(certificate.getEncoded());
并解码,像上面那样传递上面的字符串
bytes = Base64.decode(encodedValue, Base64.DEFAULT);
关于java - 如何提取PKCS12 keystore (包含pkcs#8的 key 对和证书),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57852885/