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