package com.shlanbao.tzsc.utils.tools;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* MD5加密工具类
*
@author Leejean
* @create 2014-6-24 下午04:13:41
*
* @author zhuguifei
* @update 2019-06-03
* @desc 添加SHA256加密
*/
public class MD5Util {
public static void main(String[] args) {
String s = "lanbaoit";
System.out.println(md5(s));
System.out.println("SHA256:" + SHA256(s));
}
/**
* md5加密
*
* @param str
* @return
*/
public static String md5(String str) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(str.getBytes());
byte[] byteDigest = md.digest();
int i;
StringBuffer buf = new StringBuffer("");
for (int offset = 0; offset < byteDigest.length; offset++) {
i = byteDigest[offset];
if (i < 0)
i += 256;
if (i < 16)
buf.append("0");
buf.append(Integer.toHexString(i));
}
// 32位加密
//return buf.toString();
// 16位的加密
return buf.toString().substring(8, 24);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
/**
* 传入文本内容,返回 SHA-256 串
*
* @param strText
* @return
*/
public static String SHA256(final String strText) {
return SHA(strText, "MD5");
}
/**
* 传入文本内容,返回 SHA-512 串
*
* @param strText
* @return
*/
public static String SHA512(final String strText) {
return SHA(strText, "SHA-512");
}
/**
* 字符串 SHA 加密
*
* @param
* @return
*/
private static String SHA(final String strText, final String strType) {
// 返回值
String strResult = null;
// 是否是有效字符串
if (strText != null && strText.length() > 0) {
try {
// SHA 加密开始
// 创建加密对象 并傳入加密類型
MessageDigest messageDigest = MessageDigest
.getInstance(strType);
// 传入要加密的字符串
messageDigest.update(strText.getBytes());
byte byteBuffer[] = messageDigest.digest();
StringBuffer strHexString = new StringBuffer();
// 遍歷 byte buffer
for (int i = 0; i < byteBuffer.length; i++) {
String hex = Integer.toHexString(0xff & byteBuffer[i]);
if (hex.length() == 1) {
strHexString.append('0');
}
strHexString.append(hex);
}
// 得到返回結果
strResult = strHexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
return strResult;
}
}