Android How to - Encript and decrypt String with AES








Question

We would like to know how to encript and decrypt String with AES.

Answer

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
//ww  w .ja v a  2  s  . c o  m
import android.util.Base64;

class AES {

  public static String encrypt(String input, String key) {
    byte[] crypted = null;
    try {
      SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
      Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
      cipher.init(Cipher.ENCRYPT_MODE, skey);
      crypted = cipher.doFinal(input.getBytes());
    } catch (Exception e) {
      System.out.println(e.toString());
    }
    return new String(Base64.encode(crypted, 8));
  }

  public static String decrypt(String input, String key) {
    byte[] output = null;

    try {
      SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
      Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
      cipher.init(Cipher.DECRYPT_MODE, skey);
      output = cipher.doFinal(Base64.decode(input, 8));
    } catch (Exception e) {
      System.out.println(e.toString());
    }
    return new String(output);
  }

}