import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
/**
* @version V1.0
* @desc AES 加密工具類
*/
public class AESUtils {
private static final String KEY_ALGORITHM = "AES";
private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";//默認(rèn)的加密算法
private static final String PASSWORD_KEY = "123456";//解密秘鑰
/**
* AES 加密操作
*
* @param content 待加密內(nèi)容
* @param password 加密密碼
* @return 返回Base64轉(zhuǎn)碼后的加密數(shù)據(jù)
*/
public static String encrypt(String content) {
try {
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// 創(chuàng)建密碼器
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(PASSWORD_KEY));// 初始化為加密模式的密碼器
byte[] result = cipher.doFinal(byteContent);// 加密
return Base64.encodeBase64String(result);//通過Base64轉(zhuǎn)碼返回
} catch (Exception ex) {
Logger.getLogger(AESUtils.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
* AES 解密操作
*
* @param content
* @param password
* @return
*/
public static String decrypt(String content) {
try {
//實(shí)例化
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
//使用密鑰初始化,設(shè)置為解密模式
cipher.init(Cipher.DECRYPT_MODE, getSecretKey(PASSWORD_KEY));
//執(zhí)行操作
byte[] result = cipher.doFinal(Base64.decodeBase64(content));
return new String(result, "utf-8");
} catch (Exception ex) {
Logger.getLogger(AESUtils.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
* 生成加密秘鑰
*
* @return
*/
private static SecretKeySpec getSecretKey(final String password) {
//返回生成指定算法密鑰生成器的 KeyGenerator 對(duì)象
KeyGenerator kg = null;
try {
kg = KeyGenerator.getInstance(KEY_ALGORITHM);
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG" );
secureRandom.setSeed(password.getBytes());
//AES 要求密鑰長(zhǎng)度為 128
kg.init(128, secureRandom);
//生成一個(gè)密鑰
SecretKey secretKey = kg.generateKey();
return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);// 轉(zhuǎn)換為AES專用密鑰
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(AESUtils.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
public static void main(String[] args) {
String s = "oFWN75fxFHQ";
System.out.println("s:" + s);
String s1 = AESUtils.encrypt(s);
System.out.println("s1:" + s1);
System.out.println("s2:"+AESUtils.decrypt(s1));
}
}
名稱欄目:AES加密和解密工具類
標(biāo)題網(wǎng)址:
http://weahome.cn/article/pjddse.html