1、单一MD或者SHA算法的缺点(摘要值容易被篡改)
2、HMAC算法
2.1 HMAC算法简介
HMAC,全称为“Hash Message Authentication Code”,中文名“散列消息鉴别码”,主要是利用哈希算法,以一个密钥和一个消息为输入,生成一个消息摘要作为输出。一般的,消息鉴别码用于验证传输于两个共 同享有一个密钥的单位之间的消息。HMAC 可以与任何迭代散列函数捆绑使用。MD5 和 SHA-1 就是这种散列函数。HMAC 还可以使用一个用于计算和确认消息鉴别值的密钥。
2.2 对比单一MD或者SHA算法的优点
2.3 HSAC算法种类
2.4 HMAC算法编程步骤
1.构建秘钥
2.执行消息摘要
3、HMAC代码实现
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class HMACUtils {
/**
*
* @param data
* 要获取消息摘要的数据
* @param key
* 加密过程中,用到的秘钥
* @return
*/
public static String encryptHmac(byte[] data, byte[] key) {
try {
// 判断数据的合法性
if (data == null) {
throw new RuntimeException("数据不能为NULL");
}
// 获取秘钥
SecretKey secretKey = new SecretKeySpec(key, "HmacSHA512");
// 获取加密算法
Mac mac = Mac.getInstance("HmacSHA512");
// 设置秘钥
mac.init(secretKey);
// 获取数据
byte[] resultBytes = mac.doFinal(data);
// 将字节数组转化为16进制数据
String resultString = fromBytesToHex(resultBytes);
// 返回数据
return resultString;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
*
* @param data
* 要获取消息摘要的数据
* @param key
* 加密过程中,用到的秘钥
* @return
*/
public static String encryptHmac(String data, byte[] key) {
try {
// 判断数据的合法性
if (data == null) {
throw new RuntimeException("数据不能为NULL");
}
// 获取秘钥
SecretKey secretKey = new SecretKeySpec(key, "HmacSHA512");
// 获取加密算法
Mac mac = Mac.getInstance("HmacSHA512");
// 设置秘钥
mac.init(secretKey);
// 获取数据
byte[] resultBytes = mac.doFinal(data.getBytes());
// 将字节数组转化为16进制数据
String resultString = fromBytesToHex(resultBytes);
// 返回数据
return resultString;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 将字节数组转化为16进制
*
* @param resultBytes
* @return
*/
private static String fromBytesToHex(byte[] resultBytes) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < resultBytes.length; i++) {
if (Integer.toHexString(0xFF & resultBytes[i]).length() == 1) {
builder.append("0").append(
Integer.toHexString(0xFF & resultBytes[i]));
} else {
builder.append(Integer.toHexString(0xFF & resultBytes[i]));
}
}
return builder.toString();
}
/**
* 用于生成秘钥
*
* @return
*/
public static byte[] initHmacKey() {
try {
KeyGenerator keyGen = KeyGenerator.getInstance("HmacSHA512");
SecretKey secretKey = keyGen.generateKey();
return secretKey.getEncoded();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
测试代码
public class Test {
// 待加密的明文
public static final String DATA = "tes2t";
public static void main(String[] args) throws Exception {
/* Test HMAC */
byte[] hmacKey = HMACUtils.initHmacKey();
System.out.println("HMAC KEY: " + BytesToHex.fromBytesToHex(hmacKey));
String hmacResult = HMACUtils.encryptHmac(DATA.getBytes(), hmacKey);
System.out.println(DATA + ">>>HMAC>>>" + hmacResult);
}
}
4、总结
散列函数特征:
(1)输入任意长度数据,输出固定长度散列值,计算很容易,过程不可逆
(2)对于某数据,其散列值固定
(3)两个数据不同,则对应的散列值也不同
(4)两个散列值不同,则对应的原始输入数据也不同