import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.springframework.util.StringUtils;
public class MD5 {
private static final String ALGORITHM = "MD5";
public MD5() {
}
/**md5的UTF-8编码加密.
* @param text 待加密的文本
* @return 加密后统一转成大写的文本
* @version v1.0.0
*/
public static String encrypt(String text) {
byte[] hash;
try {
MessageDigest digest = MessageDigest.getInstance(ALGORITHM);
hash = digest.digest(text.getBytes("UTF-8"));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
StringBuilder hex = new StringBuilder(hash.length * 2);
for (byte b : hash) {
if ((b & 0xFF) < 0x10)
hex.append("0");
hex.append(Integer.toHexString(b & 0xFF));
}
String md5 = hex.toString();
md5 = md5.toUpperCase();
return md5;
}
/**md5的UTF-8编码加密.
* @param text 待加密的文本
* @param key 校验字符串
* @return 加密后统一转成大写的文本
* @version v1.0.0
*/
public static String encrypt(String text, String key) {
if(StringUtils.isEmpty(key)){
return null;
}
return encrypt(new StringBuilder(text).append(key).toString());
}
public static void main(String args[]) {
System.out.println(encrypt("中国", "123"));
System.out.println(encrypt("12345611"));
System.out.println(encrypt("123456","11"));
}
}