加密mac算法
import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.binary.Hex; import org.apache.commons.codec.digest.HmacAlgorithms; import org.apache.commons.codec.digest.HmacUtils; import javax.crypto.KeyGenerator; import javax.crypto.Mac; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Objects; public /** * MAC 算法测试 */ class MacTest { public static void main(String[] args) throws NoSuchAlgorithmException, DecoderException, InvalidKeyException { // 待加密字符 String originalStr = "yaochunhui123456"; System.out.println(String.format("待加密字符: %s", originalStr)); // 已加密字符 String alreadyDigestStr = "7720C2EEFE4F1037B006025ECECBEF49"; System.out.println(String.format("已加密字符: %s", alreadyDigestStr)); /* jdk 实现 */ // 初始化 KeyGenerator, jdk 提供 HmacMD5、HmacSHA1、HmacSHA256、HmacSHA384和 HmacSHA512 四种算法 // KeyGenerator keyGenerator = KeyGenerator.getInstance("HmacMD5"); // 产生密钥 // SecretKey secretKey = keyGenerator.generateKey(); // 默认密钥 // byte[] defaultKey = secretKey.getEncoded(); // 自定义密钥 byte[] myKey = Hex.decodeHex(new char[]{'b','b','b','b','b','b','b','b','b','b'}); // 还原密钥 SecretKey restoreSecretKey = new SecretKeySpec(myKey, "HmacMD5"); // 实例化 MAC Mac mac = Mac.getInstance(restoreSecretKey.getAlgorithm()); // 初始化 MAC mac.init(restoreSecretKey); //执行摘要 byte[] hmacMD5Bytes = mac.doFinal(originalStr.getBytes()); String encodeHexString = Hex.encodeHexString(hmacMD5Bytes).toUpperCase(); System.out.println(String.format("%s 加密结果:%s", originalStr, encodeHexString)); System.out.println(String.format("验证结果:%b", Objects.equals(encodeHexString, alreadyDigestStr))); /* apache 实现 */ // HmacMD5 HmacUtils hmacMd5 = new HmacUtils(HmacAlgorithms.HMAC_MD5, myKey); String apacheHmacMd5 = hmacMd5.hmacHex(originalStr.getBytes()).toUpperCase(); System.out.println(String.format("%s 加密结果:%s", originalStr, apacheHmacMd5)); System.out.println(String.format("验证结果:%b", Objects.equals(apacheHmacMd5, alreadyDigestStr))); // HmacSHA1 HmacUtils hmacSha1 = new HmacUtils(HmacAlgorithms.HMAC_SHA_1, KeyGenerator.getInstance(HmacAlgorithms.HMAC_SHA_1.getName()).generateKey().getEncoded()); String apacheHmacHex1 = hmacSha1.hmacHex(originalStr.getBytes()).toUpperCase(); System.out.println(String.format("%s 加密结果:%s", originalStr, apacheHmacHex1)); // HmacSHA256 HmacUtils hmacSha256 = new HmacUtils(HmacAlgorithms.HMAC_SHA_256, KeyGenerator.getInstance(HmacAlgorithms.HMAC_SHA_256.getName()).generateKey().getEncoded()); String apacheHmacSha256 = hmacSha256.hmacHex(originalStr.getBytes()).toUpperCase(); System.out.println(String.format("%s 加密结果:%s", originalStr, apacheHmacSha256)); // HmacSHA384 , 类似上面 // HmacSHA512, 类似上面 } }