alex-zhang / crypto-js

Automatically exported from code.google.com/p/crypto-js
0 stars 0 forks source link

How do I use Sha256 on a file(binary file such as pdf, image, video, etc...) in javascript? #62

Closed GoogleCodeExporter closed 8 years ago

GoogleCodeExporter commented 8 years ago
What steps will reproduce the problem?
1. If I pass in binary message to generate SHA-256, it does not provide the 
correct hash. For example, I use a FileReader to read in a binary file(pdf, 
mp3, mp4, exe, etc...) data as a message to the SHA-256 function to create a 
hash.
2. Even if I pass it a base64 format value message, it also does not provide 
the correct hash.
3.

What is the expected output? What do you see instead?
I have the details of the expected output in stackoverflow:
http://stackoverflow.com/questions/13981832/how-do-i-use-sha256-on-a-filebinary-
file-such-as-images-in-javascript

What version of the product are you using? On what operating system?
CryptoJS v3.0.2

Please provide any additional information below.
Does the message we pass in have to be string? 
jsSHA(http://caligatio.github.com/jsSHA/) has a pretty nice function where   
the input message type can be specified(base64, text, hex). But it does not 
have Progressive Hashing. 

Original issue reported on code.google.com by ucrkart...@gmail.com on 24 Dec 2012 at 5:56

GoogleCodeExporter commented 8 years ago
When you pass a string to a hasher, it's converted to bytes using UTF-8. That's 
to ensure foreign characters are not clipped. Since you're working with binary 
data, you'll want to convert the string to bytes using Latin1.

sha256.update(CryptoJS.enc.Latin1.parse(evt.target.result));

Original comment by Jeff.Mott.OR on 24 Dec 2012 at 6:09

GoogleCodeExporter commented 8 years ago
Thanks Jeff! That fixed it. 

Original comment by ucrkart...@gmail.com on 24 Dec 2012 at 3:12

GoogleCodeExporter commented 8 years ago

Original comment by Jeff.Mott.OR on 26 Dec 2012 at 2:41

GoogleCodeExporter commented 8 years ago
I'm using the following javascript:
<script type="text/javascript">
function HashBinary(file) {
   var sha256 = CryptoJS.algo.SHA256.create();
   sha256.update(CryptoJS.enc.Latin1.parse(file));
   var hash = sha256.finalize();
   return hash;
}
</script>
Parameter "file" is an object from a ZIP file got with 
Scripting.FileSystemObject.GetFile in HTA/ASP script or stream from 
ADODB.Stream in same script.
In bove situations the hash is the same, but not the expected one.
And the line "sha256.update" in javascript has no effect. Same wrong hash is 
calcalated.
Am I doing something wrong?

Original comment by reinaldo...@gmail.com on 29 Jan 2013 at 5:12

GoogleCodeExporter commented 8 years ago
Hi, Reinaldo. Please provide a full page/script that I can use to reproduce the 
issue. Also let me know what browser and OS you're on, as well as what output 
you expect and what you see instead. Thanks.

Original comment by Jeff.Mott.OR on 29 Jan 2013 at 5:29