var result = "";
var reader = new FileReader();
reader.onload = function(event) {
result = CryptoJS.SHA256(event.target.result).toString();
};
reader.readAsBinaryString(tempFile);
The hash value of a file in JavaScript is 98a0996953e89a6d388057ae9168f004c9d1fb4ec3d863d1ab35fefe554bb214
public String sha256(String filepath) throws Exception {
MessageDigest md = MessageDigest.getInstance("SHA-256");
FileInputStream fis = new FileInputStream(filepath);
byte[] dataBytes = new byte[1024];
int nread = 0;
while ((nread = fis.read(dataBytes)) != -1) {
md.update(dataBytes, 0, nread);
}
byte[] mdbytes = md.digest();
/*String shaHex = DatatypeConverter.printHexBinary(mdbytes);*/
StringBuffer sb = new StringBuffer();
for (int i = 0; i < mdbytes.length; i++) {
sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
}
fis.close();
return sb.toString();
}
/* */ from the method you run
SHA256 hash = new SHA256();
System.out.println("java hash : "+hash.sha256(filePath+filename));
The hash value in java is f60dc63c2653b4f35dbf14ac5ad4e9a99e87f5af193b6b599e361c493d5d23a9
It comes out like this. How can I get the same value when the two are different?
cryptojs sha256 java javascript
jshell> import java.sequ
jshell> import java.seq
jshell> import java.security.*
jshell> public String sha256(String filepath) throws Exception {
...> MessageDigest md = MessageDigest.getInstance("SHA-256");
...> FileInputStream fis = new FileInputStream(filepath);
...>
...> byte[] dataBytes = new byte[1024];
...>
...> int nread = 0;
...> while ((nread = fis.read(dataBytes)) != -1) {
...> md.update(dataBytes, 0, nread);
...> }
...>
...> byte[] mdbytes = md.digest();
...>
...> /*String shaHex = DatatypeConverter.printHexBinary(mdbytes);*/
...> StringBuffer sb = new StringBuffer();
...> for (int i = 0; i < mdbytes.length; i++) {
...> sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
...> }
...> fis.close();
...> return sb.toString();
...> }
| | created method sha256(String)
jshell> sha256("/usr/bin/gcc")
$4 ==> "5aa1a5dbef17daf4563c88b4e891fecaa17f4557ff0f4cc824531c3a1d8a43ea"
*python
In [3]: import sys
In [4]: import hashlib
In [5]: BUF_SIZE = 65536
In [6]: sha2 = hashlib.sha256()
In [7]: with open('/usr/bin/gcc', 'rb') as f:
...: ...: while True:
...: ...: data = f.read(BUF_SIZE)
...: ...: if not data:break
...: ...: sha2.update(data)
In [9]: print("SHA2: {0}".format(sha2.hexdigest()))
SHA2: 5aa1a5dbef17daf4563c88b4e891fecaa17f4557ff0f4cc824531c3a1d8a43ea
The Java code written by the questioner is fine.
Check out how to use the jscrytojs library and look at the bug tracker in that library.
© 2024 OneMinuteCode. All rights reserved.