Several days ago, my friend asked me how to create a simple AES encryption – decryption using java. Well, here is your answer, hope it will helped you.
package com.edw.testing; import java.security.AlgorithmParameters; import java.security.spec.KeySpec; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.SecretKeySpec; import sun.misc.BASE64Encoder; public class TestingAES { public TestingAES() { } private void execute() throws Exception { String password = "mypassword"; String salt = "salt"; String cipherText = "Hello, World!"; SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); KeySpec spec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), 65536, 256); SecretKey tmp = factory.generateSecret(spec); SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES"); // encrypt Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secret); AlgorithmParameters params = cipher.getParameters(); byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV(); byte[] ciphertext = cipher.doFinal(cipherText.getBytes("UTF-8")); System.out.println("password : "+password); System.out.println("salt : "+salt); System.out.println("cipherText : "+cipherText); System.out.println("iv : "+new BASE64Encoder().encode(iv)); System.out.println("ciphertext : "+new BASE64Encoder().encode(ciphertext)); // decrypt Cipher cipherDecrypt = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipherDecrypt.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv)); String plaintext = new String(cipherDecrypt.doFinal(ciphertext), "UTF-8"); System.out.println("decrypted text : "+plaintext); } public static void main(String[] args) throws Exception { TestingAES testingAES = new TestingAES(); testingAES.execute(); } }
And this is what is written on my netbeans console,
Oh and if you ever found this kind of error
Caused by: java.security.InvalidKeyException: Illegal key size or default parameters
it means that you need to install Java Cryptography Extension (JCE). You will find it here,
http://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html
Have fun 😀
Hey man nice example ! can you demo how to encrypt/decrypt a file? ive been trying to implement your code in my project but its not working the best (n);
Hi Travis,
you can use bouncycastle to do that.