Code Monkey home page Code Monkey logo

js-sha256's Introduction

js-sha256

Build Status Coverage Status CDNJS
NPM
A simple SHA-256 / SHA-224 hash function for JavaScript supports UTF-8 encoding.

Demo

SHA256 Online
SHA224 Online
SHA256 File Online
SHA225 File Online

Download

Compress
Uncompress

Installation

You can also install js-sha256 by using Bower.

bower install js-sha256

For node.js, you can use this command to install:

npm install js-sha256

Usage

You could use like this:

sha256('Message to hash');
sha224('Message to hash');

var hash = sha256.create();
hash.update('Message to hash');
hash.hex();

var hash2 = sha256.update('Message to hash');
hash2.update('Message2 to hash');
hash2.array();

// HMAC
sha256.hmac('key', 'Message to hash');
sha224.hmac('key', 'Message to hash');

var hash = sha256.hmac.create('key');
hash.update('Message to hash');
hash.hex();

var hash2 = sha256.hmac.update('key', 'Message to hash');
hash2.update('Message2 to hash');
hash2.array();

Node.js

If you use node.js, you should require the module first:

var sha256 = require('js-sha256');

or

var sha256 = require('js-sha256').sha256;
var sha224 = require('js-sha256').sha224;

or

const { sha256, sha224 } = require('js-sha256');

TypeScript

If you use TypeScript, you can import like this:

import { sha256, sha224 } from 'js-sha256';

RequireJS

It supports AMD:

require(['your/path/sha256.js'], function(sha256) {
// ...
});

Example

sha256(''); // e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
sha256('The quick brown fox jumps over the lazy dog'); // d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592
sha256('The quick brown fox jumps over the lazy dog.'); // ef537f25c895bfa782526529a9b63d97aa631564d5d789c2b765448c8635fb6c
sha224(''); // d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f
sha224('The quick brown fox jumps over the lazy dog'); // 730e109bd7a8a32b1cb9d9a09aa2325d2430587ddbc0c38bad911525
sha224('The quick brown fox jumps over the lazy dog.'); // 619cba8e8e05826e9b8c519c0a5c68f4fb653e8a3d8aa04bb2c8cd4c

// It also supports UTF-8 encoding
sha256('中文'); // 72726d8818f693066ceb69afa364218b692e62ea92b385782363780f47529c21
sha224('中文'); // dfbab71afdf54388af4d55f8bd3de8c9b15e0eb916bf9125f4a959d4

// It also supports byte `Array`, `Uint8Array`, `ArrayBuffer` input
sha256([]); // e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
sha256(new Uint8Array([211, 212])); // 182889f925ae4e5cc37118ded6ed87f7bdc7cab5ec5e78faef2e50048999473f

// Different output
sha256(''); // e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
sha256.hex(''); // e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
sha256.array(''); // [227, 176, 196, 66, 152, 252, 28, 20, 154, 251, 244, 200, 153, 111, 185, 36, 39, 174, 65, 228, 100, 155, 147, 76, 164, 149, 153, 27, 120, 82, 184, 85]
sha256.digest(''); // [227, 176, 196, 66, 152, 252, 28, 20, 154, 251, 244, 200, 153, 111, 185, 36, 39, 174, 65, 228, 100, 155, 147, 76, 164, 149, 153, 27, 120, 82, 184, 85]
sha256.arrayBuffer(''); // ArrayBuffer

Benchmark

jsPerf Benchmark

License

The project is released under the MIT license.

Contact

The project's website is located at https://github.com/emn178/js-sha256
Author: Chen, Yi-Cyuan ([email protected])

js-sha256's People

Contributors

dependabot[bot] avatar emn178 avatar nolsherry avatar olezhek avatar shiyuesong avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

js-sha256's Issues

Outdated typescript definition

Typescript claims that there is no default export when using import sha256 form 'js-sha256';.
The index.d.ts claims that only two named exports exists (sha256 and sha224) but this does not seem to be the case anymore as import * as sha from 'js-sha256'; shows named as well as a default export.
Trying to import { sha256, sha224 } from 'js-sha256'; fails as well, as the real export of this module is not an object containing these functions, but an objects that contains the default in on property and named exports inside another.
A workaround is to import * as sha from 'js-sha256'; and then use (sha as any).default(message), but this is considered bad practice as it's loosing the type information and requires low level interaction with the es-module system.

Different Result with sha256.hmac

Hello,

I have been testing sha256.hmac compared to other sources and noticed a discrepancy.
This library outputs a simple test like:
sha256.hmac('a','b'); // = 08de329931e295683776aa9a43529bd0b275286df3160300c49ba4e841833013
while online sources like here and here and the library CryptoJS output the same input as:
cb448b440c42ac8ad084fc8a8795c98f5b7802359c305eabd57ecdb20e248896

同学,您这个项目引入了22个开源组件,存在3个漏洞,辛苦升级一下

检测到 emn178/js-sha256 一共引入了22个开源组件,存在3个漏洞

漏洞标题:Growl命令执行漏洞
缺陷组件:[email protected]
漏洞编号:CVE-2017-16042
漏洞描述:Growl是一套支持Node.js的通知系统。
Growl 1.10.2之前版本中存在安全漏洞,该漏洞源于在将输入传递到shell命令之前,程序未能正确的对其进行过滤。攻击者可利用该漏洞执行任意命令。
国家漏洞库信息:https://www.cnvd.org.cn/flaw/show/CNVD-2018-24664
影响范围:(∞, 1.10.0)
最小修复版本:1.10.0
缺陷组件引入路径:[email protected]>[email protected]>[email protected]

另外还有3个漏洞,详细报告:https://mofeisec.com/jr?p=i17ed6

Hmac update question

I think It's more of a question than an issue because I am probably not using the library correctly. After I run update on the hmac second time, shouldn't the hash change? Why doesn't it and how would I properly use the update function? See example below.

var hash = sha256.hmac.create('mykey');
hash.update(mykey,'Message one to hash');
hash.hex() is ABC
hash.update(mykey,'Message two to hash');
hash.hex() is still ABC

Deprecate library and reccomend standardized APIs

Since the Web Crypto API is now widely supported both on the Web and Node.js this library serves little to no purpose in modern JavaScript development. This library is also very clearly no longer actively maintained.

Given these arguments I would like to propose this library be deprecated as follows:

  • Add a section to the README instructing users to use the Web Crypto API instead.
  • Deprecate all versions of the NPM package using npm deprecate.
  • Archive the repository on Github.

How fast is it compared to native ?

Here is a lib that use native implementation from browser and node.js for sha512 :
https://github.com/paulmillr/noble-ed25519/blob/master/index.ts#L849

Browser : https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest
Node : https://nodejs.org/api/crypto.html#crypto_crypto_createhash_algorithm_options

But with es module native compatibility issue. (you also have but i've handled them here : https://github.com/1000i100/js-sha256 but dropping, for now some coverage. That's why i haven't send pull-request )

Rollupjs build complains about the use of eval in this library.

(!) Use of eval is strongly discouraged
https://github.com/rollup/rollup/wiki/Troubleshooting#avoiding-eval
node_modules/js-sha256/src/sha256.js
84:
85: var nodeWrap = function (method, is224) {
86: var crypto = eval("require('crypto')");
^
87: var Buffer = eval("require('buffer').Buffer");
88: var algorithm = is224 ? 'sha224' : 'sha256';
...and 1 other occurrence
created dist/transactionmgmt.dev.js in 4.7s

[2018-06-21 10:33:00] waiting for changes...
screen shot 2018-06-21 at 10 35 13 am

Generates incorrect hash in some cases

It seems that js-sha256 produces incorrect hash for some inputs in the browser environment (issue does not reproduce in NodeJS environment).

I am currently using Chrome 120.0.6099.71.

Here is one input that produces incorrect hash:

Tehtäväsi on muotoilla teksti, jossa käyttäjälle suositellaan hänen henkilökohtaisiin tietoihinsa perustuen avioehdon tekemistä. Suosittelemme nimenomaan tätä tuotetta käyttäjän henkilökohtaisista tiedoista johtuen. Tuottamasi tekstin tulee olla lyhyt, persoonallinen, ymmärrettävä ja todenmukainen. Suositus perustuu seuraaviin seikkoihin:

Seikka 0: Avioehdon tekeminen on verohyötyjen vuoksi suositeltavaa, koska olet ilmaissut että haluat kuoleman tapauksessa turvata ensisijaisesti aviopuolisosi asemaa (ennemmin kuin lasten asemaa). Avioehdolla voit määrätä, että puolet kuolleen puolison omaisuudesta siirtyy verovapaasti leskelle.

Voit halutessasi hyödyntää seuraavia tietoja tekstin muotoilussa persoonallisemmaksi: Käyttäjällä on kumppani nimeltä PARTNER_NAME. Käyttäjällä on suurperhe. Käyttäjällä on lapsiperhe.

Puhuttele käyttäjää siihen sävyyn että tiedät jo mitä käyttäjä haluaa, koska hän on kertonut toiveistaan, ja niiden perusteella tehty suositus on ilmiselvä. Joten älä käytä epävarmoja ilmaisuja kuten "halutessasi", vaan kirjoita itsevarmoilla ilmaisuilla kuten "koska haluat". Älä tee oletuksia käyttäjän sukupuolesta, emme tiedä onko hän mies vai nainen. Älä käytä sanaa jälkikasvu, puhu ennemmin lapsesta tai lapsista riippuen onko lapsia yksi vai useampia. Älä puhuttele käyttäjää ensimmäisessä persoonassa, käytä ennemmin passiivimuotoa. Tekstin sävyn tulisi olla neutraalin asiallinen, ei melodramaattinen eikä leikkisä. Pysy totuudessa, älä keksi uusia seikkoja yllä listattujen lisäksi. Viittaa ihmisiin nimillä silloin kun se on mahdollista. Tekstin tulisi olla vain muutaman lauseen mittainen. Älä siis kirjoita pitkiä selityksiä äläkä kirjoita listoja. Tiivistä oleellinen tieto lyhyeksi ja persoonalliseksi tekstiksi.

The fastest way to reproduce is by copypasting the input to these SHA256 calculators and seeing that the calculated hashes are different:

The hash is calculated correctly until the character in position 1751 (the last "s" character in the last word of the string). For some reason the hash is calculated incorrectly at position 1751 (and, naturally, every position after that).

I tried to construct a shorter input example, but it seems that any change to the input before position 1751 causes the issue to disappear: add character, remove character, change character... any change and issue disappears.

Different output on online-tools and while using the lib

Screenshot from 2021-02-02 15-07-36

sha256.hex('b03cadd31554cdbe6e67fc0ad2f0ffeb8aae91de4f0657c3ba6fc11b94b85e46') === '182ee7d99a515fdd59d25d5d8a2a263b52097fd212e169f2df208a6c4b7e1c73'

why it gives 182ee7d99a515fdd59d25d5d8a2a263b52097fd212e169f2df208a6c4b7e1c73 instead of 2656b1039a88fbd83409795d31480d3090ec797488df19cbef2b70c69df87c29? am I using the library in the wrong way?

thank you

v0.3.0 -> v0.3.1 breaks builds

Hi,

since version 0.3.1 my builds no longer work.

var sha256 = require("js-sha256");
var sha = sha256("my string");
TypeError: '[object Object]' is not a function (evaluating 'sha256("my string")')

Breaking changes should be done in a major version, not a patch.

Use ArrayBuffer

Hi,

Thanks for the help on SHA 3. Could you also allow the use of ArrayBuffer?

Thanks

Ken

react-native is interpreted as node environment

Hi you try to determine if you are in a node environment by checking the process variable.
React native also has a standard process variable which looks like this (at least in my setup):

{ env: { NODE_ENV: 'development' } }	

You check in line 14

var NODE_JS = !root.JS_SHA256_NO_NODE_JS && typeof process == 'object' && process.versions && process.versions.node;

the problem is that both process.versions && process.versions.node are undefined so that evaluates somehow to true.
Maybe you can do a check

if (prossess.versions === undefined)
      NODE_JS = false;

or something.

Best regards Max

Crypto not found in React Native

React Native gives the following error: "Unable to resolve module 'crypto' from '/js-sha26/src/sha256.js': Module does not exist i the module map".

Using Salt

What should I do if I want to use salt?

Google Chrome 115.0.5790.102 produces incorrect SHA-256 hashes

I don't think this is a bug in this code but opening this issue to maybe help out someone else trying to debug this in the future:

When this library is used with Google Chrome 115.0.5790.102 (released on July 20 2023), it will produce correct hashes for a while and then after a certain number of hashes are computed, all future hash outputs will be incorrect.

This was seen on x86 and ARM machines running Linux and macOS.

Presumably this is a JIT bug in this particular version of Chrome. It is apparently fixed in 115.0.5790.110 which was released to stable channel 5 days later.

One of the test cases for HMAC is "wrong"

The following test case indicates that it is supposed to be using a Uint8Array for the secret, but is in fact using a ArrayBuffer:

testCases.sha224_hmac.Uint8Array = {
'da8f94de91d62154b55ea4e8d6eb133f6d553bcd1f1ba205b9488945': [
new ArrayBuffer(0),
'Hi There'
]
};

The sha256_hmac test properly uses a Uint8Array.

Avoid modifying the Array prototype?

Currently the code modifies the Array prototype by adding the __ARRAY__ property to it. Could this be avoided?

In one of my project it actually caused a hard to track down bug. 😄

Object.isArray() or a polyfill given here or something like lodash's _.isArray() can be used instead to detect whether an object is an array

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.