java hmac-sha1 hmac-sha256

2022-11-08  本文已影响0人  饱饱想要灵感
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;


/**
 * This class consists of utility method for encoding based on HmacSHA1 algorithm
 */
public class HmacDigestUtil {

    /**
     * Returns an encoded string based on HmacSHA1 algorithm
     * @param key Key used to encode the data
     * @param data The data to be encoded
     * @return an encoded string
     */
    public static String signHmacSHA1(String key, String data) throws Exception {
        byte[] signData = signHmacSHA1(key.getBytes(StandardCharsets.UTF_8), data.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(signData);
    }

    /**
     * Initializes the encoder and returns the encoded byte array
     * @param key Key used to encode the data
     * @param data The data to be encoded
     * @return an encoded byte array
     */
    private static byte[] signHmacSHA1(byte[] key, byte[] data) throws Exception {
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(new SecretKeySpec(key, "HmacSHA1"));
        return mac.doFinal(data);
    }

    /**
     * Returns the encoded string generated by HmacSHA256.
     * The output is a String of length 64.
     * (SHA256 -> 256bits -> 32 bytes -> 64 characters in hex number)
     * @param key
     * @param data
     * @return
     */
    public static String signHmacSha256ToHexString(String key, String data) throws Exception {
        byte[] signData = signHmacSha256(key.getBytes(StandardCharsets.UTF_8), data.getBytes(StandardCharsets.UTF_8));
        return toCoreUtilsString(signData);
    }

    

    /**
     * Returns the SHA256 MAC in byte array.
     *
     * @param key
     * @param data
     * @return
     */
    private static byte[] signHmacSha256(byte[] key, byte[] data) throws Exception {
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(key, "HmacSHA256"));
        return mac.doFinal(data);
    }
    
    /**
     * Converts bytes to Hex Strings.
     * Example: [10100000,00000000,00010011,00100100] -> [a0,00,13,24] -> "a0001324"
     * @param binaryData
     * @return
     */
    private static String toCoreUtilsString(byte[] binaryData) {
        if (binaryData == null) return null;
        if (binaryData.length == 0) return "";
        StringBuilder result = new StringBuilder();
        for (byte b: binaryData){
            result.append(String.format("%02x", b));
        }
        return result.toString();
    }

}
上一篇下一篇

猜你喜欢

热点阅读