Java:高效计算大文件的 SHA-256 哈希值
我需要计算一个大文件(或其一部分)的SHA-256哈希值。我的实现工作正常,但它比C++的CryptoPP计算慢得多(25分钟,而~30GB文件为10分钟)。我需要的是C++和Java中类似的执行时间,因此哈希值几乎同时准备就绪。我也尝试了Bouncy Castle的实现,但它给了我同样的结果。以下是我如何计算哈希:
int buff = 16384;
try {
RandomAccessFile file = new RandomAccessFile("T:\\someLargeFile.m2v", "r");
long startTime = System.nanoTime();
MessageDigest hashSum = MessageDigest.getInstance("SHA-256");
byte[] buffer = new byte[buff];
byte[] partialHash = null;
long read = 0;
// calculate the hash of the hole file for the test
long offset = file.length();
int unitsize;
while (read < offset) {
unitsize = (int) (((offset - read) >= buff) ? buff : (offset - read));
file.read(buffer, 0, unitsize);
hashSum.update(buffer, 0, unitsize);
read += unitsize;
}
file.close();
partialHash = new byte[hashSum.getDigestLength()];
partialHash = hashSum.digest();
long endTime = System.nanoTime();
System.out.println(endTime - startTime);
} catch (FileNotFoundException e) {
e.printStackTrace();
}