Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 596
Manuel Gustavo Guillen Avatar asked Jul 15 '13 15:07

Manuel Gustavo Guillen


1 Answers

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);
like image 137
lockner Avatar answered Oct 06 '22 15:10

lockner