版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/SpiderManSun/article/details/84942250
以下Java代码可以将任何字符串通过HMAC哈希,并输出成由大写的A到P组成的密文字符串。
public class HMAC {
private final static String KEY_MAC = "HMACMD5";
/**
* 全局数组
*/
private final static String[] hexDigits = { "A", "B", "C", "D", "E", "F","G", "H", "I", "J", "K", "L",
"M", "N", "O", "P" };
/**
* BASE64 加密
* @param key 需要加密的字节数组
* @return 字符串
* @throws Exception
*/
public static String encryptBase64(byte[] key) throws Exception {
return (new BASE64Encoder()).encodeBuffer(key);
}
/**
* BASE64 解密
* @param key 需要解密的字符串
* @return 字节数组
* @throws Exception
*/
public static byte[] decryptBase64(String key) throws Exception {
return (new BASE64Decoder()).decodeBuffer(key);
}
/**
* HMAC加密
* @param data 需要加密的字节数组
* @param key 密钥
* @return 字节数组
*/
public static byte[] encryptHMAC(byte[] data, String key) {
SecretKey secretKey;
byte[] bytes = null;
try {
secretKey = new SecretKeySpec(decryptBase64(key), KEY_MAC);
Mac mac = Mac.getInstance(secretKey.getAlgorithm());
mac.init(secretKey);
bytes = mac.doFinal(data);
} catch (Exception e) {
e.printStackTrace();
}
return bytes;
}
/**
* HMAC加密
* @param data 需要加密的字符串
* @param key 密钥
* @return 字符串
*/
public static String encryptHMAC(String data, String key) throws UnsupportedEncodingException {
if (data==null||data.equals("")) {
return null;
}
byte[] bytes = encryptHMAC(data.getBytes(), key);
//return new String(bytes,"UTF-8");
return byteArrayToHexString(bytes);
}
private static String byteToHexString(byte b) {
int ret = b;
//System.out.println("ret = " + ret);
if (ret < 0) {
ret += 256;
}
int m = ret / 16;
int n = ret % 16;
return hexDigits[m] + hexDigits[n];
}
private static String byteArrayToHexString(byte[] bytes) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
sb.append(byteToHexString(bytes[i]));
}
return sb.toString();
}
/**
* 测试方法
* @param args
*/
public static void main(String[] args) throws Exception {
String word = "This is a test";
System.out.println(encryptHMAC(word, "123"));
}
}