一. 关于字符串与16进制的转换
String str = "Hello World";
StringBuilder hexStr = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
hexStr.append(String.format("%02x", (int) str.charAt(i)));
}
System.out.println("16进制表示为:" + hexStr.toString());
运行结果:16进制表示为:48656c6c6f20576f726c64
String.format()
方法用于格式化字符串,其中%02x
表示以16进制形式输出,不足两位时前面补0。(int) str.charAt(i)
将字符转换为ASCII码值。StringBuilder
用于拼接字符串。
二.MD5加密后的长度都是定长的128位哈希值,即32位16进制数据。一共占用16字节。
三 AES加密
AES-128是一种区块加密算法,其处理的数据块大小固定为128位(16字节)。无论输入数据的实际长度是多少,加密后的数据都会以16字节的块来表示。如果原始数据不是16字节的倍数,那么需要进行填充(Padding)以满足这个要求。
aes加密的明文是30个字节 ,那他加密的逻辑是什么?
他会分成一个是16字节 一个是14字节的数据块,并对14字节的数据块进行补全16字节,然后再加密。加密后拼接起来。
明文如果是16字节, 那么加密后的密文也是16个字节。所以明文如果是16个字节的倍数的话,那密文和明文的长度相同。
四.aesdemo
public static void main(String[] args) throws Exception {
// 生成32位的的16进制字符串
// String content=RandomUtils.generateRandomHexString(32);
String content="1f4976ee90992305a7e28ca645cbc915";
System.out.println(content);
byte[] KEY = MD5.MD5Encode2("CHZD12KTNX190930430");
String encStr=aesEncryptBluetooth(content, KEY);
System.out.println(encStr);
System.out.println(ByteUtils.bytes2HexStr(aesDecryptByBytesBluetooth(encStr, KEY)));
System.out.println(hexEncode(aesDecryptByBytesBluetooth(encStr, KEY)));
}
/**
* 加密 将16进制的字符串加密
*/
public static String aesEncryptBluetooth(String hexStr, byte[] cabinetMd5) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
Cipher cipher = Cipher.getInstance(ALGORITHMSTR2);
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(cabinetMd5, "AES"));
return hexEncode(cipher.doFinal(ByteUtils.hexStr2Bytes(hexStr)));
}
/**
* 解密 将16进制的字符串解密
* @param hexStr
* @param cabinetMd5
* @return
* @throws Exception
*/
public static byte[] aesDecryptByBytesBluetooth(String hexStr, byte[] cabinetMd5) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
Cipher cipher = Cipher.getInstance(ALGORITHMSTR2);
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(cabinetMd5, "AES"));
byte[] decryptBytes = cipher.doFinal(ByteUtils.hexStr2Bytes(hexStr));
return decryptBytes;
}
输出结果
1f4976ee90992305a7e28ca645cbc915
08919dcc0c03684fc894bea8679b0653
1f4976ee90992305a7e28ca645cbc915
1f4976ee90992305a7e28ca645cbc915