Android How to - Encript String with AES








Question

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

Answer

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
/*w  w  w  . java 2  s .  c  o  m*/
class AESUtils {
  public static String encription(String key, String text) {
    byte[] ivraw = key.getBytes();
    SecretKeySpec skeySpec = new SecretKeySpec(ivraw, "AES");

    try {
      Cipher cipher = Cipher.getInstance("AES");
      cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
      byte[] encrypted = cipher.doFinal(text.getBytes());
      return new String(encrypted);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
}