1. 程式人生 > >通過Java實現HMAC,將字串雜湊成為全部由字母組成的密文串

通過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"));
    }
}