Java HMAC_SHA256实现

发布于:2024-04-09 ⋅ 阅读:(89) ⋅ 点赞:(0)

HMAC_SHA256在PHP中可以通过系统函数hash_hmac实现

$hash = hash_hmac('sha256', "abcdefg", "123");

java中就要麻烦一点


import org.apache.commons.codec.binary.Hex;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class EncryptUtil { 
    /**
     * @param plainStr 需要加密的字符串
     * @param key
     * @return 加密后的字符串
     */
    public static String hmacsha256(String plainStr, String key) {
        SecretKeySpec secretKey = new
                SecretKeySpec(key.getBytes(Charset.forName("UTF-8")),
                "HmacSHA256");
        Mac mac = null;
        try {
            mac = Mac.getInstance(secretKey.getAlgorithm());
            mac.init(secretKey);
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            e.printStackTrace();
        }

        byte digest[] = mac.doFinal(plainStr.getBytes(Charset.forName("UTF-8")));
        return new StringBuilder().append(byte2HexStr(digest)).toString();
    }

    public static String byte2HexStr(byte array[]) {
        return array != null ? new String(Hex.encodeHex(array)) : null;
    }
    public static void main(String[] args) {
        String hash = EncryptUtil.hmacsha256("abcdefg", "123");
        System.out.println(hash);
    }
}

网站公告

今日签到

点亮在社区的每一天
去签到