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

java实现MD5加密算法的实例代码

程序员文章站 2024-02-17 09:45:22
复制代码 代码如下:package other; import java.security.messagedigest;import java.security.nosu...

复制代码 代码如下:

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"));
    }
}