001/** 002 * Copyright (c) 2022-2023, 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 021public class HashUtil { 022 private static final char[] HEX_DIGITS = "0123456789abcdef".toCharArray(); 023 024 public static String md5(String srcStr) { 025 return hash("MD5", srcStr); 026 } 027 028 public static String sha256(String srcStr) { 029 return hash("SHA-256", srcStr); 030 } 031 032 public static String hash(String algorithm, String srcStr) { 033 try { 034 MessageDigest md = MessageDigest.getInstance(algorithm); 035 byte[] bytes = md.digest(srcStr.getBytes(StandardCharsets.UTF_8)); 036 return toHex(bytes); 037 } catch (Exception e) { 038 throw new RuntimeException(e); 039 } 040 } 041 042 public static String toHex(byte[] bytes) { 043 StringBuilder ret = new StringBuilder(bytes.length * 2); 044 for (byte b : bytes) { 045 ret.append(HEX_DIGITS[(b >> 4) & 0x0f]); 046 ret.append(HEX_DIGITS[b & 0x0f]); 047 } 048 return ret.toString(); 049 } 050 051}