encode ECB - Android java.security

Android examples for java.security:AES

Description

encode ECB

Demo Code

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

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

import android.util.Base64;

public class Main {

  public static String encodeECB(String stringToEncode, String Key) throws NullPointerException {
    try {/*from   ww  w  . j  a  v  a  2 s.co  m*/
      SecretKeySpec skeySpec = getKey(Key);
      byte[] clearText = stringToEncode.getBytes("utf-8");
      Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
      cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
      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