Bouncy Castle : PEMReader => PEMParser

后端 未结 2 1007
再見小時候
再見小時候 2020-11-29 08:28

With a PEM certificate like

-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-256-CBC,B9846B5D1803E.....

using BC 1.46,

相关标签:
2条回答
  • 2020-11-29 09:03

    For Version 1.55 of bcpkix-jdk15on the decryption code changes to this:

    kp = ((PEMEncryptedKeyPair) object).decryptKeyPair(decryptorProvider);
    

    I didn't check if this is a mistake in the above answer or just an API difference between the versions.

    0 讨论(0)
  • 2020-11-29 09:14

    I just needed to solve the same problem and found no answer. So I spent some time studying BC API and found a solution which works for me. I needed to read the private key from file so there is privateKeyFileName parameter instead pemString parameter in the myFunc method.

    Using BC 1.48 and PEMParser:

    int myFunc(String privateKeyFileName, char [] password) {
         File privateKeyFile = new File(privateKeyFileName); // private key file in PEM format
         PEMParser pemParser = new PEMParser(new FileReader(privateKeyFile));
         Object object = pemParser.readObject();
         PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(password);
         JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
         KeyPair kp;
         if (object instanceof PEMEncryptedKeyPair) {
            System.out.println("Encrypted key - we will use provided password");
            kp = converter.getKeyPair(((PEMEncryptedKeyPair) object).decryptKeyPair(decProv));
        } else {
            System.out.println("Unencrypted key - no password needed");
            kp = converter.getKeyPair((PEMKeyPair) object);
        }
    }
    
    0 讨论(0)
提交回复
热议问题