Java SecretKeySpec create AES key

Description

Java SecretKeySpec create AES key




//package com.demo2s;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

public class Main {

   public static String aesDecryptHex(String encrypted, String key) {

      return aesDecrypt(hex2byte(encrypted), key);
   }/*from   w w w .j  a  v a  2s  . co  m*/

   public static String aesDecrypt(byte[] encrypted, String key) {
      try {
         byte[] raw = key.getBytes("ASCII");
         SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
         Cipher cipher = Cipher.getInstance("AES");
         cipher.init(Cipher.DECRYPT_MODE, skeySpec);
         byte[] original = cipher.doFinal(encrypted);
         return new String(original, "utf-8");
      } catch (UnsupportedEncodingException e) {
         e.printStackTrace();
      } catch (NoSuchAlgorithmException e) {
         e.printStackTrace();
      } catch (InvalidKeyException e) {
         e.printStackTrace();
      } catch (NoSuchPaddingException e) {
         e.printStackTrace();
      } catch (BadPaddingException e) {
         e.printStackTrace();
      } catch (IllegalBlockSizeException e) {
         e.printStackTrace();
      }
      return null;
   }

   public static byte[] hex2byte(String hexstr) {
      if (hexstr == null) {
         return null;
      }
      int l = hexstr.length();
      if ((l & 1) == 1) {
         return null;
      }
      byte[] b = new byte[l / 2];
      for (int i = 0; i != l / 2; i++) {
         b[i] = (byte) Integer.parseInt(hexstr.substring(i * 2, i * 2 + 2), 16);
      }
      return b;
   }
}



PreviousNext

Related