昨天加密一個電影,總報錯。原來是用MappedByteBuffer 文件大於2G,那麼這種方式會出現異常。
下面是解決方案:
注意 1: MD5是常用的加密算法,也經常用於校驗信息完整,如文件的完整性。用術語講,MD5是一種消息摘要算法(Message Digest Algorithm)。另外還有一種常用的消息摘要算法SHA1。如果想了解這些的話,可以去百度百科:MD5、SHA1、消息摘要算法。
Java已經實現了MD5、SHA1算法。利用java.security.MessageDigest類就可以獲取字符串和文件的MD5以及SHA1結果。
注意 2: RandomAccessFile本身不帶緩衝讀寫,和FileInputStream、FileOutputStream等一樣,直接按字節讀寫時,性能不可接受;
· 使用MappedByteBuffer讀寫,固然性能會得到極大提升;其實只要自己處理緩衝,性能都會有非常大的提升,比如以下兩種方式(見下記代碼)中第一種使用了MappedByteBuffer,第二種自己進行緩衝,對於12M的文件,後者的效率甚至高於前者。
· BufferedXXXX之類的緩衝流,如果僅使用默認的buffer size,性能不一定最優,要權衡不同情況各種因素設置大小。
1.字符串的MD5(下面的代碼有詳細註釋)
// 輸入的字符串轉換成字節數組
byte[] inputByteArray = input.getBytes();
// inputByteArray是輸入字符串轉換得到的字節數組
messageDigest.update(inputByteArray);
// 轉換並返回結果,也是字節數組,包含16個元素
byte[] resultByteArray = messageDigest.digest();
// 字符數組轉換成字符串返回
return byteArrayToHex(resultByteArray);
} catch (NoSuchAlgorithmException e) {
return null;
}
}
//下面這個函數用於將字節數組換成成16進制的字符串
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位十六進制字符(2的8次方等於16的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);
從上面代碼可以看出,使用MessageDigest對字符串進行MD5算法的步驟是,先將字符串轉換成字節數組,在進行MD5算法,最後返回的也是一個字節數組,要我們自己轉成32位的字符串。
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);
}