天天看點

Java MD5生成器

項目名:create_md5

項目語言:java swing;

建構工具:maven;

使用ide:eclipse

程式運作界面如下:

Java MD5生成器

功能:

(1)擷取指定檔案的md5值;

(2)擷取指定一段文本的md5值

說明:本文中,md5值使用十六進制位串表示。

如何擷取檔案的md5值呢?

Java MD5生成器

/** 

     * get md5 of one file:hex string,test ok! 

     *  

     * @param file 

     * @return : hex string 

     */  

    public static string getfilemd5(file file) {  

        if (!file.exists() || !file.isfile()) {  

            return null;  

        }  

        messagedigest digest = null;  

        fileinputstream in = null;  

        byte buffer[] = new byte[1024];  

        int len;  

        try {  

            digest = messagedigest.getinstance("md5");  

            in = new fileinputstream(file);  

            while ((len = in.read(buffer, 0, 1024)) != -1) {  

                digest.update(buffer, 0, len);  

            }  

            in.close();  

        } catch (exception e) {  

            e.printstacktrace();  

        biginteger bigint = new biginteger(1, digest.digest());  

        return bigint.tostring(16);  

    }  

/*** 

     * get md5 of one file!test ok! 

     * @param filepath 

     * @return 

    public static string getfilemd5(string filepath) {  

        file file = new file(filepath);  

        return getfilemd5(file);  

如何擷取一段文本的md5值呢?

Java MD5生成器

public static final char[] hexchar = { '0', '1', '2', '3', '4', '5', '6',  

            '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };  

public static byte[] digest(byte srcbytes[], string algorithm)  

            throws nosuchalgorithmexception {  

        messagedigest digest = messagedigest.getinstance(algorithm);  

        digest.update(srcbytes);  

        byte digestbytes[] = digest.digest();  

        return digestbytes;  

public static string getmd5(string source) throws nosuchalgorithmexception {  

        byte bytes[] = digest(source.getbytes(), "md5");  

        return tohexstring(bytes);  

     * convert byte array to hex(16) bit string 

     * @param byte[] 

     * @return hex(16) bit string 

    public static string tohexstring(byte[] b) {  

        stringbuilder sb = new stringbuilder(b.length * 2);  

        for (int i = 0; i < b.length; i++) {  

            sb.append(hexchar[(b[i] & 0xf0) >>> 4]);  

            sb.append(hexchar[b[i] & 0x0f]);  

        return sb.tostring();  

項目結構如下:

Java MD5生成器

繼續閱讀