Search code examples
javasecurityencryptionaesrsa

How to use passphrase for RSAPrivateKey in JAVA?


I encrypt and decrypt with RSA 2048 keys. But for additional security I need to use passphrase for RSAPrivateKey with a AES 128 method.

I can generate this keys, but I don't know how to use them in JAVA.

In my code I initialize private (witout passphrase) key (public is the same):

String PRIVATE_KEY_FILE_RSA = "src/pri.der";
File privKeyFile = new File(PRIVATE_KEY_FILE_RSA);

// read private key DER file
DataInputStream dis = new DataInputStream(new FileInputStream(privKeyFile));
byte[] privKeyBytes = new byte[(int) privKeyFile.length()];
dis.read(privKeyBytes);
dis.close();
KeyFactory keyFactory = KeyFactory.getInstance("RSA");

// decode private key
PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(privKeyBytes);
RSAPrivateKey privKey =(RSAPrivatKey) keyFactory.generatePublic(pubSpec);

And use:

Algorithm algorithm = Algorithm.RSA256(pubKey, privKey);
...

I need for any information or examples how to enter there passphrase.


Solution

  • This solution is better for me.

    I used not-yet-commons-ssl-0.3.11.jar. For example:

    //path to private key file
    String PRIVATE_KEY_FILE_RSA = "C:\\Users\\Adey";
    FileInputStream in = new FileInputStream(PRIVATE_KEY_FILE_RSA);
    // passphrase - the key to decode private key
    String passphrase = "somepass";
    PKCS8Key pkcs8 = new PKCS8Key(in, passphrase.toCharArray());
    byte[] decrypted = pkcs8.getDecryptedBytes();
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decrypted);
    RSAPrivateKey privKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(spec);