Java tutorial
//package com.java2s; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; public class Main { private static final char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; public static String encryptHmacMD5ToString(String data, String key) { return encryptHmacMD5ToString(data.getBytes(), key.getBytes()); } public static String encryptHmacMD5ToString(byte[] data, byte[] key) { return bytes2HexString(encryptHmacMD5(data, key)); } private static String bytes2HexString(byte[] bytes) { if (bytes == null) return null; int len = bytes.length; if (len <= 0) return null; char[] ret = new char[len << 1]; for (int i = 0, j = 0; i < len; i++) { ret[j++] = hexDigits[bytes[i] >>> 4 & 0x0f]; ret[j++] = hexDigits[bytes[i] & 0x0f]; } return new String(ret); } public static byte[] encryptHmacMD5(byte[] data, byte[] key) { return hmacTemplate(data, key, "HmacMD5"); } private static byte[] hmacTemplate(byte[] data, byte[] key, String algorithm) { if (data == null || data.length == 0 || key == null || key.length == 0) return null; try { SecretKeySpec secretKey = new SecretKeySpec(key, algorithm); Mac mac = Mac.getInstance(algorithm); mac.init(secretKey); return mac.doFinal(data); } catch (InvalidKeyException | NoSuchAlgorithmException e) { e.printStackTrace(); return null; } } }