如何在JavaScript中使用SHA256上的文件(二进制文件如图片)? [英] How do I use Sha256 on a file(binary file such as images) in javascript?

查看:254
本文介绍了如何在JavaScript中使用SHA256上的文件(二进制文件如图片)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做一个JavaScript文件SHA256。我用的FileReader(HTML5)在一个文件中读取。我用的是readAsBinaryString函数中的FileReader中的图像文件通过。然后在FileReader.onload功能我在evt.target.result传递给SHA256方法中的 CryptoJs API 。我能够顺利拿到一个哈希值,但它是不正确的。当我通过在一个文本文件,它工作正常,但没有图像文件。

code(应该能够在code在Firefox下面复制到一个HTML文件并运行它 - preSS的整个文件按钮):

 <风格>
  #byte_content {
    保证金:为5px 0;
    最大高度:100像素;
    溢出-Y:汽车;
    溢出 - X:隐藏;
  }
  #byte_range {的margin-top:5像素; }
< /风格><输入类型=文件ID =文件NAME =文件/>读取的字节:
<跨度类=readBytesButtons>
  &所述按钮数据startbyte =0的数据endbyte =4&GT 1-5&下; /按钮>
  <按钮数据startbyte =5数据endbyte =14> 6-15< /按钮>
  <按钮数据startbyte =6数据endbyte =7> 7-8< /按钮>
  <按钮和GT;整个文件< /按钮>
< / SPAN>
< D​​IV ID =byte_range>< / DIV>< BR>
< D​​IV ID =byte_content>< / DIV>< BR>
< D​​IV ID =crypto_sha256>< / DIV>&所述; SCRIPT SRC =HTTP://crypto-js.google$c$c.com/svn/tags/3.0.2/build/rollups/sha256.js>&下; /脚本>
&LT;脚本src=\"http://crypto-js.google$c$c.com/svn/tags/3.0.2/build/components/enc-base64-min.js\"></script>
&LT;脚本&GT;  VAR SHA256;  功能readBlob(opt_startByte,opt_stopByte){    var中的文件=的document.getElementById('文件')的文件。
    如果(!files.length){
      警报(请选择一个文件!');
      返回;
    }    var文件=文件[0];
    VAR开始= parseInt函数(opt_startByte)|| 0;
    VAR停止= parseInt函数(opt_stopByte)|| file.size - 1;    VAR读卡器=新的FileReader();    //如果我们使用onloadend,我们需要检查readyState的。
    reader.onloadend =功能(EVT){
      如果(evt.target.readyState == FileReader.DONE){// DONE == 2
        的document.getElementById('byte_content')的textContent = evt.target.result。
        的document.getElementById('byte_range')。的textContent =
            ['读取的字节:,启动+ 1, - ,停+ 1,
             '的',file.size,字节文件']加入('');        // **更新的解决方案:自二进制数据,需要将消息从字符串转换为使用的Latin1字节**
            sha256.update(CryptoJS.enc.Latin1.parse(evt.target.result));        变种散列= sha256.finalize();        。的document.getElementById('crypto_sha256')的textContent = ['SHA-256:',哈希]。加入('');
      }
    };    VAR BLOB = file.slice(起动,停止+ 1);
    reader.readAsBinaryString(BLOB);
  }  document.querySelector('。readBytesButtons')。的addEventListener('点击',功能(EVT){
    如果(evt.target.tagName.toLowerCase()=='按钮'){
      VAR startByte = evt.target.getAttribute('数据startbyte');
      VAR endByte = evt.target.getAttribute('数据endbyte');      SHA256 = CryptoJS.algo.SHA256.create();      readBlob(startByte,endByte);
    }
  },FALSE);
&LT; / SCRIPT&GT;

样输出:


  1. 测试文本文件:


    • 将生成的Javascript SHA256:结果
      78cb5e86455dc8e3bc20fe17e0213a938281216d57b31f8307f5bca67c37bb09

    • SHA256通过cygwin的同一文件生成:

      $ sha256sum Phillips.txt
      78cb5e86455dc8e3bc20fe17e0213a938281216d57b31f8307f5bca67c37bb09 * SomeTestFile.txt


  2. 测试二进制文件(PDF):


    • 将生成的Javascript SHA256:

      57f93c1d20a8ad8ade984a1d9756c1a40600bd8a7527601945c4e0b5e042c605

    • SHA256通过cygwin的同一文件生成:

      $ sha256sum烟雾\\探测器\\ Brochure.pdf
      57f93c1d20a8ad8ade984a1d9756c1a40600bd8a7527601945c4e0b5e042c605 *烟雾探测器Brochure.pdf



解决方案

下面是找到了一个简单的解决方案:的 HTTPS://$c$c.google.com/p/crypto-js/issues/detail ID = 62


  

当你传递一个字符串到散列器,它转换为使用UTF-8字节。这是确保外国字符不裁剪。既然你处理二进制数据,你会希望将字符串转换为使用的Latin1字节。


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

I am trying to do a Sha256 on a file in Javascript. I used FileReader(HTML5) to read in a file. I use the readAsBinaryString function in the FileReader to pass in the images file. Then on the FileReader.onload function I pass in the evt.target.result to the SHA256 method in the CryptoJs API. I am able to successfully get a hash value but it is not correct. When I pass in a text file, it works fine but not image file.

Code(Should be able to copy the code below to a HTML file and run it on firefox - press the "entire file" button):

<style>
  #byte_content {
    margin: 5px 0;
    max-height: 100px;
    overflow-y: auto;
    overflow-x: hidden;
  }
  #byte_range { margin-top: 5px; }
</style>

<input type="file" id="files" name="file" /> Read bytes: 
<span class="readBytesButtons">
  <button data-startbyte="0" data-endbyte="4">1-5</button>
  <button data-startbyte="5" data-endbyte="14">6-15</button>
  <button data-startbyte="6" data-endbyte="7">7-8</button>
  <button>entire file</button>
</span>
<div id="byte_range"></div><BR>
<div id="byte_content"></div><BR>
<div id="crypto_sha256"></div>

<script src="http://crypto-js.googlecode.com/svn/tags/3.0.2/build/rollups/sha256.js"></script>
<script src="http://crypto-js.googlecode.com/svn/tags/3.0.2/build/components/enc-base64-min.js"></script>
<script>

  var sha256;

  function readBlob(opt_startByte, opt_stopByte) {

    var files = document.getElementById('files').files;
    if (!files.length) {
      alert('Please select a file!');
      return;
    }

    var file = files[0];
    var start = parseInt(opt_startByte) || 0;
    var stop = parseInt(opt_stopByte) || file.size - 1;

    var reader = new FileReader();

    // If we use onloadend, we need to check the readyState.
    reader.onloadend = function(evt) {
      if (evt.target.readyState == FileReader.DONE) { // DONE == 2
        document.getElementById('byte_content').textContent = evt.target.result;
        document.getElementById('byte_range').textContent = 
            ['Read bytes: ', start + 1, ' - ', stop + 1,
             ' of ', file.size, ' byte file'].join('');

        //**UPDATED SOLUTION: Since its binary data, the message needs to be converted from string to bytes using Latin1**
            sha256.update(CryptoJS.enc.Latin1.parse(evt.target.result));

        var hash = sha256.finalize();

        document.getElementById('crypto_sha256').textContent = ['SHA-256: ', hash].join('');
      }
    };

    var blob = file.slice(start, stop + 1);
    reader.readAsBinaryString(blob);
  }

  document.querySelector('.readBytesButtons').addEventListener('click', function(evt) {
    if (evt.target.tagName.toLowerCase() == 'button') {
      var startByte = evt.target.getAttribute('data-startbyte');
      var endByte = evt.target.getAttribute('data-endbyte');

      sha256 = CryptoJS.algo.SHA256.create();

      readBlob(startByte, endByte);
    }
  }, false);
</script>

Sample outputs:

  1. Testing a "text" file:

    • SHA256 generated by Javascript:
      78cb5e86455dc8e3bc20fe17e0213a938281216d57b31f8307f5bca67c37bb09
    • SHA256 generated by cygwin on the same file:
      $ sha256sum Phillips.txt 78cb5e86455dc8e3bc20fe17e0213a938281216d57b31f8307f5bca67c37bb09 *SomeTestFile.txt
  2. Testing a "binary" file(pdf):

    • SHA256 generated by Javascript:
      57f93c1d20a8ad8ade984a1d9756c1a40600bd8a7527601945c4e0b5e042c605
    • SHA256 generated by cygwin on the same file:
      $ sha256sum Smoke\ Detector\ Brochure.pdf 57f93c1d20a8ad8ade984a1d9756c1a40600bd8a7527601945c4e0b5e042c605 *Smoke Detector Brochure.pdf

解决方案

Here is a simple solution found : https://code.google.com/p/crypto-js/issues/detail?id=62

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));

这篇关于如何在JavaScript中使用SHA256上的文件(二进制文件如图片)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆