AES/CBC/PKCS5Padding encrypt - Android java.security

Android examples for java.security:AES

Description

AES/CBC/PKCS5Padding encrypt

Demo Code

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

import android.util.Base64;

public class Main {

  private final static String DEFAULT_KEY = "ITAG_KEY_MANAGER";
  private final static byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F', 0 };

  public static String encrypt(String src) throws Exception {
    return encrypt(DEFAULT_KEY, src);
  }//from  w  ww . ja va2 s  . c o m

  public static String encrypt(String key, String src) throws Exception {
    byte[] keyByte = key.getBytes();
    SecretKeySpec keySpec = new SecretKeySpec(keyByte, "AES");
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    IvParameterSpec ivSpec = new IvParameterSpec(iv);
    cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);

    byte[] srcByte = src.getBytes();
    byte[] encrypted = cipher.doFinal(srcByte);

    String result = Base64.encodeToString(encrypted, Base64.DEFAULT);
    return result;
  }

}

Related Tutorials