package test.util;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class AESUtil {
/**
* 生成密钥
* @return
* @throws Exception
*/
public static byte[] initKey() throws Exception{
// KeyGenerator 密钥生成器
KeyGenerator keygen = KeyGenerator.getInstance("AES");
// 初始化密钥生成器
keygen.init(128);
// 生成密钥
SecretKey secretKey = keygen.generateKey();
return secretKey.getEncoded();
}
/**
* DES 加密
* @param data
* @param key
* @return
* @throws Exception
* @throws NoSuchAlgorithmException
*/
public static byte[] encrype(byte[] data,byte[] key) throws Exception{
// 恢复密钥
SecretKey secretKey = new SecretKeySpec(key, "AES");
// Cipher 完成加密解密工作
Cipher cipher = Cipher.getInstance("AES");
// 根据密钥,对Cipher初始化
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
// 加密/解密
byte[] cipherByte = cipher.doFinal(data);
return cipherByte;
}
/**
* DES 解密
* @param data
* @param key
* @return
* @throws NoSuchPaddingException
* @throws NoSuchAlgorithmException
*/
public static byte[] decrype(byte[] data,byte[] key) throws Exception{
SecretKey secretKey = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] planByte = cipher.doFinal(data);
return planByte;
}
}