hmac
HMAC是密钥相关的哈希运算消息认证码,HMAC运算利用哈希算法,以一个密钥和一个消息为输入,生成一个消息摘要作为输出
测试JAVA8中不支持HmacSHA384.HmacSHA512
使用apache - package org.apache.commons.codec.digest 包中 DigestUtils 也提供了丰富的MD5,SHA1等加密方法
public class signatureTest { String type = "HmacMD5,HmacSHA1,HmacSHA224,HmacSHA256"; //HmacSHA384.HmacSHA512 @Test public void testSign1() throws NoSuchAlgorithmException { String secret = "ndE2jdZNFixH9G6Aidsfyf7lYT3PxW"; String message = "channel"; String hash = null; try { String[] aa = type.split(","); for(String type : aa){ System.out.println("type:" + type); Mac sha256_HMAC = Mac.getInstance(type); SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), type); sha256_HMAC.init(secret_key); byte[] bytes = sha256_HMAC.doFinal(message.getBytes()); System.out.println(byteArrayToHex1(bytes)); System.out.println(byteArrayToHex2(bytes)); System.out.println("-----------------------------------------------------"); } } catch (Exception e) { System.out.println("Error HmacSHA256 ===========" + e.getMessage()); } } private static String byteArrayToHex1(byte[] bytes) { return new HexBinaryAdapter().marshal(bytes); } private static String byteArrayToHex2(byte[] bytes) { StringBuilder hs = new StringBuilder(); String stmp; for (int n = 0; bytes!=null && n < bytes.length; n++) { stmp = Integer.toHexString(bytes[n] & 0XFF); if (stmp.length() == 1) hs.append('0'); hs.append(stmp); } return hs.toString().toUpperCase(); } }