Roberto Milani
Roberto Milani

Reputation: 790

Calculate SHA-256 hash and B64 of a file in JavaScript

what is the simplest way to calculate the SHA-256 of a file in JavaScript? (using the File API of W3C)

Once I have the sha-256 hash of this file, I need to generate the base64 of this hash?

What libraries do you suggest me to do that?

thanks in advance

Upvotes: 1

Views: 6721

Answers (2)

CODeeerrrrrrrr
CODeeerrrrrrrr

Reputation: 598

Have you thought of using CryptoJS

CryptoJS is a growing collection of standard and secure cryptographic algorithms implemented in JavaScript using best practices and patterns. They are fast, and they have a consistent and simple interface.

CryptoJS

Basically you can include components/lib-typedarrays-min.js and then do the following in code.

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

    var wordArray = CryptoJS.lib.WordArray.create(e.target.result);
    var hash = CryptoJS.SHA256(wordArray);
  }
};

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

I haven't tested the above solution but it should work fine.

Upvotes: 4

Alexander.It
Alexander.It

Reputation: 187

OpenSSL is a widely used tool for cryptography

Upvotes: -5

Related Questions