Java的字符串md5加密和文件md5


1、字符串的md5加密

使用MessageDigest對字符串進行MD5算法的步驟是,先將字符串轉換成字節數組,在進行MD5算法,最后返回的也是一個字節數組,要我們自己轉成32位的字符串。

 

package com.yourcompany.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Encryption {
    public static String stringMd5(String input){
        try{
            //拿到一個MD5轉換器(如果想要SHA1加密參數換成"SHA1")
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            //輸入的字符串轉換成字節數組
            byte[] inputByteArray = input.getBytes();
            //inputByteArray是輸入字符串轉換得到的字節數組
            messageDigest.update(inputByteArray);
            //轉換並返回結果,也是字節數組,包含16個元素
            byte[] resultByteArray = messageDigest.digest();
            //字符數組轉換成字符串返回
            return byteArrayToHex(resultByteArray);
            
            
        }catch(NoSuchAlgorithmException e){
            return null;
        }
    }
    
    public static String byteArrayToHex(byte[] byteArray){
        //首先初始化一個字符數組,用來存放每個16進制字符
        char[] hexDigits = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
        //new一個字符數組,這個就是用來組成結果字符串的(解釋一下:一個byte是八位二進制,也就是2位十六進制字符)
        char[] resultCharArray = new char[byteArray.length*2];
        //遍歷字節數組,通過位運算(位運算效率高),轉換成字符放到字符數組中去
        int index = 0;
        for(byte b : byteArray){
            resultCharArray[index++] = hexDigits[b>>> 4 & 0xf];
            resultCharArray[index++] = hexDigits[b& 0xf];
        }
        
        //字符數組組合成字符串返回
        return new String(resultCharArray);
    }
    
}

 

 

2、文件MD5

對文件進行MD5也可以像字符串MD5一樣的,首先要把文件轉成字節數組,后面和字符串MD5完全一樣。

但是如果是一個特別大的文件,一下子把一個文件的數組全部讀到內存中,那么估計內存也吃不消。

對於大文件,可以使用DigestInputStream。

public static String fileMD5(String inputFile) throws IOException {

 

      // 緩沖區大小(這個可以抽出一個參數)

      int bufferSize = 256 * 1024;

      FileInputStream fileInputStream = null;

      DigestInputStream digestInputStream = null;

 

      try {

         // 拿到一個MD5轉換器(同樣,這里可以換成SHA1)

         MessageDigest messageDigest =MessageDigest.getInstance("MD5");

 

         // 使用DigestInputStream

         fileInputStream = new FileInputStream(inputFile);

         digestInputStream = new DigestInputStream(fileInputStream,messageDigest);

 

         // read的過程中進行MD5處理,直到讀完文件

         byte[] buffer =new byte[bufferSize];

         while (digestInputStream.read(buffer) > 0);

 

         // 獲取最終的MessageDigest

         messageDigest= digestInputStream.getMessageDigest();

 

         // 拿到結果,也是字節數組,包含16個元素

         byte[] resultByteArray = messageDigest.digest();

 

         // 同樣,把字節數組轉換成字符串

         return byteArrayToHex(resultByteArray);

 

      } catch (NoSuchAlgorithmException e) {

         return null;

      } finally {

         try {

            digestInputStream.close();

         } catch (Exception e) {

         }

         try {

            fileInputStream.close();

         } catch (Exception e) {

         }

      }

   }

上面的方法本人親測過大小約4G的文件,得出的MD5值和網上下載的一個MD5小工具得到的MD5值一樣,說明上面的方式沒有什么問題。不過取大文件的MD5很慢,4G的文件跑一下要一分鍾(I5處理器 6G內存 64位XP系統 本本)。

附1:我在網上還看到一種給文件MD5的方式

public static String getFileMD5String(File file) throws IOException{
 FileInputStream in = new FileInputStream(file);
 FileChannel ch =in.getChannel();
 MappedByteBuffer byteBuffer =ch.map(FileChannel.MapMode.READ_ONLY, 0,file.length());
 messagedigest.update(byteBuffer);
 return byteArrayToHex (messagedigest.digest());
}

我也嘗試過這樣的方式,但是如果文件大於2G,那么這種方式會出現異常。所以不推薦。

附2:測試文件MD5的main方法

public static void main(String[] args) {

  long startTime = System.currentTimeMillis();

  try {
    System.out.println(fileMD5("E:/軟件/VS2008ProEdition90DayTrialCHSX1435983.iso"));
  } catch (IOException e) {
    e.printStackTrace();
  }

  long endTime = System.currentTimeMillis();

  System.out.println((endTime - startTime)/1000);
}

 轉載:http://blog.csdn.net/xiao__gui/article/details/8148203

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM