欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

MD5加密

程序员文章站 2024-03-19 09:33:04
...
/**
* md5 common class<br>
* MD5.java
* @author <br>
* 2007/11/19 11:51:59
*/
public class MD5 {

/**
* MD5 instance class
*/
private static MD5 instance = null;

// MD5
private MessageDigest _md5 = null;

/**
* MD5 instance get.
* @return MD5 instance
*/
public static MD5 getInstance() {
if (instance == null) {
instance = new MD5();
}
return instance;
}

/**
* get md5F<br>
* MD5.java<br>
*/
private MD5() {
try {
_md5 = MessageDigest.getInstance("MD5");
} catch (Exception e) {

}
}

/**
* do md5 <br>
* @param str
* string<br>
* @return md5Str MD5 string<br>
*/
public String getMD5Str(String str) {
char[] charArray = str.toCharArray();
byte[] byteArray = new byte[charArray.length];

for (int i = 0; i < charArray.length; i++) {
byteArray[i] = (byte) charArray[i];
}

byte[] md5Bytes = _md5.digest(byteArray);

StringBuffer hexValue = new StringBuffer();

int val = 0;

for (int i = 0; i < md5Bytes.length; i++) {
val = ((int) md5Bytes[i]) & 0xff;

if (val < 16) {
hexValue.append("0");
}

hexValue.append(Integer.toHexString(val));
}

return hexValue.toString();
}
}
相关标签: Java