java版:
package tom; import java.security.MessageDigest; import javax.crypto.KeyGenerator; import javax.crypto.Mac; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; /** * 基础加密组件 * @version 1.0 */ public class Hmacmd5 { /** * MAC算法可选以下多种算法 * * <pre> * HmacMD5 * HmacSHA1 * HmacSHA256 * HmacSHA384 * HmacSHA512 * </pre> */ public static final String KEY_MAC = "HmacMD5"; /** * HMAC加密 * * @param data * @param key * @return * @throws Exception */ public static byte[] encryptHMAC(byte[] data, String key) throws Exception { SecretKey secretKey = new SecretKeySpec(key.getBytes(), KEY_MAC); Mac mac = Mac.getInstance(secretKey.getAlgorithm()); mac.init(secretKey); return mac.doFinal(data); } /*byte数组转换为HexString*/ public static String byteArrayToHexString(byte[] b) { StringBuffer sb = new StringBuffer(b.length * 2); for (int i = 0; i < b.length; i++) { int v = b[i] & 0xff; if (v < 16) { sb.append('0'); } sb.append(Integer.toHexString(v)); } return sb.toString(); } public static void main(String[] args)throws Exception{ String inputStr = "{"name":"zhangsan"}"; byte[] inputData = inputStr.getBytes(); String key = "laidefa"; System.out.println(Hmacmd5.byteArrayToHexString(Hmacmd5.encryptHMAC(inputData, key))); } }
输出结果:
2cbb94ce78b35e4030851c4d40dacf12
PS:关于加密解密感兴趣的朋友还可以参考本站在线工具:
文字在线加密解密工具(包含AES、DES、RC4等):
http://tools.jb51.net/password/txt_encode
MD5在线加密工具:
http://tools.jb51.net/password/CreateMD5Password
在线散列/哈希算法加密工具:
http://tools.jb51.net/password/hash_encrypt
在线MD5/hash/SHA-1/SHA-2/SHA-256/SHA-512/SHA-3/RIPEMD-160加密工具:
http://tools.jb51.net/password/hash_md5_sha
在线sha1/sha224/sha256/sha384/sha512加密工具: