package com.kkb.misc.util;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Tool {
public static String getMD5(String text, String salt,String algorithm) {
try {
MessageDigest instance = MessageDigest.getInstance(algorithm!=null?algorithm:"MD5");
instance.update(text.getBytes("UTF-8"));
if (salt != null) {
instance.update(salt.getBytes("UTF-8"));
}
byte[] digests = instance.digest();
StringBuilder sb = new StringBuilder();
//字节转16进制
for (byte digest : digests) {
String hex = Integer.toHexString(digest & 0xFF);
if (hex.length() < 2) {
sb.append(0);
}
sb.append(hex);
}
//转字符串
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String getMD5(String text) {
return getMD5(text,null);
}
public static String getMD5(String text,String salt) {
return getMD5(text,salt,null);
}
public static void main(String[] args) {
System.out.println(getMD5("abc"));
System.out.println(getMD5("abc","akjKJHKJAJKSHJKAHSJANJNJANS"));
System.out.println(getMD5("abc","akjKJHKJAJKSHJKAHSJANJNJANS","SHA-256"));
System.out.println(getMD5("abc",null,"SHA-512"));
}
}
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Tool {
public static String getMD5(String text, String salt,String algorithm) {
try {
MessageDigest instance = MessageDigest.getInstance(algorithm!=null?algorithm:"MD5");
instance.update(text.getBytes("UTF-8"));
if (salt != null) {
instance.update(salt.getBytes("UTF-8"));
}
byte[] digests = instance.digest();
StringBuilder sb = new StringBuilder();
//字节转16进制
for (byte digest : digests) {
String hex = Integer.toHexString(digest & 0xFF);
if (hex.length() < 2) {
sb.append(0);
}
sb.append(hex);
}
//转字符串
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String getMD5(String text) {
return getMD5(text,null);
}
public static String getMD5(String text,String salt) {
return getMD5(text,salt,null);
}
public static void main(String[] args) {
System.out.println(getMD5("abc"));
System.out.println(getMD5("abc","akjKJHKJAJKSHJKAHSJANJNJANS"));
System.out.println(getMD5("abc","akjKJHKJAJKSHJKAHSJANJNJANS","SHA-256"));
System.out.println(getMD5("abc",null,"SHA-512"));
}
}