encode CBC - Android java.security

Android examples for java.security:AES

Description

encode CBC

Demo Code

import java.io.UnsupportedEncodingException;
import java.util.Arrays;

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

import android.annotation.SuppressLint;
import android.util.Base64;

public class Main {

  @SuppressLint("TrulyRandom")
  public static String encodeCBC(String stringToEncode, String Key, String IV) throws NullPointerException {
    try {//from  ww w . j a  v a2s.c  o m
      SecretKeySpec skeySpec = getKey(Key);
      byte[] clearText = stringToEncode.getBytes("UTF8");
      IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes());
      Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
      cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivParameterSpec);

      String encrypedValue = Base64.encodeToString(cipher.doFinal(clearText), Base64.DEFAULT);
      return encrypedValue;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return "";
  }

  private static SecretKeySpec getKey(String Key) throws UnsupportedEncodingException {
    int keyLength = 256;
    byte[] keyBytes = new byte[keyLength / 8];
    Arrays.fill(keyBytes, (byte) 0x0);
    byte[] passwordBytes = Key.getBytes("UTF-8");
    int length = passwordBytes.length < keyBytes.length ? passwordBytes.length : keyBytes.length;
    System.arraycopy(passwordBytes, 0, keyBytes, 0, length);
    SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
    return key;
  }

}

Related Tutorials