本文主要是介绍通过Java实现HMAC,将字符串哈希成为全部由字母组成的密文串,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
以下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"));}
}
这篇关于通过Java实现HMAC,将字符串哈希成为全部由字母组成的密文串的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!