AES decrypt String - Java Security

Java examples for Security:AES

Description

AES decrypt String

Demo Code


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

public class Main {
  public static void main(String[] argv) {
    String message = "java2s.com";
    System.out.println(decrypt(message));
  }//ww  w.ja  v  a  2s .co  m

  public static String decrypt(String message) {
    try {
      SecretKeySpec sks = new SecretKeySpec(hexStringToByteArray("yourkey"), "AES");
      Cipher cipher = Cipher.getInstance("AES");
      cipher.init(Cipher.DECRYPT_MODE, sks);
      byte[] decrypted = cipher.doFinal(hexStringToByteArray(message));
      return new String(decrypted);
    } 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;
  }
}

Related Tutorials