整理AES加解密,字节数组与十六进制字符串的相互转换。
public class AES {
public static void main(String[] args) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException {
String content = "AES加解密";
String key = "010203";
System.out.println("加密前:" + content);
String encryptStr = encrypt(content, key);
System.out.println("加密后:" + encryptStr);
String decryptStr = decrypt(encryptStr, key);
System.out.println("解密后:" + decryptStr);
}
public static String encrypt(String content, String key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException {
// 获取AES专用密钥
SecretKeySpec aesKey = getKey(key);
// 创建密码器
Cipher cipher = Cipher.getInstance("AES");
// 初始化为加密模式
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
byte[] source = content.getBytes("UTF-8");
// 加密
byte[] encrypt = cipher.doFinal(source);
// 加密后的字节数组可能乱码,但可转换为十六进制字符串
String result = byte2HexStr(encrypt);
return result;
}
/*
* 一位十六进制对应四位二进制,如十六进制的E对应的二进制为0110
* 所以可把字节的高四位、低四位转换对应的十六进制
*/
public static String byte2HexStr(byte[] byteArr) {
StringBuffer buffer = new StringBuffer();
String temp = "0123456789ABCDEF";
for(int i = 0; i < byteArr.length; i++) {
// 右移四位得到高四位
buffer.append(temp.charAt(byteArr[i] >> 4 & 0x0f));
buffer.append(temp.charAt(byteArr[i] & 0x0f));
}
return buffer.toString();
}
public static String decrypt(String content, String key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
// 获取AES专用密钥
SecretKeySpec aesKey = getKey(key);
// 创建密码器
Cipher cipher = Cipher.getInstance("AES");
// 初始化为解密模式
cipher.init(Cipher.DECRYPT_MODE, aesKey);
// 十六进制字符串转换为字节数组
byte[] temp = hexStr2Byte(content);
// 解密
byte[] decrypt = cipher.doFinal(temp);
return new String(decrypt);
}
public static byte[] hexStr2Byte(String content) {
// 每两位十六进制字符串对应一字节
byte[] result = new byte[content.length() / 2];
String str = "0123456789ABCDEF";
for(int i = 0; i < result.length; i++) {
int pos = i * 2;
result[i] = (byte)(str.indexOf(content.charAt(pos)) << 4 | str.indexOf(content.charAt(pos + 1)));
}
return result;
}
public static SecretKeySpec getKey(String key) throws NoSuchAlgorithmException {
// 创建AES的key生成器
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128, new SecureRandom(key.getBytes()));
// 根据约定的key生成密钥
SecretKey secretKey = keyGenerator.generateKey();
// 返回基本编码格式
byte[] encoded = secretKey.getEncoded();
// 创建AES专用密钥
SecretKeySpec aesKey = new SecretKeySpec(encoded, "AES");
return aesKey;
}
}
运行结果如下: