天天看點

Android加密之MD5方式前言簡介使用

前言

由于安全性考慮,需要把sign中的key值以及其他的參數進行MD5方式簽名加密,可以有效的保護應用程式的資料

簡介

MD5即Message-Digest Algorithm 5(資訊-摘要算法5),用于確定資訊傳輸完整一緻。是計算機廣泛使用的雜湊算法之一(又譯摘要算法、雜湊演算法),主流程式設計語言普遍已有MD5實作。将資料(如漢字)運算為另一固定長度值,是雜湊算法的基礎原理,MD5的前身有MD2、MD3和MD4。

MD5算法具有以下特點:

1、壓縮性:任意長度的資料,算出的MD5值長度都是固定的。

2、容易計算:從原資料計算出MD5值很容易。

3、抗修改性:對原資料進行任何改動,哪怕隻修改1個位元組,所得到的MD5值都有很大差別。

4、強抗碰撞:已知原資料和其MD5值,想找到一個具有相同MD5值的資料(即僞造資料)是非常困難的。

MD5的作用是讓大容量資訊在用數字簽名軟體簽署私人密鑰前被”壓縮”成一種保密的格式(就是把一個任意長度的位元組串變換成一定長的十六進制數字串)。

MD5常見用途

  • 登陸密碼保護時将密碼進行MD5加密再上傳到資料庫,可以防止被密碼被劫持破解。如密碼是123456,如果明文上傳,被人擷取後能輕易盜取賬号,如果用md5加密後,它變成”49ba59abbe56e057”,這樣即使被劫持,也難以将這串字元反譯成123456
  • 檢驗檔案完整性

    網絡傳輸檔案時,受到網絡環境的影響,有時會發生檔案傳輸不完整的現象。這個時候常見的方法就是用md5校驗碼。如果兩個檔案的md5一樣,那麼檔案就下載下傳完整了,如果不一樣說明下載下傳不完成。

使用

MD5加密是不可逆的(現在已經可以被破解了,更多資訊請自行上網搜尋),加密後字元串可取16位或32位。一定注意,MD5加密要區分大小寫,否則加密出來的結果不同。

/**
 * Created by ${zk} on 2018/4/25 0025.
 * 歡迎每一天
 */

public class MD5sign {
    private static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
            '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

    public static String getBytesMD5(byte[] bytes) {
        try {

            // 獲得MD5摘要算法的 MessageDigest 對象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");

            // 使用指定的位元組更新摘要
            mdInst.update(bytes);

            // 獲得密文
            byte[] md = mdInst.digest();

            // 把密文轉換成十六進制的字元串形式
            int j = md.length;
            char str[] = new char[j * ];
            int k = ;
            for (int i = ; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>>  & ];
                str[k++] = hexDigits[byte0 & ];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 傳回字元串的32位MD5值
     *
     * @param s
     *            字元串
     * @return str MD5值
     */
    public final static String getStringMD5(String s) {
        return getBytesMD5(s.getBytes());
    }

    /**
     * 傳回字元串的16位MD5值
     *
     * @param s
     *            字元串
     * @return str MD5值
     */
    public final static String getStringMD5_16(String s) {
        return getStringMD5(s).substring(, );
    }

    public final static String getBitmapMD5(Bitmap bm) {
        return getBytesMD5(bitmapToBytes(bm));
    }

    public final static String getBitmapMD5_16(Bitmap bm) {
        return getBytesMD5(bitmapToBytes(bm)).substring(, );
    }

    public static byte[] bitmapToBytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, , baos);
        return baos.toByteArray();
    }

    /**
     * 加密檔案 
     * @param file  
     * @return 視訊 音樂
     */
    public static String md5ForFile(File file){
        int buffersize = ;
        FileInputStream fis = null;
        DigestInputStream dis = null;

        try {
            //建立MD5轉換器和檔案流
            MessageDigest messageDigest =MessageDigest.getInstance("MD5");
            fis = new FileInputStream(file);
            dis = new DigestInputStream(fis,messageDigest);

            byte[] buffer = new byte[buffersize];
            //DigestInputStream實際上在流處理檔案時就在内部就進行了一定的處理
            while (dis.read(buffer) > );

            //通過DigestInputStream對象得到一個最終的MessageDigest對象。
            messageDigest = dis.getMessageDigest();

            // 通過messageDigest拿到結果,也是位元組數組,包含16個元素
            byte[] array = messageDigest.digest();
            // 同樣,把位元組數組轉換成字元串
            StringBuilder hex = new StringBuilder(array.length * );
            for (byte b : array) {
                if ((b & ) < ){
                    hex.append("0");
                }
                hex.append(Integer.toHexString(b & ));
            }
            return hex.toString();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}