001/*
002 *  Copyright (c) 2022-2025, Mybatis-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.mybatisflex.core.audit.http;
017
018import java.nio.charset.StandardCharsets;
019import java.security.MessageDigest;
020
021/**
022 * Hash 工具类。
023 */
024public class HashUtil {
025
026    private HashUtil() {
027    }
028
029    private static final char[] HEX_DIGITS = "0123456789abcdef".toCharArray();
030
031    public static String md5(String srcStr) {
032        return hash("MD5", srcStr);
033    }
034
035    public static String sha256(String srcStr) {
036        return hash("SHA-256", srcStr);
037    }
038
039    public static String hash(String algorithm, String srcStr) {
040        try {
041            MessageDigest md = MessageDigest.getInstance(algorithm);
042            byte[] bytes = md.digest(srcStr.getBytes(StandardCharsets.UTF_8));
043            return toHex(bytes);
044        } catch (Exception e) {
045            throw new RuntimeException(e);
046        }
047    }
048
049    public static String toHex(byte[] bytes) {
050        StringBuilder ret = new StringBuilder(bytes.length * 2);
051        for (byte b : bytes) {
052            ret.append(HEX_DIGITS[(b >> 4) & 0x0f]);
053            ret.append(HEX_DIGITS[b & 0x0f]);
054        }
055        return ret.toString();
056    }
057
058}