Initial project

This commit is contained in:
Timi
2025-07-12 12:45:46 +08:00
parent a87693cf37
commit abf09cee04
20 changed files with 2769 additions and 94 deletions

View File

@@ -0,0 +1,83 @@
package com.imyeyu.utils;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* @author 夜雨
* @version 2023-08-07 14:27
*/
public class Digest {
public static String md5(String data) throws NoSuchAlgorithmException {
return md5(data, StandardCharsets.UTF_8);
}
public static String md5(String data, Charset charset) throws NoSuchAlgorithmException {
return md5(data.getBytes(charset));
}
public static String md5(byte[] data) throws NoSuchAlgorithmException {
if (data == null || data.length == 0) {
return null;
}
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(data);
byte[] bytes = md5.digest();
char[] chars = new char[bytes.length * 2];
for (int i = 0, j = 0; i < bytes.length; i++) {
chars[j++] = Text.HEX_DIGITS_LOWER[bytes[i] >>> 4 & 0xF];
chars[j++] = Text.HEX_DIGITS_LOWER[bytes[i] & 0xF];
}
return new String(chars);
}
public static String sha1(String data) throws NoSuchAlgorithmException {
return sha1(data, StandardCharsets.UTF_8);
}
public static String sha1(String data, Charset charset) throws NoSuchAlgorithmException {
return sha1(data.getBytes(charset));
}
public static String sha1(byte[] bytes) throws NoSuchAlgorithmException {
MessageDigest sha = MessageDigest.getInstance("SHA");
sha.update(bytes);
return Text.byteToHex(sha.digest());
}
public static String sha256(String data) throws NoSuchAlgorithmException {
return sha256(data, StandardCharsets.UTF_8);
}
public static String sha256(String data, Charset charset) throws NoSuchAlgorithmException {
return sha256(data.getBytes(charset));
}
public static String sha256(byte[] bytes) throws NoSuchAlgorithmException {
MessageDigest sha = MessageDigest.getInstance("SHA-256");
sha.update(bytes);
return Text.byteToHex(sha.digest());
}
public static String sha512(String data) throws NoSuchAlgorithmException {
return sha512(data, StandardCharsets.UTF_8);
}
public static String sha512(String data, Charset charset) throws NoSuchAlgorithmException {
return sha512(data.getBytes(charset));
}
public static String sha512(byte[] bytes) throws NoSuchAlgorithmException {
MessageDigest sha = MessageDigest.getInstance("SHA-512");
BigInteger number = new BigInteger(1, sha.digest(bytes));
StringBuilder result = new StringBuilder(number.toString(16));
while (result.length() < 64) {
result.insert(0, "0");
}
return result.toString();
}
}