Encrypting files with Public Key Encryption in Java
This HOWTO describes one way of implementing public key encryption in Java. It is generally not advisable to use a public key encryption algorithm such as RSA to directly encrypt files, since (i) public key encryption is slow, and (ii) it will only let you encrypt small things (...well, I haven't managed to get it to encrypt big things ;)
The alternative, and commonly used approach, is to use a shared key algorithm to encrypt/decrypt the files, and then use a public key algorithm to encrypt/decrypt the (randomly generated) key used by the shared key algorithm. This has the benefit of fast file encryption/decryption whilst still requiring a non-shared private key to get access to the key needed to decrypt the files.
In this HOWTO, I use the RSA public key algorithm and the AES shared key algorithm. The code is here.
Note to Windows users: you will need to install Sun's Unlimited Strength Jurisdiction Policy Files to run this code - for the most recent java version, these are currently available here (the last item in the list). If you still get an InvalidKeyException, check that the policy files are installed in both the JDK and the JRE directories.