Giter VIP home page Giter VIP logo

crypto-hash's Introduction

crypto-hash

Tiny hashing module that uses the native crypto API in Node.js and the browser

Useful when you want the same hashing API in all environments. My cat calls it isomorphic.

In Node.js it uses node:crypto, while in the browser it uses window.crypto.

The browser version is only ~300 bytes minified & gzipped.

When used in the browser, it must be in a secure context (HTTPS).

This package is for modern browsers. Internet Explorer is not supported.

Install

npm install crypto-hash

Usage

import {sha256} from 'crypto-hash';

console.log(await sha256('🦄'));
//=> '36bf255468003165652fe978eaaa8898e191664028475f83f506dabd95298efc'

API

sha1(input, options?)

sha256(input, options?)

sha384(input, options?)

sha512(input, options?)

Returns a Promise<string> with a Hex-encoded hash.

In Node.js, the operation is executed using worker_threads. A thread is lazily spawned on the first operation and lives until the end of the program execution. It's unrefed, so it won't keep the process alive.

SHA-1 is insecure and should not be used for anything sensitive.

input

Type: string ArrayBuffer ArrayBufferView

options

Type: object

outputFormat

Type: string
Values: 'hex' | 'buffer'
Default: 'hex'

Setting this to buffer makes it return an ArrayBuffer instead of a string.

Related

  • hasha - Hashing in Node.js made simple

crypto-hash's People

Contributors

bendingbender avatar chocolateboy avatar davixyz avatar derhuerst avatar mwanago avatar richienb avatar sindresorhus avatar stroncium 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

crypto-hash's Issues

Critical dependency: the request of a dependency is an expression

I'm getting this warning when I run npm run watch.

I can't solve it or figure out what it means. Any help would be appreciated.

WARNING in ./node_modules/crypto-hash/index.js 7:9-22
Critical dependency: the request of a dependency is an expression

webpack compiled with 1 warning

Laravel + Vue and just added an SDK, where I am guessing this dependency came from.

Crypto: Subtle Digest Alg not an Object

We use this library on a project that has to support legacy web engines (connected TVs) and on Chrome 38 we get errors like

TypeError: Failed to execute 'digest' on 'SubtleCrypto': parameter 1 ('algorithm') is not an object.

By patching with

diff --git a/browser.js b/browser.js
index 0b4337488bdf198c626d6787c3ccb09222d8b171..6165eaf420fce74837f938cb40bcb2ccf07a3c9f 100644
--- a/browser.js
+++ b/browser.js
@@ -44,7 +44,7 @@ const create = algorithm => async (buffer, options) => {
 		...options
 	};
 
-	const hash = await _globalThis.crypto.subtle.digest(algorithm, buffer);
+	const hash = await _globalThis.crypto.subtle.digest({name: algorithm}, buffer);
 
 	return options.outputFormat === 'hex' ? bufferToHex(hash) : hash;
 };

we got it working

see ampproject/amphtml#4354

Improve bufferToHex performance

The #7 method mentioned here is a good 10x faster compared to the one currently being used by this library.

That's the code:

// Pre-Init
const LUT_HEX_4b = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'];
const LUT_HEX_8b = new Array(0x100);
for (let n = 0; n < 0x100; n++) {
  LUT_HEX_8b[n] = `${LUT_HEX_4b[(n >>> 4) & 0xF]}${LUT_HEX_4b[n & 0xF]}`;
}
// End Pre-Init
function toHex(buffer) {
  let out = '';
  for (let idx = 0, edx = buffer.length; idx < edx; idx++) {
    out += LUT_HEX_8b[buffer[idx]];
  }
  return out;
}

Uppercase letters would need to be converted to lowercase though. And a Uint8Array needs to be passed to the function rather than an ArrayBuffer.

Inconsistent Buffer SHA1 in Node.js

I have a foo.txt like this:

foo
bar
baz

(LF. No LF at the end.)

And I have the following script:

const { sha1 } = require("crypto-hash");
const fs = require("fs");
const path = require("path");
const crypto = require("crypto");

main();

async function main() {
  const filePath = "foo.txt";
  const buf = fs.readFileSync(filePath);
  const str = fs.readFileSync(filePath, {
    encoding: "utf8",
  });
  console.log(await sha1(buf));
  console.log(await sha1(str));
  console.log(
    await new Promise((resolve, reject) => {
      const hash = crypto.createHash("sha1");
      const input = fs.createReadStream(filePath);
      input.on("readable", () => {
        const data = input.read();
        if (data) {
          hash.update(data);
        } else {
          resolve(hash.digest("hex"));
        }
      });
    })
  );
}

When I run it 3 times I get:

PS C:\Temp> node .\hashtest.js
4c37dbe6f4897fbed62502239273902421e1ea6a
01e06a68df2f0598042449c4088842bb4e92ca75
01e06a68df2f0598042449c4088842bb4e92ca75
PS C:\Temp> node .\hashtest.js
678082bb5b423c3dec7eb593465bd2d2cfa54287
01e06a68df2f0598042449c4088842bb4e92ca75
01e06a68df2f0598042449c4088842bb4e92ca75
PS C:\Temp> node .\hashtest.js
35d9940f295a0205252456e8c808eb5f651711b1
01e06a68df2f0598042449c4088842bb4e92ca75
01e06a68df2f0598042449c4088842bb4e92ca75

The output of sha1(buf) seems to constantly change, and never match the expected result.

Can't resolve 'crypto' in '.../node_modules/crypto-hash'

Sorry, I recognize this is likely not an issue with your library but I wonder if you know a way I could work around this issue:

I'm using a library (github.com/metaplex/js) which it depends on crypto-hash and it's giving me the following error during build:

Can't resolve 'crypto' in '.../node_modules/crypto-hash'

It seems my build is trying to use index.js instead of browser.js. I don't know what that is, seeing as how you are setting "browser": "browser.js", in the package.json. Is there some setting I need to adjust for my build to use the browser.js file instead of index.js?

ArrayBuffer not valid.

Documentation says input can be string ArrayBuffer ArrayBufferView

Unfortunately ArrayBuffer will fail because of this line ->

// Creating a copy of buffer at call time, will be transfered later
buffer = source.buffer.slice(0);

ArrayBuffer has no property buffer, you need a view.
A simple fix would be something like->

buffer = source instanceof ArrayBuffer ? new Unit8Array(source).slice(0) : source.buffer.slice(0)

Thrown “SCRIPT1028: SCRIPT1028: Expected identifier, string or number” in Edge browser.

When using an Angular app which use the @azure/cosmos and run it at Edge browser, it will hit the below error message.
“SCRIPT1028: SCRIPT1028: Expected identifier, string or number”
Clicking the error, I found the error thrown by the line 39.
After search it, found this github link:
https://github.com/sindresorhus/crypto-hash/blob/master/browser.js#L39
This code is part of the ‘crypto-hash.’

It seems that the ‘crypto-hash’ is required if using the @azure/cosmos.

I search again and found below link which indicating that Edge doesn’t support the Rest parameters (the syntax is ‘…options’)
https://stackoverflow.com/questions/53628191/edge-script1028-expected-identifier-string-or-number

Then, the issue seems to be the dead-lock status.
The Angular app use the @azure/cosmos. The @azure/cosmos required the ‘crypto-hash’. ‘crypto-hash’ use the Rest parameters. However, the Edge doesn’t support such syntax..
Therefore, the above restriction let the Angular app cannot be used in the Edge browser.

Could you please look into the issue and consider making change on '…options’ to make the 'crypto-hash' be compatible with Edge browser as well?

Appreciate it!

HMAC support

@sindresorhus Would you be open to HMAC support in this library? I am happy to take a shot at a PR but wanted to confirm you thought it fit in here rather than a separate library.

IE11 support

I tried running this library through babel, but I'm still getting an error:

image

If IE11 isn't supported even with Babel, could that be noted somewhere? Thanks!

error Error [ERR_REQUIRE_ESM]: require()

am trying to use this with sveltekit but I keep getting error

Error [ERR_REQUIRE_ESM]: require() of ES Module Instead change the require of index.js to a dynamic import() which is available in all CommonJS modules

am importing this this way import { sha256 } from 'crypto-hash';

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.