md5加密字符串和文件

1,MD5簡(jiǎn)介

1)Message Digist Algorithm 5(消息摘要算法); SHA(Secure hash algorithm)安全hash算法。
2)Java已經(jīng)實(shí)現(xiàn)了MD5、SHA1算法。java.security.MessageDigest,String和文件的MD5以及SHA1結(jié)果。the array of bytes for the resulting hash value.
3)md5是一個(gè)固定長(zhǎng)度128比特(bit)的串1和0的組合,md5的32位表示使用16進(jìn)制表示二進(jìn)制,md5的16位表示32位表示去掉前8位和后8位

2,MD5加密字符串

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

    public static String md5String(String input) throws Exception {
        MessageDigest md = MessageDigest.getInstance("md5");
        byte[] inputBytes = input.getBytes();
        byte[] resultByte = md.digest(inputBytes);

        int length = resultByte.length;
        char[] result = new char[length * 2];

        int index = 0;
        for(int i = 0; i < length; i++){
            int val = resultByte[i];//轉(zhuǎn)換成int類型
            if(val < 0){
                val = val + 256;//負(fù)數(shù)使用補(bǔ)碼表示,eg: -1 + 256,等效于只取負(fù)數(shù)補(bǔ)碼的低8位(原byte類型)。
            }

            result[index++] = HEX[val/16];//使用除k取整法轉(zhuǎn)成16
            result[index++] = HEX[val % 16];
        }

        return result.toString();
    }

3,MD5加密文件

public static String md5File(String path) throws Exception{
        MessageDigest md = MessageDigest.getInstance("md5");
        File file = new File(path);
        InputStream inputStream = new FileInputStream(file);

        DigestInputStream digestInputStream = new DigestInputStream(inputStream, md);
        byte[] buffer =new byte[256 * 1024];
        while (digestInputStream.read(buffer) > 0){
            md = digestInputStream.getMessageDigest();
        }

        byte[] resultByte = md.digest();
        int length = resultByte.length;
        char[] result = new char[length * 2];

        int index = 0;
        for(int i = 0; i < length; i++){
            result[index++] = HEX[resultByte[i] >>> 4 & 0xf];//使用位運(yùn)算來進(jìn)行16進(jìn)制轉(zhuǎn)換
            result[index++] = HEX[resultByte[i] & 0xf];
        }

        return result.toString();
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 這篇文章主要講述在Mobile BI(移動(dòng)商務(wù)智能)開發(fā)過程中,在網(wǎng)絡(luò)通信、數(shù)據(jù)存儲(chǔ)、登錄驗(yàn)證這幾個(gè)方面涉及的加密...
    雨_樹閱讀 3,039評(píng)論 0 6
  • 概述 之前一直對(duì)加密相關(guān)的算法知之甚少,只知道類似DES、RSA等加密算法能對(duì)數(shù)據(jù)傳輸進(jìn)行加密,且各種加密算法各有...
    Henryzhu閱讀 3,218評(píng)論 0 14
  • 小紅的朋友在裝修新居,近200平米的大房子。這下小紅起勁啊!竟然陪著買起了紅木。已經(jīng)結(jié)伴著去了紅木廠好多次! 為了...
    天使小魚兒閱讀 302評(píng)論 5 9
  • title: RetrofitUtils的工具類date: 2016-10-31 10:33:27tags: Ut...
    _蘇芳_閱讀 1,340評(píng)論 0 1
  • 一位患者到傳說中的免費(fèi)醫(yī)院,廣播提示:“您好!您不需要掛號(hào)、排隊(duì)!”患者說感覺眼睛看不清楚,廣播提示患者上二...
    政先生閱讀 423評(píng)論 0 2

友情鏈接更多精彩內(nèi)容