首页 > 代码库 > HmacSHA 和HmacMd5 加密算法实现
HmacSHA 和HmacMd5 加密算法实现
package com.asiainfo.encryption.s2; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SignatureException; import java.util.Formatter; import javax.crypto.KeyGenerator; import javax.crypto.Mac; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import sun.misc.BASE64Encoder; public class HmacSignature { private static final String HMAC_SHA1_ALGORITHM = "HMACSHA1"; //算法名称 etc: HMACSHA256、HMACSHA384、HMACSHA512、HMACMD5、(jdk 没有提供HMACSHA224的算法实现) private static String toHexString(byte[] bytes) { Formatter formatter = new Formatter(); for (byte b : bytes) { formatter.format("%02x", b); } String hexString = formatter.toString(); formatter.close(); return hexString; } public static String calculateRFC2104HMAC(String data, String key) throws SignatureException, NoSuchAlgorithmException, InvalidKeyException { SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM); Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM); mac.init(signingKey); return toHexString(mac.doFinal(data.getBytes())); } public static String calculateRFC2104HMAC(String data, byte[] key) throws SignatureException, NoSuchAlgorithmException, InvalidKeyException { SecretKeySpec signingKey = new SecretKeySpec(key, HMAC_SHA1_ALGORITHM); Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM); mac.init(signingKey); return toHexString(mac.doFinal(data.getBytes())); } public static void main(String[] args) throws Exception { KeyGenerator generator = KeyGenerator.getInstance(HMAC_SHA1_ALGORITHM); SecretKey key = generator.generateKey(); byte[] digest = key.getEncoded(); BASE64Encoder encoder = new BASE64Encoder(); String encoderDigest = encoder.encodeBuffer(digest); encoderDigest = encoderDigest.replaceAll("[^(A-Za-z0-9)]", ""); //如果想看到生成的密钥 System.out.println("Base64编码后的密钥:" + encoderDigest); String content = "一代宗师"; System.out.println("明文: " + content); String hmac = calculateRFC2104HMAC(content, encoderDigest); System.out.println("密文: " + hmac); } } 最终输出: Base64编码后的密钥:lwfmhK3H0qmTOfLGjDZ5HwHhz14enep7P7qXncxvNXWqUWWJMCvA6cqWP3GuvKtE2ArscZSF0lSaRH9jXg 明文: 美女 密文: 719e053be349ca02a721a3d6b509e84e21f7a0c5
本文出自 “一代宗师” 博客,请务必保留此出处http://765682.blog.51cto.com/755682/1854038
HmacSHA 和HmacMd5 加密算法实现
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。