Java 从pkcs12和文本加密中提取私钥

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18539274/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 08:53:29  来源:igfitidea点击:

Extracting Private key from pkcs12 and text encryption

javaencryptionrsaencryption-asymmetricpkcs#12

提问by user2662294

I have .p12 file, I am extracting the private key using openssl, I have a password for extracting it.

我有 .p12 文件,我正在使用 openssl 提取私钥,我有一个密码来提取它。

openssl pkcs12 -in my.p12 -nocerts -out privateKey.pem

And after I get my private key, I'm trying to use that key for encryption:

在我获得我的私钥后,我尝试使用该密钥进行加密:

 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();returns null. But when I create a private key by myself by this command:

r.readObject(); 返回空值。但是当我通过这个命令自己创建一个私钥时:

openssl genrsa -out privkey.pem 2048

The above code works fine.

上面的代码工作正常。

  • How can I extract private key from p12 file properly?
  • Or is there any way to use p12 file for encrypt/decrypt the text without extracting through command line?
  • 如何从 p12 文件中正确提取私钥?
  • 或者有什么方法可以使用 p12 文件加密/解密文本而不通过命令行提取?

I know it is just PKCS#12is just archaive file which stores keys.

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

采纳答案by Rob

I don't know what is wrong with your code, but I have code that reads stuff from a key store. I read the file into a KeyStore instance and then access the key or entry as appropriate. Here are some of the relevant calls:

我不知道你的代码有什么问题,但我有从密钥库读取内容的代码。我将文件读入 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));

To find the alias of the entry you are interested in, I suggest using keytool (comes with JDK):

要查找您感兴趣的条目的别名,我建议使用 keytool(JDK 附带):

keytool -list -v -keystore keystore.pkcs12 -storetype pkcs12

You will be prompted for the keystore password and then get information like this:

系统将提示您输入密钥库密码,然后获取如下信息:

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 ...]