md5值生成

版权声明:本文为博主原创文章,转载时请在文章最前方附上本文地址。 https://blog.csdn.net/qq_35033270/article/details/88558865

md5值生成

import java.security.MessageDigest;
import org.apache.log4j.Logger;
public class Md5Util {
	 /**使用Log4j打印日志*/
private static Logger logger = Logger.getLogger(Md5Util.class);
 /**
 * 生成md5
 * @param message the string to be encrypted
 * @return the encrypted md5
 */
public static String getMD5(String message) {
String md5str = "";
try {
//1 创建一个提供信息摘要算法的对象,初始化为md5算法对象
MessageDigest md = MessageDigest.getInstance("MD5");

//2 将消息变成byte数组
byte[] input = message.getBytes();

//3 计算后获得字节数组,这就是那128位了
byte[] buff = md.digest(input);

//4 把数组每一字节(一个字节占八位)换成16进制连成md5字符串
md5str = bytesToHex(buff);

} catch (Exception e) {
logger.debug(e.getMessage());
}
return md5str;
}


/**
 * 
 * @description //二进制转十六进制
 * @version 1.0
 * @param bytes to be changed
 * @return the md5 string
 */
public static String bytesToHex(byte[] bytes) {
StringBuffer md5str = new StringBuffer();
//把数组每一字节换成16进制连成md5字符串
int digital;
for (int i = 0; i < bytes.length; i++) {
digital = bytes[i];

if (digital < 0) {
digital &= 0xFF;
}
if (digital < 16) {
md5str.append("0");
}
md5str.append(Integer.toHexString(digital));
}
return md5str.toString().toUpperCase();
}
}

猜你喜欢

转载自blog.csdn.net/qq_35033270/article/details/88558865