encrypt AES - Android java.security

Android examples for java.security:AES

Description

encrypt AES

Demo Code


import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import android.util.Base64;
import android.util.Log;

public class Main {
  public static final String KEY = "your key";
  private static String tag = "";

  public static String encryptAES(String content) {
    try {/*from  w w w. j  a  v  a  2 s. c om*/
      byte[] bytes = Base64.decode(KEY, Base64.NO_WRAP);
      byte[] valueBytes = content.getBytes("UTF-8");
      String str = new String(bytes, "UTF-8");
      Log.i(tag, "str " + str);
      String strs[] = str.split(",");
      if (strs.length == 2) {

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
        IvParameterSpec zeroIv = new IvParameterSpec(Base64.decode(strs[0], Base64.NO_WRAP));
        SecretKeySpec key = new SecretKeySpec(Base64.decode(strs[1], Base64.NO_WRAP), "AES");
        cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
        byte[] result = cipher.doFinal(valueBytes, 0, valueBytes.length);
        String decryptStr = Base64.encodeToString(result, Base64.NO_WRAP);
        Log.i(tag, "decrypt STR " + decryptStr + " length " + decryptStr.length() + " " + decryptStr.contains("\n"));
        return decryptStr;
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
}

Related Tutorials