我有.p12文件,我使用openssl提取私钥,我有一个提取密码。
openssl pkcs12 -in my.p12 -nocerts -out privateKey.pem
在我获得私钥后,我正在尝试使用该密钥进行加密:
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
上面的代码工作正常。
我知道它只是PKCS#12只是存储密钥的古老文件。
答案 0 :(得分:2)
我不知道您的代码有什么问题,但我有从密钥库中读取内容的代码。我将文件读入KeyStore实例,然后根据需要访问密钥或条目。以下是一些相关的电话:
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 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 ...]