用于对密钥加密保存使用
直接上代码
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.SecureRandom;
/**
* AES 对称算法加密/解密工具类
*
* @author
*/
public class AESUtils {
public static void main(String[] args) throws Exception {
String content = "这是一段代码"; //原文内容
String key = "这是钥匙"; //解密用的原始密码
// 加密数据, 返回密文
byte[] cipherBytes = AESUtils.encrypt(content.getBytes(), key.getBytes());
//转化为16进制字符串用于保存配置文件
String hexString = byteArrayToHexString(cipherBytes);
System.out.println(hexString);
//恢复为字节数组与cipherBytes内容相同
byte[] toByteArray = hexStringToByteArray(hexString);
// 解密数据, 返回明文
byte[] plainBytes = AESUtils.decrypt(toByteArray, key.getBytes());
System.out.println(new String(plainBytes));
}
/**
* 生成密钥对象
*/
private static SecretKey generateKey(byte[] key) throws Exception {
// 创建安全随机数生成器
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
// 设置 密钥key的字节数组 作为安全随机数生成器的种子
random.setSeed(key);
// 创建 AES算法生成器
KeyGenerator gen = KeyGenerator.getInstance("AES");//加密/解密算法名称
// 初始化算法生成器 密钥可选长度: 128, 192 or 256
gen.init(128, random);
// 生成 AES密钥对象
return gen.generateKey();
}
/**
* 数据加密: 明文 -> 密文
* @param content 明文文
* @param key 密钥
* @return
* @throws Exception
*/
public static byte[] encrypt(byte[] content, byte[] key) throws Exception {
// 生成密钥对象
SecretKey secKey = generateKey(key);
// 获取 AES 密码器
Cipher cipher = Cipher.getInstance("AES");
// 初始化密码器(加密模型)
cipher.init(Cipher.ENCRYPT_MODE, secKey);
// 加密数据, 返回密文
byte[] cipherBytes = cipher.doFinal(content);
return cipherBytes;
}
/**
* 数据解密: 密文 -> 明文
* @param content 密文
* @param key 密钥
* @return
* @throws Exception
*/
public static byte[] decrypt(byte[] content, byte[] key) throws Exception {
// 生成密钥对象
SecretKey secKey = generateKey(key);
// 获取 AES 密码器
Cipher cipher = Cipher.getInstance("AES");
// 初始化密码器(解密模型)
cipher.init(Cipher.DECRYPT_MODE, secKey);
// 解密数据, 返回明文
byte[] plainBytes = cipher.doFinal(content);
return plainBytes;
}
/**
* 字节数组转换成16进制字符串
* @param arr
* @return content
*/
public static String byteArrayToHexString(byte[] arr) {
char[] Chars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
char[] c = new char[arr.length * 2];
int index = 0;
for (byte a : arr) {
c[index++] = Chars[a & 0xf];
c[index++] = Chars[a >>> 4 & 0xf];
}
String content = new String(c);
return content;
}
/**
* 16进制字符串转换成字节数组
* @param content
* @return
*/
public static byte[] hexStringToByteArray(String content) {
String HexString = "0123456789abcdef";
byte[] arr = new byte[content.length() / 2];
char[] crr = content.toCharArray();
int index = 0;
for (int i = 0; i < crr.length; ) {
int low = HexString.indexOf(crr[i++]);
int high = HexString.indexOf(crr[i++]);
arr[index++] = (byte) (high << 4 | low);
}
return arr;
}
}
运行结果