/** Password based encryption with AES, this program is derived by A. Lisitsa from the code by mrclay taken from https://github.com/mrclay/jSecureEdit/tree/master/src/org/mrclay/crypto Notice that it **works only for the key size 128** see the line > KeySpec spec = new PBEKeySpec(password, salt, 1024, 128); below. For other AES key sizes (192,256) it does not work, producing the exception: Illegal key size or default parameters. **/ import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.security.spec.InvalidParameterSpecException; import java.security.spec.KeySpec; import javax.crypto.*; import javax.crypto.spec.*; import java.security.Key; import javax.crypto.Cipher; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.SecretKeySpec; import javax.crypto.spec.PBEParameterSpec; import javax.crypto.spec.SecretKeySpec; public class PBE { public static void main( String[] args) throws Exception { char[] password = "newpassword".toCharArray(); byte[] salt = { (byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c, (byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99 }; SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); KeySpec spec = new PBEKeySpec(password, salt, 1024, 128); Key secretKey = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] cleartext = "This is another example".getBytes(); byte[] ciphertext = cipher.doFinal(cleartext); System.out.println("cipher : " + Utils.toHex(ciphertext)); } }