我有 .p12 文件,我正在使用 openssl 提取私钥,我有一个用于提取它的密码。
openssl pkcs12 -in my.p12 -nocerts -out privateKey.pem
获得私钥后,我尝试使用该 key 进行加密:
public static void main(String[] args) throws Exception {
Security.addProvider(new BouncyCastleProvider());
KeyPair keyPair = readKeyPair(privateKey, "testpassword".toCharArray());
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
byte[] textEncrypted = cipher.doFinal("hello world".getBytes());
System.out.println("encrypted: "+new String(textEncrypted));
cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
byte[] textDecrypted = cipher.doFinal(textEncrypted);
System.out.println("decrypted: "+new String(textDecrypted));
}
private static KeyPair readKeyPair(File privateKey, char[] keyPassword) throws IOException {
FileReader fileReader = new FileReader(privateKey);
PEMReader r = new PEMReader(fileReader, new DefaultPasswordFinder(keyPassword));
try {
return (KeyPair) r.readObject(); // this returns null
} catch (IOException ex) {
throw new IOException("The private key could not be decrypted", ex);
} finally {
r.close();
fileReader.close();
}
}
r.readObject(); 返回 null。但是当我通过这个命令自己创建私钥时:
openssl genrsa -out privkey.pem 2048
上面的代码工作正常。
- 如何从 p12 文件中正确提取私钥?
- 或者有什么方法可以使用 p12 文件来加密/解密文本 不通过命令行提取?
我知道这只是 PKCS#12只是存储 key 的存档文件。
最佳答案
我不知道你的代码有什么问题,但我有从 key 存储中读取内容的代码。我将文件读入 KeyStore 实例,然后根据需要访问 key 或条目。以下是一些相关的调用:
char[] password;
String alias;
java.security.KeyStore keyStore = KeyStore.getInstance("PKCS12", "BC");
keyStore.load(inputStream, password);
java.security.PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, password);
java.security.keystore.PrivateKeyEntry privateKeyEntry = (PrivateKeyEntry) keyStore.getEntry(alias, new KeyStore.PasswordProtection(password));
要查找您感兴趣的条目的别名,我建议使用 keytool(JDK 附带):
keytool -list -v -keystore keystore.pkcs12 -storetype pkcs12
系统将提示您输入 keystore 密码,然后获取如下信息:
Keystore type: PKCS12
Keystore provider: SunJSSE
Your keystore contains 1 entry
Alias name: thealias
Creation date: Aug 30, 2013
Entry type: PrivateKeyEntry
Certificate chain length: 2
[... lots of info about the certificates deleted ...]
关于java - 从 pkcs12 和文本加密中提取私钥,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18539274/