Java中的mac计算
作者:互联网
2009-12-04
报文鉴别在身份认证中占重要位置,是认证系统的一个重要环节,在金融和商业系统中广泛应用。
报文鉴别常用报文鉴别码(Message Authentication Code,即MAC)作为鉴别的基础,
其基本原理是:用一个密钥((private Key))生成一个小数据块附加在要传输的报文后面。这种技术是假定通讯双方共享一个密钥K,当通讯的一方要给另一方传输数据M时,通过特定的算法计算出该报文M的MAC=F(K,M),这里的F就是指鉴别运算函数,然后报文数据M和MAC一起传送给另一方。当另一方收到数据时,先用同样的算法F计算MAC,和传输过来的MAC进行比较,如果相同,则认为数据是正确的。 鉴别函数常被认为是加密算法的一种,但是区别在于它不用于逆运算,有一定的安全性。 通常对于不同的应用系统采用各自特定的鉴别函数,这样在一定程度上保证了数据的安全性。
从j2sdk1.4以后,java提供了类javax.crypto.Mac类报文鉴别
view plaincopy to clipboardprint?
byte[] macData = "this is a mac test".getBytes(); //get a instance of Mac, using HmacMD5 algorithm
Mac mac = Mac.getInstance("HmacMD5"); //init the IV of the algorithm, 8 bytes. may read from file
byte[] ivInitKey = { 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07 };
IvParameterSpec spec = new IvParameterSpec(ivInitKey); // the secrete key bytes of the Mac validation, May read from file too
byte[] keyBytes = { 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f }; //generate the secrete Key Object using secrete bytes and DESede algorithm
SecretKey key = new SecretKeySpec(keyBytes, "DESede"); // init Mac mac.init(key, spec);
byte[] macCode = mac.doFinal(macData);
byte[] macData = "this is a mac test".getBytes(); //get a instance of Mac, using HmacMD5 algorithm
Mac mac = Mac.getInstance("HmacMD5"); //init the IV of the algorithm, 8 bytes. may read from file
byte[] ivInitKey = { 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07 };
IvParameterSpec spec = new IvParameterSpec(ivInitKey); // the secrete key bytes of the Mac validation, May read from file too
byte[] keyBytes = { 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f }; //generate the secrete Key Object using secrete bytes and DESede algorithm
SecretKey key = new SecretKeySpec(keyBytes, "DESede"); // init Mac mac.init(key, spec);
byte[] macCode = mac.doFinal(macData);
macCode 就是生成的Mac,用同样的密钥能产生同样的mac。
通讯双方只要保证用同样的密钥就能保证得到同样的Mac,达到报文验证的目的。
看来看去,这和网络上常用的checksum原理是一样的。
-
相关推荐
专题
+ 收藏
+ 收藏
+ 收藏
+ 收藏
+ 收藏
最新数据
相关文章
拒绝硬编码!利用 Java SPI 打造一个可插拔的代码解析器
给 Spring Boot 接口加了幂等保护:Token 机制 + 结果缓存,一个注解搞定
一站式了解接口防刷(限流)的基本操作
ThreadForge v1.1.0 发布:让 Java 并发更接近 Go 的开发体验
各版本JDK对比:JDK 21 特性详解
JVM 内存溢出排查
LangChain4j Prompt 提示词工程
彻底重绘Spring Boot性能版图,资源占用缩减80%
百度智能云模型接入
CompletableFuture深度解析:异步编程与任务编排的实现
AI精选
