- package cn.itcast.gz;
- import javax.crypto.KeyGenerator;
- import javax.crypto.Mac;
- import javax.crypto.SecretKey;
- /**
- * Mac算法是带有密钥的消息摘要算法比MD5相对来说要更安全些,实现起来分为两步:
- * 1、构建密钥
- * 2、执行消息摘要
- *
- */
- public class MACTest {
- public static void main(String[] args) throws Exception{
- //初始化KeyGenerator
- KeyGenerator keyGenerator = KeyGenerator.getInstance("HmacMD5");
- //产生密钥
- SecretKey secretKey = keyGenerator.generateKey();
- //得到密钥
- byte[] key = secretKey.getEncoded();
- //实例化Mac
- Mac mac = Mac.getInstance(secretKey.getAlgorithm());
- //初始化Mac
- mac.init(secretKey);
- //执行消息摘要 data是摘要后的结果
- byte[] data = mac.doFinal("要摘要的".getBytes());
- System.out.println(bytes2HexString(data));
- }
- /**
- *把字节数组转换为16进制的形式
- * @param b
- * @return
- */
- public static String bytes2HexString(byte[] b) {
- String ret = "";
- for (int i = 0; i < b.length; i++) {
- String hex = Integer.toHexString(b[ i ] & 0xFF);
- if (hex.length() == 1) {
- hex = '0' + hex;
- }
- ret += hex.toUpperCase();
- }
- return ret;
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/130120148491.html
来源: http://www.codesnippet.cn/detail/130120148491.html