Search code examples
javaencryptionrsaprivate-key

How to decrypt a password protected RSA key in java?


I'm writing a code to consume a private key to encrypt and decrypt a message. The problem is that the key i use is protected by a passphrase. So i have to decrypt the key itself before use it to encrypt and decrypt. This is the header of the key content:

-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,E51B4CCF38530A32

b9gvBvJNyUxA/2AH5mb+7dNcIns05EIXlbiM47xSUiQZgOdbP5ZHy5WL6S+uxU7s
.
.
.
-----END RSA PRIVATE KEY-----

How can I achieve that in Java?


Solution

  • This is an encrypted private RSA key in PKCS#1 format, PEM encoded, which is most convenient to import using BouncyCastle:

    import java.io.FileReader;
    import java.security.PrivateKey;
    import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
    import org.bouncycastle.openssl.PEMEncryptedKeyPair;
    import org.bouncycastle.openssl.PEMKeyPair;
    import org.bouncycastle.openssl.PEMParser;
    import org.bouncycastle.openssl.bc.BcPEMDecryptorProvider;
    import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
    
    ...
    
    String path = "...";
    String password = "...";
    try (PEMParser pemParser = new PEMParser(new FileReader(path))){
    
        PEMEncryptedKeyPair encKeyPair = (PEMEncryptedKeyPair)pemParser.readObject();
        PEMKeyPair keyPair = encKeyPair.decryptKeyPair(new BcPEMDecryptorProvider(password.toCharArray()));
    
        JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
        PrivateKeyInfo privKeyInfo = keyPair.getPrivateKeyInfo();
        PrivateKey privKey = converter.getPrivateKey(privKeyInfo);
    }