Decrypt with AES/ECB/PKCS5Padding or AES/CBC/PKCS5Padding - Android java.security

Android examples for java.security:AES

Description

Decrypt with AES/ECB/PKCS5Padding or AES/CBC/PKCS5Padding

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.util.Base64;

public class Main {

  public static String Decrypt(String stringToEncode, String Key, String IV) throws Exception {
    try {/*from www  .  ja v  a 2s. c  o  m*/
      if (Key == null) {
        return null;
      }

      Cipher cipher;
      byte[] encrypted1 = Base64.decode(stringToEncode, 0);
      if (null != IV) {
        IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes());
        SecretKeySpec skeySpec = getKey(Key);
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivParameterSpec);
      } else {
        byte[] raw = Key.getBytes("utf-8");
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
      }
      byte[] ret = cipher.doFinal(encrypted1);
      return new String(ret, "utf-8");
    } catch (Exception ex) {
      System.out.println(ex.toString());
      return null;
    }
  }

  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