1.生成AES Key
/**
* AES根据密码生成Key
* @param password
* @return
*/
public static Key createKey(String password) {
// 构造密码生成器,指定为AES算法
try {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
// 生成128位的随机源
keyGenerator.init(128, new SecureRandom(password.getBytes()));
// 产生原始对称秘钥
SecretKey secretKey = keyGenerator.generateKey();
// 获得原始对称秘钥的字节数组
byte[] encodedBytes = secretKey.getEncoded();
// Key转换,根据字节数组生成AES秘钥
return new SecretKeySpec(encodedBytes, "AES");
} catch (Exception e) {
LOG.error("generate key fail");
}
return null;
}
2.AES加密(ECB模式)
/**
* AES加密操作,使用ECB模式
* @param contents
* @param password
* @return
*/
public static String encryptAES(String contents, String password) throws Exception {
// 创建密码器
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
// 初始化为加密密码器
cipher.init(Cipher.ENCRYPT_MODE, createKey(password));
// 加密
byte[] encryptBytes = cipher.doFinal(contents.getBytes("UTF-8"));
return byte2Hex(encryptBytes);
}
3.AES解密
/**
* AES解密操作
* @param encryptCode
* @param password
* @return
*/
public static String decryptAES(String encryptCode, String password) throws Exception {
// 创建密码器
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
// 初始化为解密密码器
cipher.init(Cipher.DECRYPT_MODE, createKey(password));
// 解密
byte[] decryptBytes = cipher.doFinal(hex2Byte(encryptCode));
return new String(decryptBytes, "UTF-8");
}
----------------------------------
工具方法
/**
* 将byte[]数组转换成16进制字符。一个byte生成两个字符,长度对应1:2
* @param bytes,输入byte[]数组
* @return 16进制字符
*/
public static String byte2Hex(byte[] bytes) {
if (bytes == null) {
return null;
}
StringBuilder builder = new StringBuilder();
// 遍历byte[]数组,将每个byte数字转换成16进制字符,再拼接起来成字符串
for (int i = 0; i < bytes.length; i++) {
// 每个byte转换成16进制字符时,bytes[i] & 0xff如果高位是0,输出将会去掉,所以+0x100(在更高位加1),再截取后两位字符
builder.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
}
return builder.toString();
}
/**
* 将16进制字符转换成byte[]数组。与byte2Hex功能相反。
* @param string 16进制字符串
* @return byte[]数组
*/
public static byte[] hex2Byte(String string) {
if (string == null || string.length() < 1) {
return null;
}
// 因为一个byte生成两个字符,长度对应1:2,所以byte[]数组长度是字符串长度一半
byte[] bytes = new byte[string.length() / 2];
// 遍历byte[]数组,遍历次数是字符串长度一半
for (int i = 0; i < string.length() / 2; i++) {
// 截取没两个字符的前一个,将其转为int数值
int high = Integer.parseInt(string.substring(i * 2, i * 2 + 1), 16);
// 截取没两个字符的后一个,将其转为int数值
int low = Integer.parseInt(string.substring(i * 2 + 1, i * 2 + 2), 16);
// 高位字符对应的int值*16+低位的int值,强转成byte数值即可
// 如dd,高位13*16+低位13=221(强转成byte二进制11011101,对应十进制-35)
bytes[i] = (byte) (high * 16 + low);
}
return bytes;
}
来源:https://www.cnblogs.com/hello4world/p/12215967.html