Read a Private Encrypted Key in Java

I have the following piece of code:

    PEMParser pemParser;
    File telexuskeys = new File(locationKey);
    if(telexuskeys.exists())
        pemParser = new PEMParser(new FileReader(telexuskeys));
    else{
        usage(ops);
        throw new FileNotFoundException("The key file (company's certificate) doesn't exist!");
    }

    System.out.println("Loading company's certificate");

    Object object = pemParser.readObject();
    Object object2 = pemParser.readObject();

    PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(passwordPem.toCharArray());
    JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC"); 

    byte[] keyBytes = PrivateKeyInfo.getInstance(object2).getEncoded();
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA", "BC");        
    PrivateKey pk = kf.generatePrivate(spec);

My pem file just have the certificate and the private key. I used to be able to read the file and obtain the private key but now the file is protected (encrypted) with a password. What is the instruction that I'm still missing. I know I need to use the PEMDecryptorProvider and the JcaPEMKeyConverter objects in order to obtain it but I haven't found the correct combination.

Upvotes: 7

Views: 7353

Answers (2)

NDAclan
NDAclan

Reputation: 53

My key was generated with the command below.

openssl req -new -newkey rsa:2048 -keyout key.pem -pubkey -out pubreq.p10 -subj "/CN=MyKey"

Apparently the output was a PKCS8EncryptedPrivateKeyInfo and after reading stuff here and there, this is what I came up with:

try {
    File file = ResourceUtils.getFile("classpath:" + decryptionKeystore);

    try (FileReader fileReader = new FileReader(file);
        PEMParser keyReader = new PEMParser(fileReader)) {
        Object keyPair = keyReader.readObject();
        PrivateKeyInfo keyInfo;

        if (keyPair instanceof PEMEncryptedKeyPair) {
            PEMDecryptorProvider decryptionProv = new JcePEMDecryptorProviderBuilder().build(passphrase);
            PEMKeyPair decryptedKeyPair = ((PEMEncryptedKeyPair) keyPair).decryptKeyPair(decryptionProv);
            keyInfo = decryptedKeyPair.getPrivateKeyInfo();
        } else if (keyPair instanceof PKCS8EncryptedPrivateKeyInfo) {
            InputDecryptorProvider decryptorProvider = new JceOpenSSLPKCS8DecryptorProviderBuilder().build(passphrase);
            keyInfo = ((PKCS8EncryptedPrivateKeyInfo) keyPair).decryptPrivateKeyInfo(decryptorProvider);
        } else {
            keyInfo = ((PEMKeyPair) keyPair).getPrivateKeyInfo();
        }

        return new JcaPEMKeyConverter().getPrivateKey(keyInfo);
    } catch (Exception e) {
        LOGGER.error("Exception while getting private key", e);
    }
} catch (FileNotFoundException e) {
    LOGGER.debug("Decryption keystore file not found");
}

Upvotes: 0

lockner
lockner

Reputation: 201

The following code does the work for me. (Using the bcpkix and bcprov libs from Bouncy Castle).

private PrivateKey readPrivateKey(String privateKeyPath, String keyPassword) throws IOException {

    FileReader fileReader = new FileReader(privateKeyPath);
    PEMParser keyReader = new PEMParser(fileReader);

    JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
    PEMDecryptorProvider decryptionProv = new JcePEMDecryptorProviderBuilder().build(keyPassword.toCharArray());

    Object keyPair = keyReader.readObject();
    PrivateKeyInfo keyInfo;

    if (keyPair instanceof PEMEncryptedKeyPair) {
        PEMKeyPair decryptedKeyPair = ((PEMEncryptedKeyPair) keyPair).decryptKeyPair(decryptionProv);
        keyInfo = decryptedKeyPair.getPrivateKeyInfo();
    } else {
        keyInfo = ((PEMKeyPair) keyPair).getPrivateKeyInfo();
    }

    keyReader.close();
    return converter.getPrivateKey(keyInfo);

Upvotes: 9

Related Questions