2013-08-30 25 views
2

我有.p12文件,我使用openssl解压私钥,我有一个提取密码。从pkcs12提取私钥并进行文本加密

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 

上述代码正常工作。

  • 如何正确提取p12文件的私钥?
  • 或者是否有任何方法使用p12文件加密/解密文本 而不通过命令行解压?

我知道这只是PKCS#12只是存储密钥的古董文件。

回答

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)); 

要找到你感兴趣,我建议使用密钥工具条目的别名(自带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 ...] 
+0

嗨罗布谢谢你的回答。我之前尝试过这种方式。我的密钥库没有任何别名。有什么办法可以找出办法。我有一个与p12文件一起的证书。 – user2662294

+0

添加了一些关于列出密钥库内容的细节,因此也许您可以找到您感兴趣的项目上的别名。 – Rob

+0

它向我显示了这个:'Keystore type:PKCS12 Keystore provider:SunJSSE Your keystore包含0条目,顺便说一句,我有* .cer,文件以及我的.p12文件。有什么关系吗?谢谢! – user2662294