I am trying to make same result with Java in the javascript using CryptoJs. But I am failed many times. I found the CryptoJs to generate Hash value in the javascript recently . But It was defficult to make same result between javascript and java. I want to get hash value (checksum) from zip or xls ,doc . And the Java application have to check if it has same hash value or not. Does anyone know whats going wrong on my javascript?
====== java source ==========
public static String getFileHashSHA256(String fileName) throws Exception {
int buff = 16384;
RandomAccessFile file = new RandomAccessFile(fileName, "r");
MessageDigest hashSum = MessageDigest.getInstance("SHA-256");
byte[] buffer = new byte[buff];
byte[] partialHash = null;
long read = 0;
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();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < partialHash.length; i++) {
sb.append(Integer.toString((partialHash[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
result hash value : 2f3512d3caad7b43f0036bafa7c80e78e9fca6a253857d24b1c38dc5cdab1399
========= javascript source ==============
var fileToLoad = document.getElementById("fileToLoad").files[0];
var fileReader = new FileReader();
fileReader.readAsBinaryString(fileToLoad);
fileReader.onload = function(fileLoadedEvent)
{
var hash = CryptoJS.SHA256(fileLoadedEvent.target.result).toString();
console.log(hash);
};
result hash value : cc7cf3ed59fb26a43d2596e54c48bced09ad22bff68e2cb5a1ea7cc80b48387d
The both hash value is diffrent even though it bring from a same zip file.