我需要计算一个大文件(或其中的一部分)的 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();
}