MD5算法原理及Java實現

原文鏈接:MD5算法原理及Java實現
一、什麼是MD5算法?

MD5稱爲消息摘要算法(MD5 Message-Digest Algoritm),是被廣泛使用的密碼散列函數,可產生16位的hash value,

用於確保信息傳輸的完整一直性。

MD5輸入任意不同長度的信息,可固定輸出32-bit數據,最後聯合輸出固定的信息摘要。

二、MD5的功能?

1、一致性驗證,對一段信息產生摘要信息,以防止被篡改。無論任何形式的文件,都會產生一個獨一無二的MD5數據指紋,

我們經常在下載文件的時候用於文件比對。
2、數字簽名,對一端信息message(字符串)產生fingerprint(指紋),以防着被篡改。

三、MD5的特性?

1、長度固定:無論字符串長度,加密後的字符長度都相等,便於統計計算。

2、便於加密:無論字符串還是文件,正向加密過程便於開發者理解。

3、可多變性:兩個相近的字符串只要有細微的差別,所產生的密文完全是不一樣的。

4、不可逆性:知道正向加密,卻是無法算出逆向加密密碼,這樣大大提高了數據的安全性。

四、JAVA實現MD5?

1、字符串加密

//MD5-32位簽名算法
 //MD5-32位簽名算法
    public static String MD5Code(String source) {
        String resultStr = null;
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");//MessageDigest jdk 1.8數字簽名
            if (!"".equals(source) && null != source)
                resultStr = byteArrayToHexString(md5.digest(source.getBytes())); //字符串報文
            else
                return "數據源不可爲空!";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultStr;
    }

    // byte[]數組 轉換String
    private static String byteArrayToHexString(byte[] bytes) {
        StringBuffer resultStrBuff = new StringBuffer();
        for (int i = 0; i < bytes.length; i++)
            resultStrBuff.append(byteToHexString(bytes[i]));

        return resultStrBuff.toString();
    }

    //byte 轉換String
    private static String byteToHexString(byte bytes) {
        int n = bytes;
        if (n < 0)
            n += 256;
        int d1 = n / 16;//求整數
        int d2 = n % 16; //求餘數
        return hexDigits[d1] + hexDigits[d2];
    }

    //hex 16進製取值(取下標數)
    private static final String hexDigits[] =
            {"0", "1", "2", "3", "4", "5", "6", "7", "a", "b", "c", "d", "e", "f", "g", "h"};
"h"};

//可逆簽名方法編寫

//編寫可逆加密
    public static String encryption(String source) {
        char[] a = source.toCharArray();
        for (int i = 0; i < a.length; i++)
            a[i] = (char) (a[i] ^ 's');
        String str = new String(a);
        return str;
    }

    // 加密後解密
    public static String JM(String source) {
        char[] a = source.toCharArray();
        for (int i = 0; i < a.length; i++) {
            a[i] = (char) (a[i] ^ 't');
        }
        String str = new String(a);
        return str;
    }

以上便是Java對於MD5的簡單簽名算法。

面向開發過程,記錄學習之路。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章