AES encrypt String - Java Security

Java examples for Security:AES

Description

AES encrypt String

Demo Code

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

public class Main {
  public static void main(String[] argv) {
    String value = "java2s.com";
    System.out.println(encrypt(value));
  }/*from   ww  w.  j  ava 2  s .  c o m*/

  public static String encrypt(String value) {
    try {
      SecretKeySpec sks = new SecretKeySpec(hexStringToByteArray("yourkey"), "AES");
      Cipher cipher = Cipher.getInstance("AES");
      cipher.init(Cipher.ENCRYPT_MODE, sks, cipher.getParameters());
      byte[] encrypted = cipher.doFinal(value.getBytes());
      return byteArrayToHexString(encrypted);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  private static byte[] hexStringToByteArray(String s) {
    byte[] b = new byte[s.length() / 2];
    for (int i = 0; i < b.length; i++) {
      int index = i * 2;
      int v = Integer.parseInt(s.substring(index, index + 2), 16);
      b[i] = (byte) v;
    }
    return b;
  }

  private static String byteArrayToHexString(byte[] b) {
    StringBuilder sb = new StringBuilder(b.length * 2);
    for (int i = 0; i < b.length; i++) {
      int v = b[i] & 0xff;
      if (v < 16) {
        sb.append('0');
      }
      sb.append(Integer.toHexString(v));
    }
    return sb.toString().toUpperCase();
  }

  
}

Related Tutorials