[feat][M]:新增MD5加密工具类

master
Romesum 5 years ago
parent 0f82695eed
commit 6caf2f815c

@ -0,0 +1,104 @@
package com.hzu.bookingsystem.utils;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 1.MD532
* 2.MD532
* 3.
* 4.Unicode
*/
public class MD5Util {
/**
* MD532
*
* @param string MD5
* @return
*/
public static String md5Encrypt32Upper(String string) {
byte[] hash;
try {
//创建一个MD5算法对象并获得MD5字节数组,16*8=128位
hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Huh, MD5 should be supported?", e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Huh, UTF-8 should be supported?", e);
}
//转换为十六进制字符串
StringBuilder hex = new StringBuilder(hash.length * 2);
for (byte b : hash) {
if ((b & 0xFF) < 0x10) hex.append("0");
hex.append(Integer.toHexString(b & 0xFF));
}
return hex.toString().toUpperCase();
}
/**
* MD532
*
* @param string MD5
* @return
*/
public static String md5Encrypt32Lower(String string) {
byte[] hash;
try {
//创建一个MD5算法对象并获得MD5字节数组,16*8=128位
hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Huh, MD5 should be supported?", e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Huh, UTF-8 should be supported?", e);
}
//转换为十六进制字符串
StringBuilder hex = new StringBuilder(hash.length * 2);
for (byte b : hash) {
if ((b & 0xFF) < 0x10) hex.append("0");
hex.append(Integer.toHexString(b & 0xFF));
}
return hex.toString().toLowerCase();
}
/**
*
*
* @param bytes
* @return
*/
public static String bytesToHex(byte[] bytes) {
StringBuffer hexStr = new StringBuffer();
int num;
for (int i = 0; i < bytes.length; i++) {
num = bytes[i];
if (num < 0) {
num += 256;
}
if (num < 16) {
hexStr.append("0");
}
hexStr.append(Integer.toHexString(num));
}
return hexStr.toString().toUpperCase();
}
/**
* Unicode
*/
public static String unicodeToString(String str) {
Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
Matcher matcher = pattern.matcher(str);
char ch;
while (matcher.find()) {
ch = (char) Integer.parseInt(matcher.group(2), 16);
str = str.replace(matcher.group(1), ch + "");
}
return str;
}
}
Loading…
Cancel
Save