MD5的相關知識

  MD5算法是一種消息摘要,用於提供消息的完整性保護。

  一  其實就是爲了保護文件傳輸的完整性,比如我們從網上下載的文件,如果其在傳輸過程中被篡改過的話,則我們所下載下來的文件的md5值和源文件肯定是不一樣的。

  二  涉及到我們的android項目裏的話,就是app在進行版本升級的時候,我們需要計算我們下載文件的md5值與服務器該文件的md5值進行比較,如果一樣則代表文件是完整的且沒有被修改過,反之則說明文件不完整,我們就需要重新下載一份。

接下來我們貼出關於文件和字符串MD5值計算的相關代碼:

package com.example.asiatravel.md5demo;

import android.util.Log;

import java.io.FileInputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;

/**
 * Created by kuangxiaoguo on 16/9/6.
 */
public class MessageDigestUtil {

    private static final String TAG = "TAG";

    /**
     * 計算字符串的MD5值
     *
     * @param data 要計算的字符串對應的字節數組
     * @return 字符串的MD5值
     */
    public static String encryptMD5(byte[] data) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(data);
            byte[] resultBytes = md5.digest();
            /*
            將字節數組轉化爲16進制
             */
            return ByteToHexUtil.fromByteToHex(resultBytes);
        } catch (Exception e) {
            Log.d(TAG, "encryptMD5: " + e.getMessage());
        }
        return null;
    }

    /**
     * 計算文件的MD5值
     *
     * @param path 文件路徑
     * @return 文件MD5值
     */
    public static String getFileMD5(String path) {
        try {
            FileInputStream fileInputStream = new FileInputStream(path);
            DigestInputStream dis = new DigestInputStream(fileInputStream, MessageDigest.getInstance("MD5"));
            byte[] buffer = new byte[1024];
            int read = dis.read(buffer, 0, 1024);
            while (read != -1) {
                read = dis.read(buffer, 0, 1024);
            }
            dis.close();
            fileInputStream.close();
            MessageDigest md5 = dis.getMessageDigest();
            return ByteToHexUtil.fromByteToHex(md5.digest());
        } catch (Exception e) {
            Log.d(TAG, "getFileMD5: " + e.getMessage());
        }
        return null;
    }
}

然後是把字節數組轉化爲16進制的工具類:

package com.example.asiatravel.md5demo;

/**
 * Created by kuangxiaoguo on 16/9/6.
 * <p/>
 * 將字節數組轉化爲16進制的工具類
 */
public class ByteToHexUtil {

    public static String fromByteToHex(byte[] resultBytes) {
        StringBuilder builder = new StringBuilder();
        for (byte resultByte : resultBytes) {
            if (Integer.toHexString(0xFF & resultByte).length() == 1) {
                builder.append(0).append(Integer.toHexString(0xFF & resultByte));
            } else {
                builder.append(Integer.toHexString(0xFF & resultByte));
            }
        }
        return builder.toString();
    }

}

總結:對於MD5值的計算並不難,但是要理解每行代碼到底是什麼意思,而不是死記代碼,這樣對於我們纔有真正的提高。另外如果大家有那裏不明白的地方可以留言或者發

郵件[email protected],這樣我們可以共同提高。


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