import javax.crypto.*;importjavax.crypto.spec.SecretKeySpec;importorg.apache.commons.codec.binary.Base64;importjava.security.NoSuchAlgorithmException;importjava.security.SecureRandom;importjava.util.logging.Level;importjava.util.logging.Logger;/*** @Author:yw
* @Description:AES 加密解密
* @Date: Created in 18:392018/6/11*/
public classAESUtil {private static final String KEY ="sadaasdsad"
private static final String KEY_ALGORITHM = "AES";private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";//默认的加密算法
/*** AES 加密操作
*
*@paramcontent 待加密内容
*@parampassword 加密密码
*@return返回Base64转码后的加密数据*/
public staticString encrypt(String content, String decryptKey) {try{
Cipher cipher= Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);//创建密码器
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE,new SecretKeySpec(decryptKey.getBytes(), "AES"));//初始化为加密模式的密码器
byte[] result = cipher.doFinal(byteContent);//加密
return Base64.encodeBase64String(result);//通过Base64转码返回
} catch(Exception ex) {
Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex);
}return null;
}/*** AES 加密操作
*
*@paramcontent 待加密内容
*@parampassword 加密密码
*@return返回Base64转码后的加密数据*/
public staticString encrypt(String content) {try{
Cipher cipher= Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);//创建密码器
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE,new SecretKeySpec(KEY.getBytes(), "AES"));//初始化为加密模式的密码器
byte[] result = cipher.doFinal(byteContent);//加密
return Base64.encodeBase64String(result);//通过Base64转码返回
} catch(Exception ex) {
Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex);
}return null;
}/*** AES 解密操作
*
*@paramcontent
*@parampassword
*@return
*/
public staticString decrypt(String content, String decryptKey) {try{//实例化
Cipher cipher =Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);//使用密钥初始化,设置为解密模式
cipher.init(Cipher.DECRYPT_MODE,new SecretKeySpec(decryptKey.getBytes(), "AES"));//执行操作
byte[] result =cipher.doFinal(Base64.decodeBase64(content));return new String(result, "utf-8");
}catch(Exception ex) {
Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex);
}return null;
}/*** AES 解密操作
*
*@paramcontent
*@parampassword
*@return
*/
public staticString decrypt(String content) {try{//实例化
Cipher cipher =Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);//使用密钥初始化,设置为解密模式
cipher.init(Cipher.DECRYPT_MODE,new SecretKeySpec(KEY.getBytes(), "AES"));//执行操作
byte[] result =cipher.doFinal(Base64.decodeBase64(content));return new String(result, "utf-8");
}catch(Exception ex) {
Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex);
}return null;
}/*** 生成加密秘钥
*
*@return
*/
private static SecretKeySpec getSecretKey(finalString password) {//返回生成指定算法密钥生成器的 KeyGenerator 对象
KeyGenerator kg = null;try{
kg=KeyGenerator.getInstance(KEY_ALGORITHM);//AES 要求密钥长度为 128
kg.init(128, newSecureRandom(password.getBytes()));//生成一个密钥
SecretKey secretKey =kg.generateKey();return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);//转换为AES专用密钥
} catch(NoSuchAlgorithmException ex) {
Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex);
}return null;
}public static voidmain(String[] args) {
String content= "13958160820"; //0gqIDaFNAAmwvv3tKsFOFf9P9m/6MWlmtB8SspgxqpWKYnELb/lXkyXm7P4sMf3e
System.out.println("加密前:" +content);
System.out.println("加密密钥和解密密钥:" +KEY);
String encrypt=encrypt(content, KEY);
System.out.println(encrypt.length()+":加密后:" +encrypt);
String decrypt=decrypt(encrypt, KEY);
System.out.println("解密后:" +decrypt);
}/* *//*** 加密
* @method encrypt
*@paramcontent 需要加密的内容
*@parampassword 加密密码
*@return*@throws*@sincev1.0*//*public static String encrypt(String content){
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(KEY.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");// 创建密码器
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(byteContent);
return parseByte2HexStr(result);// 加密
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}catch (NoSuchPaddingException e) {
e.printStackTrace();
}catch (UnsupportedEncodingException e) {
e.printStackTrace();
}catch (InvalidKeyException e) {
e.printStackTrace();
}catch (IllegalBlockSizeException e) {
e.printStackTrace();
}catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}*//*** 加密
* @method encrypt
*@paramcontent 需要加密的内容
*@parampassword 加密密码
*@return*@throws*@sincev1.0*//*public static String encrypt(String content, String password){
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(password.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");// 创建密码器
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(byteContent);
return parseByte2HexStr(result);// 加密
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}catch (NoSuchPaddingException e) {
e.printStackTrace();
}catch (UnsupportedEncodingException e) {
e.printStackTrace();
}catch (InvalidKeyException e) {
e.printStackTrace();
}catch (IllegalBlockSizeException e) {
e.printStackTrace();
}catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}*//*** 解密
* @method decrypt
*@paramcontent 待解密内容
*@parampassword 解密密钥
*@return*@throws*@sincev1.0*//*public static String decrypt(String content, String password){
try {
byte[] param = parseHexStr2Byte(content);
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(password.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");// 创建密码器
cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(param);
return new String(result); // 解密
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}catch (NoSuchPaddingException e) {
e.printStackTrace();
}catch (InvalidKeyException e) {
e.printStackTrace();
}catch (IllegalBlockSizeException e) {
e.printStackTrace();
}catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}*//*** 解密
* @method decrypt
*@paramcontent 待解密内容
*@parampassword 解密密钥
*@return*@throws*@sincev1.0*//*public static String decrypt(String content){
try {
byte[] param = Base64.decodeBase64(parseHexStr2Byte(content));
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(KEY.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");// 创建密码器
cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(param);
return new String(result); // 解密
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}catch (NoSuchPaddingException e) {
e.printStackTrace();
}catch (InvalidKeyException e) {
e.printStackTrace();
}catch (IllegalBlockSizeException e) {
e.printStackTrace();
}catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}*//*** 将二进制转换成16进制
* @method parseByte2HexStr
*@parambuf
*@return*@throws*@sincev1.0*//*public static String parseByte2HexStr(byte buf[]){
StringBuffer sb = new StringBuffer();
for(int i = 0; i < buf.length; i++){
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}*//*** 将16进制转换为二进制
* @method parseHexStr2Byte
*@paramhexStr
*@return*@throws*@sincev1.0*//*public static byte[] parseHexStr2Byte(String hexStr){
if(hexStr.length() < 1)
return null;
byte[] result = new byte[hexStr.length()/2];
for (int i = 0;i< hexStr.length()/2; i++) {
int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}*//*** 另外一种加密方式--这种加密方式有两种限制
* 1、密钥必须是16位的
* 2、待加密内容的长度必须是16的倍数,如果不是16的倍数,就会出如下异常
* javax.crypto.IllegalBlockSizeException: Input length not multiple of 16 bytes
at com.sun.crypto.provider.SunJCE_f.a(DashoA13*..)
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.AESCipher.engineDoFinal(DashoA13*..)
at javax.crypto.Cipher.doFinal(DashoA13*..)
要解决如上异常,可以通过补全传入加密内容等方式进行避免。
* @method encrypt2
*@paramcontent 需要加密的内容
*@parampassword 加密密码
*@return*@throws*@sincev1.0*//*public static byte[] encrypt2(String content, String password){
try {
SecretKeySpec key = new SecretKeySpec(password.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(byteContent);
return result; // 加密
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}*/}