MAC (Message Authentication Code,消息认证码算法)
需要将密钥发送到对方,对方用该密钥进行摘要处理,进行摘要验证。
KeyGenerator keyGenerator= KeyGenerator.getInstance("HmacMd5");
SecretKey secretKey=KeyGenerator.generator();
byte[] key=secretKey.getEncoded();
SecretKey seretKey= new SecretKeySpec(key, "HmacMD5");
Mac mc=Mac.getInstance(secretKey.getAlgorithm());
mac.init(secretKey);
byte[] data=mac.doFinal(data);
public class MACode
{
//产生密钥
public static byte[]
initHmacMD5Key() throws Exception{
KeyGenerator keyGenerator=KeyGenerator. getInstance("HmacMD5");
// KeyGenerator keyGenerator=KeyGenerator.getInstance("HmacSHA1");
// KeyGenerator keyGenerator=KeyGenerator.getInstance("HmacSHA256");
// KeyGenerator keyGenerator=KeyGenerator.getInstance("HmacSHA384");
// KeyGenerator keyGenerator=KeyGenerator.getInstance("HmacSHA512");
SecretKey secretKey=keyGenerator.generateKey();
return secretKey.getEncoded();
}
//进行消息摘要
public static byte[]
encodeHmacMD5(byte[] data, byte[]
key) throws Exception{
//还原密钥
SecretKey secretKey= new SecretKeySpec(key,"HmacMD5" );
// SecretKey secretKey=new SecretKeySpec(key,"HmacSHA1");
// SecretKey secretKey=new SecretKeySpec(key,"HmacSHA256");
// SecretKey secretKey=new SecretKeySpec(key,"HmacSHA384");
// SecretKey secretKey=new SecretKeySpec(key,"HmacSHA512");
//实例化mac
Mac mac=Mac. getInstance(secretKey.getAlgorithm());
//初始化mac
mac.init(secretKey);
//返回消息摘要
return mac.doFinal(data);
}
public static final void main(String[]
args) throws Exception{
String str= "MAC消息摘要" ;
//初始化密钥
byte[]
b=initHmacMD5Key();
//获取消息摘要
byte[]
data=encodeHmacMD5(str.getBytes(), b);
System. out.println(new String(Hex.encode(data))); //进行十六进制处理
}
}