001/*
002 *  Copyright (c) 2023-2026, Agents-Flex (fuhai999@gmail.com).
003 *  <p>
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *  <p>
008 *  http://www.apache.org/licenses/LICENSE-2.0
009 *  <p>
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016package com.agentsflex.core.util;
017
018import javax.crypto.Mac;
019import javax.crypto.spec.SecretKeySpec;
020import java.nio.charset.StandardCharsets;
021import java.security.MessageDigest;
022import java.util.Base64;
023
024public class HashUtil {
025    private static final char[] HEX_DIGITS = "0123456789abcdef".toCharArray();
026    private static final char[] CHAR_ARRAY = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
027
028    public static String md5(String srcStr) {
029        return hash("MD5", srcStr);
030    }
031
032
033    public static String sha256(String srcStr) {
034        return hash("SHA-256", srcStr);
035    }
036
037    public static String hmacSHA256ToBase64(String content, String secret) {
038        try {
039            Mac hmacSHA256 = Mac.getInstance("HmacSHA256");
040            SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
041            hmacSHA256.init(secretKey);
042            byte[] bytes = hmacSHA256.doFinal(content.getBytes(StandardCharsets.UTF_8));
043            return Base64.getEncoder().encodeToString(bytes);
044        } catch (Exception e) {
045            throw new RuntimeException(e);
046        }
047    }
048
049    public static String hash(String algorithm, String srcStr) {
050        try {
051            MessageDigest md = MessageDigest.getInstance(algorithm);
052            byte[] bytes = md.digest(srcStr.getBytes(StandardCharsets.UTF_8));
053            return bytesToHex(bytes);
054        } catch (Exception e) {
055            throw new RuntimeException(e);
056        }
057    }
058
059    public static String bytesToHex(byte[] bytes) {
060        StringBuilder ret = new StringBuilder(bytes.length * 2);
061        for (byte aByte : bytes) {
062            ret.append(HEX_DIGITS[(aByte >> 4) & 0x0f]);
063            ret.append(HEX_DIGITS[aByte & 0x0f]);
064        }
065        return ret.toString();
066    }
067
068
069
070}