package com.cku.util; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Base64; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; public class AESUtils { private int _cipherMode = 0; private SecretKey _desKey = null; private Cipher _c = null; private static byte[] s_cryptKey = new byte[] { 0x56, 0x32, 0x02, 0x43, 0x71, 0x66, 0x23, 0x2F, (byte) 0xfa, (byte) 0xE7, (byte) 0x89, (byte) 0x80, 0x12, 0x56, (byte) 0x99, (byte) 0xA1 }; private AESUtils(int cipherMode) throws NoSuchAlgorithmException, NoSuchPaddingException { this._cipherMode = cipherMode; // ������Կ this._desKey = new SecretKeySpec(s_cryptKey, "AES"); // ����Cipher����,ָ����֧�ֵ�DES�㷨 this._c = Cipher.getInstance("AES"); } /** * ���� * * @param data * @return cryptedData * @throws InvalidKeyException * @throws IllegalBlockSizeException * @throws BadPaddingException * @throws NoSuchPaddingException * @throws NoSuchAlgorithmException */ public byte[] process(byte[] data) throws Exception { try { this._c.init(this._cipherMode, this._desKey); byte[] result = this._c.doFinal(data); return result; } finally { try { this._desKey.destroy(); } catch (Exception e) {} } } public static byte[] encrypt(byte[] data) throws Exception { AESUtils encryptor = new AESUtils(Cipher.ENCRYPT_MODE); return encryptor.process(data); //encryptor._desKey.destroy(); } public static byte[] decrypt(byte[] data) throws Exception { AESUtils decryptor = new AESUtils(Cipher.DECRYPT_MODE); return decryptor.process(data); } /** * @param args * @throws NoSuchPaddingException * @throws NoSuchAlgorithmException * @throws BadPaddingException * @throws IllegalBlockSizeException * @throws InvalidKeyException */ public static void main(String[] args) throws Exception { String msg = "5qf47f7q"; //for (int i = 0; i < 1000000; ++i) { byte[] encontent = AESUtils.encrypt(msg.getBytes("utf-8")); String en2 = Base64.getEncoder().encodeToString(encontent); byte[] decontent = AESUtils.decrypt(Base64.getDecoder().decode(en2)); System.out.println("xxx:" + msg); System.out.println("xxx:" + new String(encontent, "utf-8")); System.out.println("xxx:" + new String(decontent, "utf-8")); } } }