java实现MD5加密算法的实例代码
package other;
import java.security.messagedigest;
import java.security.nosuchalgorithmexception;
/*
* md5 算法
*/
public class md5 {
// 全局数组
private final static string[] strdigits = { "0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
public md5() {
}
// 返回形式为数字跟字符串
private static string bytetoarraystring(byte bbyte) {
int iret = bbyte;
// system.out.println("iret="+iret);
if (iret < 0) {
iret += 256;
}
int id1 = iret / 16;
int id2 = iret % 16;
return strdigits[id1] + strdigits[id2];
}
// 返回形式只为数字
private static string bytetonum(byte bbyte) {
int iret = bbyte;
system.out.println("iret1=" + iret);
if (iret < 0) {
iret += 256;
}
return string.valueof(iret);
}
// 转换字节数组为16进制字串
private static string bytetostring(byte[] bbyte) {
stringbuffer sbuffer = new stringbuffer();
for (int i = 0; i < bbyte.length; i++) {
sbuffer.append(bytetoarraystring(bbyte[i]));
}
return sbuffer.tostring();
}
public static string getmd5code(string strobj) {
string resultstring = null;
try {
resultstring = new string(strobj);
messagedigest md = messagedigest.getinstance("md5");
// md.digest() 该函数返回值为存放哈希值结果的byte数组
resultstring = bytetostring(md.digest(strobj.getbytes()));
} catch (nosuchalgorithmexception ex) {
ex.printstacktrace();
}
return resultstring;
}
public static void main(string[] args) {
md5 getmd5 = new md5();
system.out.println(getmd5.getmd5code("000000"));
}
}
上一篇: Kotlin实现静态方法