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"; //algorithm name etc: hmacsha256, HMACSHA384, HMACSHA512, HMACMD5, (jdk does not provide HMACSHA224 algorithm implementation) 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)]", "") //if you want to see the generated key System.out.println ("BASE64 encoded key:" + encoderdigest); string content = "Generation Guru"; System.out.println ("PlainText: " + content); String hmac = calculaterfc2104hmac (content, encoderdigest); System.out.println ("Ciphertext: " + hmac);}} Final output:  BASE64 encoded key: LWFMHK3H0QMTOFLGJDZ5HWHHZ14ENEP7P7QXNCXVNXWQUWWJMCVA6CQWP3GUVKTE2ARSCZSF0LSARH9JXG plaintext: Beautiful cipher: 719e053be349ca02a721a3d6b509e84e21f7a0c5
This article is from the "Generation Guru" blog, please make sure to keep this source http://765682.blog.51cto.com/755682/1854038
Hmacsha and HMACMD5 encryption algorithm implementation