廖雪峰Java10加密与安全-3摘要算法-5Hmac
1 比较MD5和HamcMD5
HmacMD5可以看作带安全salt的MD5
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.Security;
public class SplitString {
public static void getMD5(String text,String salt) throws Exception{
//使用salt+MD5加密
byte[] data = text.getBytes("UTF-8");
byte[] bslat = salt.getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(bslat);
md.update(data);
byte[] result = md.digest();
System.out.println(String.format("MD5加密:%0"+result.length+"x",new BigInteger(1,result)));
}
public static void getHmac(String text) throws Exception{
byte[] data = text.getBytes("UTF-8");
// 获取KeyGenerator实例
KeyGenerator keyGen = KeyGenerator.getInstance("HmacSHA1");
//获取一个随机的Key
SecretKey skey = keyGen.generateKey();
//获取一个Mac的实例
Mac mac = Mac.getInstance("HmacSHA1");
//先传入SecretKey,初始化
mac.init(skey);
//再计算输入数据的MD5
mac.update(data);
System.out.println(String.format("HmacSHA1加密:%0"+mac.doFinal().length*2+"x",new BigInteger(1,mac.doFinal())));
//打印SecretKey
byte[] key = skey.getEncoded();
System.out.println(String.format("Key:%0"+(key.length*2)+"x",new BigInteger(1,key)));
}
public static void main(String[] args) throws Exception{
String text = "hello 美女";
String salt = "stand up";
getMD5(text,salt);
getHmac(text);
}
}
## 2 代码示例
```#java
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import java.math.BigInteger;
public class SplitString {
public static byte[] hma(String hamcAlgorithm, SecretKey skey,byte[] data) throws Exception{
Mac mac = Mac.getInstance(hamcAlgorithm);
mac.init(skey);
mac.update(data);
return mac.doFinal();
}
public static void main(String[] args) throws Exception{
String[] algorithms = {"HmacMD5","HmacSHA1","HmacSHA256"};
String text = "hello world";
for(String s:algorithms){
KeyGenerator keyGen = KeyGenerator.getInstance(s);
SecretKey key = keyGen.generateKey();
byte[] data = text.getBytes("UTF-8");
byte[] reslut = hma(s,key,data);
System.out.println(String.format(s+":\t%0"+reslut.length*2+"x",new BigInteger(1,reslut))+"\t"+reslut.length);
}
}
}
<img src="https://img2018.cnblogs.com/blog/1418970/201905/1418970-20190510202600574-1584124211.png" width="500" />
## 3 总结:
* Hmac是把Key混入摘要的算法
* 可以配合MD5、SHA-1等摘要算法
* 摘要长度和原摘要算法长度相同