Android How to - Encript AES with private key








Question

We would like to know how to encript AES with private key.

Answer

/* www.  ja  v  a2 s .  c o  m*/
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
class AESEnc {

  final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();

  public static String bytesToHex(byte[] bytes) {
    char[] hexChars = new char[bytes.length * 2];
    int v;
    for (int j = 0; j < bytes.length; j++) {
      v = bytes[j] & 0xFF;
      hexChars[j * 2] = hexArray[v >>> 4];
      hexChars[j * 2 + 1] = hexArray[v & 0x0F];
    }
    return new String(hexChars);
  }

  public static String encryptAES(String value, String privateKey) {
    byte[] raw = null;
    byte[] result = null;
    try {
      raw = privateKey.getBytes("utf-8");
      SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
      Cipher cipher = Cipher.getInstance("AES");
      cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
      result = cipher.doFinal(value.getBytes("utf-8"));
    } catch (Exception e) {
      e.printStackTrace();
    }
    System.out.println("seed:"+ privateKey);
    return bytesToHex(result);
  }
}