@noble/hashes
Advanced tools
Comparing version 1.2.0 to 1.3.0
export declare function number(n: number): void; | ||
export declare function bool(b: boolean): void; | ||
export declare function bytes(b: Uint8Array | undefined, ...lengths: number[]): void; | ||
declare type Hash = { | ||
type Hash = { | ||
(data: Uint8Array): Uint8Array; | ||
@@ -6,0 +6,0 @@ blockLen: number; |
import { Hash, Input } from './utils.js'; | ||
export declare const SIGMA: Uint8Array; | ||
export declare type BlakeOpts = { | ||
export type BlakeOpts = { | ||
dkLen?: number; | ||
@@ -5,0 +5,0 @@ key?: Input; |
@@ -6,2 +6,3 @@ "use strict"; | ||
const utils_js_1 = require("./utils.js"); | ||
// For BLAKE2b, the two extra permutations for rounds 10 and 11 are SIGMA[10..11] = SIGMA[0..1]. | ||
// prettier-ignore | ||
@@ -19,3 +20,2 @@ exports.SIGMA = new Uint8Array([ | ||
10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0, | ||
// For BLAKE2b, the two extra permutations for rounds 10 and 11 are SIGMA[10..11] = SIGMA[0..1]. | ||
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, | ||
@@ -37,9 +37,9 @@ 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, | ||
if (outputLen < 0 || outputLen > keyLen) | ||
throw new Error('Blake2: outputLen bigger than keyLen'); | ||
throw new Error('outputLen bigger than keyLen'); | ||
if (opts.key !== undefined && (opts.key.length < 1 || opts.key.length > keyLen)) | ||
throw new Error(`Key should be up 1..${keyLen} byte long or undefined`); | ||
throw new Error(`key must be up 1..${keyLen} byte long or undefined`); | ||
if (opts.salt !== undefined && opts.salt.length !== saltLen) | ||
throw new Error(`Salt should be ${saltLen} byte long or undefined`); | ||
throw new Error(`salt must be ${saltLen} byte long or undefined`); | ||
if (opts.personalization !== undefined && opts.personalization.length !== persLen) | ||
throw new Error(`Personalization should be ${persLen} byte long or undefined`); | ||
throw new Error(`personalization must be ${persLen} byte long or undefined`); | ||
this.buffer32 = (0, utils_js_1.u32)((this.buffer = new Uint8Array(blockLen))); | ||
@@ -46,0 +46,0 @@ } |
import { Input } from './utils.js'; | ||
export declare type ArgonOpts = { | ||
export type ArgonOpts = { | ||
t: number; | ||
@@ -4,0 +4,0 @@ m: number; |
import { BLAKE2 } from './_blake2.js'; | ||
import { Input, HashXOF } from './utils.js'; | ||
export declare type Blake3Opts = { | ||
export type Blake3Opts = { | ||
dkLen?: number; | ||
@@ -5,0 +5,0 @@ key?: Input; |
@@ -1,4 +0,1 @@ | ||
export declare const crypto: { | ||
node?: any; | ||
web?: any; | ||
}; | ||
export declare const crypto: any; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.crypto = void 0; | ||
const nodeCrypto = require("crypto"); | ||
exports.crypto = { | ||
node: nodeCrypto, | ||
web: undefined, | ||
}; | ||
exports.crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined; | ||
//# sourceMappingURL=crypto.js.map |
@@ -7,11 +7,11 @@ export declare function scrypt(password: string, salt: string): Uint8Array; | ||
export declare function deriveMainSeed(username: string, password: string): Uint8Array; | ||
declare type AccountID = number | string; | ||
declare type OptsLength = { | ||
type AccountID = number | string; | ||
type OptsLength = { | ||
keyLength: number; | ||
}; | ||
declare type OptsMod = { | ||
type OptsMod = { | ||
modulus: bigint; | ||
}; | ||
declare type KeyOpts = undefined | OptsLength | OptsMod; | ||
declare type ESKDF = Promise<Readonly<{ | ||
type KeyOpts = undefined | OptsLength | OptsMod; | ||
type ESKDF = Promise<Readonly<{ | ||
/** | ||
@@ -18,0 +18,0 @@ * Derives a child key. Child key will not be associated with any |
import assert from './_assert.js'; | ||
import { Hash, toBytes, u32 } from './utils.js'; | ||
// For BLAKE2b, the two extra permutations for rounds 10 and 11 are SIGMA[10..11] = SIGMA[0..1]. | ||
// prettier-ignore | ||
@@ -15,3 +16,2 @@ export const SIGMA = new Uint8Array([ | ||
10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0, | ||
// For BLAKE2b, the two extra permutations for rounds 10 and 11 are SIGMA[10..11] = SIGMA[0..1]. | ||
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, | ||
@@ -33,9 +33,9 @@ 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, | ||
if (outputLen < 0 || outputLen > keyLen) | ||
throw new Error('Blake2: outputLen bigger than keyLen'); | ||
throw new Error('outputLen bigger than keyLen'); | ||
if (opts.key !== undefined && (opts.key.length < 1 || opts.key.length > keyLen)) | ||
throw new Error(`Key should be up 1..${keyLen} byte long or undefined`); | ||
throw new Error(`key must be up 1..${keyLen} byte long or undefined`); | ||
if (opts.salt !== undefined && opts.salt.length !== saltLen) | ||
throw new Error(`Salt should be ${saltLen} byte long or undefined`); | ||
throw new Error(`salt must be ${saltLen} byte long or undefined`); | ||
if (opts.personalization !== undefined && opts.personalization.length !== persLen) | ||
throw new Error(`Personalization should be ${persLen} byte long or undefined`); | ||
throw new Error(`personalization must be ${persLen} byte long or undefined`); | ||
this.buffer32 = u32((this.buffer = new Uint8Array(blockLen))); | ||
@@ -42,0 +42,0 @@ } |
@@ -1,6 +0,2 @@ | ||
import * as nodeCrypto from 'crypto'; | ||
export const crypto = { | ||
node: nodeCrypto, | ||
web: undefined, | ||
}; | ||
export const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined; | ||
//# sourceMappingURL=crypto.js.map |
{ | ||
"type": "module", | ||
"browser": { | ||
"crypto": false, | ||
"./crypto": "./esm/cryptoBrowser.js" | ||
"node:crypto": false | ||
}, | ||
"node": { | ||
"./crypto": "./esm/cryptoNode.js" | ||
} | ||
} |
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ | ||
// The import here is via the package name. This is to ensure | ||
// that exports mapping/resolution does fall into place. | ||
// We use `globalThis.crypto`, but node.js versions earlier than v19 don't | ||
// declare it in global scope. For node.js, package.json#exports field mapping | ||
// rewrites import from `crypto` to `cryptoNode`, which imports native module. | ||
// Makes the utils un-importable in browsers without a bundler. | ||
// Once node.js 18 is deprecated, we can just drop the import. | ||
import { crypto } from '@noble/hashes/crypto'; | ||
@@ -12,5 +15,5 @@ // Cast array to different type | ||
export const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift); | ||
// big-endian hardware is rare. Just in case someone still decides to run hashes: | ||
// early-throw an error because we don't support BE yet. | ||
export const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; | ||
// There is almost no big endian hardware, but js typed arrays uses platform specific endianness. | ||
// So, just to be sure not to corrupt anything. | ||
if (!isLE) | ||
@@ -20,3 +23,3 @@ throw new Error('Non little-endian hardware is not supported'); | ||
/** | ||
* @example bytesToHex(Uint8Array.from([0xde, 0xad, 0xbe, 0xef])) | ||
* @example bytesToHex(Uint8Array.from([0xde, 0xad, 0xbe, 0xef])) // 'deadbeef' | ||
*/ | ||
@@ -34,3 +37,3 @@ export function bytesToHex(uint8a) { | ||
/** | ||
* @example hexToBytes('deadbeef') | ||
* @example hexToBytes('deadbeef') // Uint8Array.from([0xde, 0xad, 0xbe, 0xef]) | ||
*/ | ||
@@ -54,4 +57,5 @@ export function hexToBytes(hex) { | ||
} | ||
// There is no setImmediate in browser and setTimeout is slow. However, call to async function will return Promise | ||
// which will be fullfiled only on next scheduler queue processing step and this is exactly what we need. | ||
// There is no setImmediate in browser and setTimeout is slow. | ||
// call of async fn will return Promise, which will be fullfiled only on | ||
// next scheduler queue processing step and this is exactly what we need. | ||
export const nextTick = async () => { }; | ||
@@ -134,15 +138,10 @@ // Returns control to thread each 'tick' ms to avoid blocking | ||
/** | ||
* Secure PRNG | ||
* Secure PRNG. Uses `globalThis.crypto` or node.js crypto module. | ||
*/ | ||
export function randomBytes(bytesLength = 32) { | ||
if (crypto.web) { | ||
return crypto.web.getRandomValues(new Uint8Array(bytesLength)); | ||
if (crypto && typeof crypto.getRandomValues === 'function') { | ||
return crypto.getRandomValues(new Uint8Array(bytesLength)); | ||
} | ||
else if (crypto.node) { | ||
return new Uint8Array(crypto.node.randomBytes(bytesLength).buffer); | ||
} | ||
else { | ||
throw new Error("The environment doesn't have randomBytes function"); | ||
} | ||
throw new Error('crypto.getRandomValues must be defined'); | ||
} | ||
//# sourceMappingURL=utils.js.map |
{ | ||
"name": "@noble/hashes", | ||
"version": "1.2.0", | ||
"version": "1.3.0", | ||
"description": "Audited & minimal 0-dependency JS implementation of SHA2, SHA3, RIPEMD, BLAKE2/3, HMAC, HKDF, PBKDF2, Scrypt", | ||
@@ -17,4 +17,4 @@ "files": [ | ||
"build": "npm run build:clean; tsc && tsc -p tsconfig.esm.json", | ||
"build:release": "rollup -c build/rollup.config.js", | ||
"build:clean": "rm *.{js,d.ts,js.map} esm/*.{js,js.map}", | ||
"build:release": "cd build; npm i; npm run build", | ||
"build:clean": "rm *.{js,d.ts,js.map} esm/*.{js,js.map} 2> /dev/null", | ||
"lint": "prettier --check 'src/**/*.{js,ts}' 'test/**/*.{js,ts}'", | ||
@@ -34,12 +34,11 @@ "format": "prettier --write 'src/**/*.{js,ts}' 'test/**/*.{js,ts}'", | ||
"browser": { | ||
"crypto": false, | ||
"./crypto": "./cryptoBrowser.js" | ||
"node:crypto": false, | ||
"./crypto": "./crypto.js" | ||
}, | ||
"devDependencies": { | ||
"@rollup/plugin-node-resolve": "13.3.0", | ||
"micro-bmark": "0.2.0", | ||
"micro-should": "0.2.0", | ||
"prettier": "2.6.2", | ||
"rollup": "2.75.5", | ||
"typescript": "4.7.3" | ||
"@types/node": "18.11.18", | ||
"micro-bmark": "0.3.0", | ||
"micro-should": "0.4.0", | ||
"prettier": "2.8.3", | ||
"typescript": "5.0.2" | ||
}, | ||
@@ -54,5 +53,5 @@ "exports": { | ||
"types": "./crypto.d.ts", | ||
"browser": { | ||
"import": "./esm/cryptoBrowser.js", | ||
"default": "./cryptoBrowser.js" | ||
"node": { | ||
"import": "./esm/cryptoNode.js", | ||
"default": "./cryptoNode.js" | ||
}, | ||
@@ -59,0 +58,0 @@ "import": "./esm/crypto.js", |
import { CHash, Input } from './utils.js'; | ||
export declare type Pbkdf2Opt = { | ||
export type Pbkdf2Opt = { | ||
c: number; | ||
@@ -4,0 +4,0 @@ dkLen?: number; |
101
README.md
@@ -22,3 +22,3 @@ # noble-hashes ![Node CI](https://github.com/paulmillr/noble-hashes/workflows/Node%20CI/badge.svg) [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier) | ||
- No dependencies, small files | ||
- No dependencies | ||
- Easily auditable TypeScript/JS code | ||
@@ -28,5 +28,5 @@ - Supported in all major browsers and stable node.js versions | ||
- Check out [homepage](https://paulmillr.com/noble/) & all libraries: | ||
[curves](https://github.com/paulmillr/noble-curves) ([secp256k1](https://github.com/paulmillr/noble-secp256k1), | ||
[ed25519](https://github.com/paulmillr/noble-ed25519), | ||
[bls12-381](https://github.com/paulmillr/noble-bls12-381)), | ||
[curves](https://github.com/paulmillr/noble-curves) | ||
([secp256k1](https://github.com/paulmillr/noble-secp256k1), | ||
[ed25519](https://github.com/paulmillr/noble-ed25519)), | ||
[hashes](https://github.com/paulmillr/noble-hashes) | ||
@@ -36,12 +36,17 @@ | ||
Use NPM in node.js / browser, or include single file from | ||
[GitHub's releases page](https://github.com/paulmillr/noble-hashes/releases): | ||
Browser, deno and node.js are supported: | ||
> npm install @noble/hashes | ||
The library does not have an entry point. It allows you to select specific primitives and drop everything else. If you only want to use sha256, just use the library with rollup or other bundlers. This is done to make your bundles tiny. | ||
For [Deno](https://deno.land), use it with npm specifier. | ||
In browser, you could also include the single file from | ||
[GitHub's releases page](https://github.com/paulmillr/noble-hashes/releases). | ||
The library does not have an entry point. It allows you to select specific | ||
primitives and drop everything else. If you only want to use sha256, just use the | ||
library with rollup or other bundlers. This is done to make your bundles tiny. | ||
```js | ||
// Common.js and ECMAScript Modules (ESM) | ||
import { sha256 } from '@noble/hashes/sha256'; | ||
import { sha256 } from '@noble/hashes/sha256'; // ECMAScript modules (ESM) and Common.js | ||
// import { sha256 } from 'npm:@noble/hashes@1.3.0/sha256'; // Deno | ||
console.log(sha256(new Uint8Array([1, 2, 3]))); // Uint8Array(32) [3, 144, 88, 198, 242...] | ||
@@ -166,3 +171,4 @@ // you could also pass strings that will be UTF8-encoded to Uint8Array | ||
See [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and [the paper on SHA512/256](https://eprint.iacr.org/2010/548.pdf). | ||
See [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and | ||
[the paper on SHA512/256](https://eprint.iacr.org/2010/548.pdf). | ||
@@ -194,3 +200,4 @@ ##### SHA3 (FIPS, SHAKE, Keccak) | ||
See ([FIPS PUB 202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf), [Website](https://keccak.team/keccak.html)). | ||
See [FIPS PUB 202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf), | ||
[Website](https://keccak.team/keccak.html). | ||
@@ -232,4 +239,8 @@ Check out [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub) | ||
- Full [NIST SP 800-185](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-185.pdf): cSHAKE, KMAC, TupleHash, ParallelHash + XOF variants | ||
- 🦘 K12 ([KangarooTwelve Paper](https://keccak.team/files/KangarooTwelve.pdf), [RFC Draft](https://www.ietf.org/archive/id/draft-irtf-cfrg-kangarootwelve-06.txt)) and M14 aka MarsupilamiFourteen are basically parallel versions of Keccak with reduced number of rounds (same as Blake3 and ParallelHash). | ||
- Full [NIST SP 800-185](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-185.pdf): | ||
cSHAKE, KMAC, TupleHash, ParallelHash + XOF variants | ||
- 🦘 K12 ([KangarooTwelve Paper](https://keccak.team/files/KangarooTwelve.pdf), | ||
[RFC Draft](https://www.ietf.org/archive/id/draft-irtf-cfrg-kangarootwelve-06.txt)) | ||
and M14 aka MarsupilamiFourteen are basically parallel versions of Keccak with | ||
reduced number of rounds (same as Blake3 and ParallelHash). | ||
- [KeccakPRG](https://keccak.team/files/CSF-0.1.pdf): Pseudo-random generator based on Keccak | ||
@@ -249,3 +260,4 @@ | ||
See [RFC 2286](https://datatracker.ietf.org/doc/html/rfc2286), [Website](https://homes.esat.kuleuven.be/~bosselae/ripemd160.html) | ||
See [RFC 2286](https://datatracker.ietf.org/doc/html/rfc2286), | ||
[Website](https://homes.esat.kuleuven.be/~bosselae/ripemd160.html) | ||
@@ -354,3 +366,4 @@ ##### BLAKE2b, BLAKE2s | ||
Matches [RFC 7914](https://datatracker.ietf.org/doc/html/rfc7914), [Website](https://www.tarsnap.com/scrypt.html) | ||
Conforms to [RFC 7914](https://datatracker.ietf.org/doc/html/rfc7914), | ||
[Website](https://www.tarsnap.com/scrypt.html) | ||
@@ -362,8 +375,11 @@ - `N, r, p` are work factors. To understand them, see [the blog post](https://blog.filippo.io/the-scrypt-parameters/). | ||
Memory usage of scrypt is calculated with the formula `N * r * p * 128 + (128 * r * p)`, which means | ||
`{N: 2 ** 22, r: 8, p: 1}` will use 4GB + 1KB of memory. To prevent DoS, we limit scrypt to `1GB + 1KB` of RAM used, | ||
which corresponds to `{N: 2 ** 20, r: 8, p: 1}`. If you want to use higher values, increase `maxmem` using the formula above. | ||
Memory usage of scrypt is calculated with the formula `N * r * p * 128 + (128 * r * p)`, | ||
which means `{N: 2 ** 22, r: 8, p: 1}` will use 4GB + 1KB of memory. To prevent | ||
DoS, we limit scrypt to `1GB + 1KB` of RAM used, which corresponds to | ||
`{N: 2 ** 20, r: 8, p: 1}`. If you want to use higher values, increase | ||
`maxmem` using the formula above. | ||
_Note:_ noble supports `2**22` (4GB RAM) which is the highest amount amongst JS libs. Many other implementations don't support it. | ||
We cannot support `2**23`, because there is a limitation in JS engines that makes allocating | ||
_Note:_ noble supports `2**22` (4GB RAM) which is the highest amount amongst JS | ||
libs. Many other implementations don't support it. We cannot support `2**23`, | ||
because there is a limitation in JS engines that makes allocating | ||
arrays bigger than 4GB impossible, but we're looking into other possible solutions. | ||
@@ -426,13 +442,40 @@ | ||
1. The library has been audited on Jan 5, 2022 by an independent security firm cure53: [PDF](https://cure53.de/pentest-report_hashing-libs.pdf). No vulnerabilities have been found. The audit has been funded by Ethereum Foundation with help of [Nomic Labs](https://nomiclabs.io). Modules `blake3`, `sha3-addons` and `sha1` have not been audited. See [changes since audit](https://github.com/paulmillr/noble-hashes/compare/1.0.0..main). | ||
2. The library has been fuzzed by [Guido Vranken's cryptofuzz](https://github.com/guidovranken/cryptofuzz). You can run the fuzzer by yourself to check it. | ||
3. [Timing attack](https://en.wikipedia.org/wiki/Timing_attack) considerations: _JIT-compiler_ and _Garbage Collector_ make "constant time" extremely hard to achieve in a scripting language. Which means _any other JS library can't have constant-timeness_. Even statically typed Rust, a language without GC, [makes it harder to achieve constant-time](https://www.chosenplaintext.ca/open-source/rust-timing-shield/security) for some cases. If your goal is absolute security, don't use any JS lib — including bindings to native ones. Use low-level libraries & languages. Nonetheless we're targetting algorithmic constant time. | ||
4. Memory dump considerations: the library shares state buffers between hash function calls. The buffers are zeroed-out after each call. However, if an attacker can read application memory, you are doomed in any case: | ||
- At some point, input will be a string and strings are immutable in JS: there is no way to overwrite them with zeros. For example: deriving key from `scrypt(password, salt)` where password and salt are strings | ||
1. The library has been audited in Jan 2022 by an independent security firm | ||
cure53: [PDF](https://cure53.de/pentest-report_hashing-libs.pdf). | ||
No vulnerabilities have been found. The audit has been funded by | ||
[Ethereum Foundation](https://ethereum.org/en/) with help of [Nomic Labs](https://nomiclabs.io). | ||
Modules `blake3`, `sha3-addons`, `sha1` and `argon2` have not been audited. | ||
See [changes since audit](https://github.com/paulmillr/noble-hashes/compare/1.0.0..main). | ||
2. The library has been fuzzed by [Guido Vranken's cryptofuzz](https://github.com/guidovranken/cryptofuzz). | ||
You can run the fuzzer by yourself to check it. | ||
3. [Timing attack](https://en.wikipedia.org/wiki/Timing_attack) considerations: | ||
_JIT-compiler_ and _Garbage Collector_ make "constant time" extremely hard to | ||
achieve in a scripting language. Which means _any other JS library can't have constant-timeness_. | ||
Even statically typed Rust, a language without GC, | ||
[makes it harder to achieve constant-time](https://www.chosenplaintext.ca/open-source/rust-timing-shield/security) | ||
for some cases. If your goal is absolute security, don't use any JS lib — including | ||
bindings to native ones. Use low-level libraries & languages. Nonetheless we're | ||
targetting algorithmic constant time. | ||
4. Memory dump considerations: the library shares state buffers between hash | ||
function calls. The buffers are zeroed-out after each call. However, if an attacker | ||
can read application memory, you are doomed in any case: | ||
- At some point, input will be a string and strings are immutable in JS: | ||
there is no way to overwrite them with zeros. For example: deriving | ||
key from `scrypt(password, salt)` where password and salt are strings | ||
- Input from a file will stay in file buffers | ||
- Input / output will be re-used multiple times in application which means it could stay in memory | ||
- `await anything()` will always write all internal variables (including numbers) to memory. With async functions / Promises there are no guarantees when the code chunk would be executed. Which means attacker can have plenty of time to read data from memory | ||
- There is no way to guarantee anything about zeroing sensitive data without complex tests-suite which will dump process memory and verify that there is no sensitive data left. For JS it means testing all browsers (incl. mobile), which is complex. And of course it will be useless without using the same test-suite in the actual application that consumes the library | ||
- Input / output will be re-used multiple times in application which means | ||
it could stay in memory | ||
- `await anything()` will always write all internal variables (including numbers) | ||
to memory. With async functions / Promises there are no guarantees when the code | ||
chunk would be executed. Which means attacker can have plenty of time to read data from memory | ||
- There is no way to guarantee anything about zeroing sensitive data without | ||
complex tests-suite which will dump process memory and verify that there is | ||
no sensitive data left. For JS it means testing all browsers (incl. mobile), | ||
which is complex. And of course it will be useless without using the same | ||
test-suite in the actual application that consumes the library | ||
We consider infrastructure attacks like rogue NPM modules very important; that's why it's crucial to minimize the amount of 3rd-party dependencies & native bindings. If your app uses 500 dependencies, any dep could get hacked and you'll be downloading malware with every `npm install`. Our goal is to minimize this attack vector. | ||
We consider infrastructure attacks like rogue NPM modules very important; that's | ||
why it's crucial to minimize the amount of 3rd-party dependencies & native bindings. | ||
If your app uses 500 dependencies, any dep could get hacked and you'll be downloading | ||
malware with every `npm install`. Our goal is to minimize this attack vector. | ||
@@ -439,0 +482,0 @@ ## Speed |
import { Input } from './utils.js'; | ||
export declare type ScryptOpts = { | ||
export type ScryptOpts = { | ||
N: number; | ||
@@ -4,0 +4,0 @@ r: number; |
import { Input, Hash, HashXOF } from './utils.js'; | ||
import { Keccak, ShakeOpts } from './sha3.js'; | ||
export declare type cShakeOpts = ShakeOpts & { | ||
export type cShakeOpts = ShakeOpts & { | ||
personalization?: Input; | ||
@@ -63,3 +63,3 @@ NISTfn?: Input; | ||
}; | ||
declare type ParallelOpts = cShakeOpts & { | ||
type ParallelOpts = cShakeOpts & { | ||
blockLen?: number; | ||
@@ -95,3 +95,3 @@ }; | ||
}; | ||
export declare type KangarooOpts = { | ||
export type KangarooOpts = { | ||
dkLen?: number; | ||
@@ -98,0 +98,0 @@ personalization?: Input; |
@@ -83,3 +83,3 @@ import { Hash, Input, HashXOF } from './utils.js'; | ||
}; | ||
export declare type ShakeOpts = { | ||
export type ShakeOpts = { | ||
dkLen?: number; | ||
@@ -86,0 +86,0 @@ }; |
import assert from './_assert.js'; | ||
import { Hash, Input, toBytes, u32 } from './utils.js'; | ||
// For BLAKE2b, the two extra permutations for rounds 10 and 11 are SIGMA[10..11] = SIGMA[0..1]. | ||
// prettier-ignore | ||
@@ -15,3 +16,2 @@ export const SIGMA = new Uint8Array([ | ||
10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0, | ||
// For BLAKE2b, the two extra permutations for rounds 10 and 11 are SIGMA[10..11] = SIGMA[0..1]. | ||
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, | ||
@@ -52,10 +52,9 @@ 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, | ||
assert.number(keyLen); | ||
if (outputLen < 0 || outputLen > keyLen) | ||
throw new Error('Blake2: outputLen bigger than keyLen'); | ||
if (outputLen < 0 || outputLen > keyLen) throw new Error('outputLen bigger than keyLen'); | ||
if (opts.key !== undefined && (opts.key.length < 1 || opts.key.length > keyLen)) | ||
throw new Error(`Key should be up 1..${keyLen} byte long or undefined`); | ||
throw new Error(`key must be up 1..${keyLen} byte long or undefined`); | ||
if (opts.salt !== undefined && opts.salt.length !== saltLen) | ||
throw new Error(`Salt should be ${saltLen} byte long or undefined`); | ||
throw new Error(`salt must be ${saltLen} byte long or undefined`); | ||
if (opts.personalization !== undefined && opts.personalization.length !== persLen) | ||
throw new Error(`Personalization should be ${persLen} byte long or undefined`); | ||
throw new Error(`personalization must be ${persLen} byte long or undefined`); | ||
this.buffer32 = u32((this.buffer = new Uint8Array(blockLen))); | ||
@@ -62,0 +61,0 @@ } |
@@ -1,6 +0,3 @@ | ||
import * as nodeCrypto from 'crypto'; | ||
export const crypto: { node?: any; web?: any } = { | ||
node: nodeCrypto, | ||
web: undefined, | ||
}; | ||
declare const globalThis: Record<string, any> | undefined; | ||
export const crypto = | ||
typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined; |
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ | ||
// The import here is via the package name. This is to ensure | ||
// that exports mapping/resolution does fall into place. | ||
// We use `globalThis.crypto`, but node.js versions earlier than v19 don't | ||
// declare it in global scope. For node.js, package.json#exports field mapping | ||
// rewrites import from `crypto` to `cryptoNode`, which imports native module. | ||
// Makes the utils un-importable in browsers without a bundler. | ||
// Once node.js 18 is deprecated, we can just drop the import. | ||
import { crypto } from '@noble/hashes/crypto'; | ||
@@ -23,5 +26,5 @@ | ||
// big-endian hardware is rare. Just in case someone still decides to run hashes: | ||
// early-throw an error because we don't support BE yet. | ||
export const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; | ||
// There is almost no big endian hardware, but js typed arrays uses platform specific endianness. | ||
// So, just to be sure not to corrupt anything. | ||
if (!isLE) throw new Error('Non little-endian hardware is not supported'); | ||
@@ -31,3 +34,3 @@ | ||
/** | ||
* @example bytesToHex(Uint8Array.from([0xde, 0xad, 0xbe, 0xef])) | ||
* @example bytesToHex(Uint8Array.from([0xde, 0xad, 0xbe, 0xef])) // 'deadbeef' | ||
*/ | ||
@@ -45,3 +48,3 @@ export function bytesToHex(uint8a: Uint8Array): string { | ||
/** | ||
* @example hexToBytes('deadbeef') | ||
* @example hexToBytes('deadbeef') // Uint8Array.from([0xde, 0xad, 0xbe, 0xef]) | ||
*/ | ||
@@ -64,4 +67,5 @@ export function hexToBytes(hex: string): Uint8Array { | ||
// There is no setImmediate in browser and setTimeout is slow. However, call to async function will return Promise | ||
// which will be fullfiled only on next scheduler queue processing step and this is exactly what we need. | ||
// There is no setImmediate in browser and setTimeout is slow. | ||
// call of async fn will return Promise, which will be fullfiled only on | ||
// next scheduler queue processing step and this is exactly what we need. | ||
export const nextTick = async () => {}; | ||
@@ -127,10 +131,15 @@ | ||
abstract digest(): Uint8Array; | ||
// Cleanup internal state. Not '.clean' because instance is not usable after that. | ||
// Clean usually resets instance to initial state, but it is not possible for keyed hashes if key is consumed into state. | ||
// NOTE: if digest is not consumed by user, user need manually call '.destroy' if zeroing is required | ||
/** | ||
* Resets internal state. Makes Hash instance unusable. | ||
* Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed | ||
* by user, they will need to manually call `destroy()` when zeroing is necessary. | ||
*/ | ||
abstract destroy(): void; | ||
// Unsafe because doesn't check if "to" is correct. Can be used as clone() if no opts passed. | ||
// Why cloneInto instead of clone? Mostly performance (same as _digestInto), but also has nice property: it reuses instance | ||
// which means all internal buffers is overwritten, which also causes overwrite buffer which used for digest (in some cases). | ||
// We don't provide any guarantees about cleanup (it is impossible to!), so should be enough for now. | ||
/** | ||
* Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()` | ||
* when no options are passed. | ||
* Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal | ||
* buffers are overwritten => causes buffer overwrite which is used for digest in some cases. | ||
* There are no guarantees for clean-up because it's impossible in JS. | ||
*/ | ||
abstract _cloneInto(to?: T): T; | ||
@@ -146,3 +155,4 @@ // Safe version that clones internal state | ||
* Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name. | ||
* When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot destroy state, next call can require more bytes. | ||
* When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot | ||
* destroy state, next call can require more bytes. | ||
*/ | ||
@@ -192,12 +202,9 @@ export type HashXOF<T extends Hash<T>> = Hash<T> & { | ||
/** | ||
* Secure PRNG | ||
* Secure PRNG. Uses `globalThis.crypto` or node.js crypto module. | ||
*/ | ||
export function randomBytes(bytesLength = 32): Uint8Array { | ||
if (crypto.web) { | ||
return crypto.web.getRandomValues(new Uint8Array(bytesLength)); | ||
} else if (crypto.node) { | ||
return new Uint8Array(crypto.node.randomBytes(bytesLength).buffer); | ||
} else { | ||
throw new Error("The environment doesn't have randomBytes function"); | ||
if (crypto && typeof crypto.getRandomValues === 'function') { | ||
return crypto.getRandomValues(new Uint8Array(bytesLength)); | ||
} | ||
throw new Error('crypto.getRandomValues must be defined'); | ||
} |
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ | ||
export declare type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array | Uint16Array | Int16Array | Uint32Array | Int32Array; | ||
export type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array | Uint16Array | Int16Array | Uint32Array | Int32Array; | ||
export declare const u8: (arr: TypedArray) => Uint8Array; | ||
@@ -9,7 +9,7 @@ export declare const u32: (arr: TypedArray) => Uint32Array; | ||
/** | ||
* @example bytesToHex(Uint8Array.from([0xde, 0xad, 0xbe, 0xef])) | ||
* @example bytesToHex(Uint8Array.from([0xde, 0xad, 0xbe, 0xef])) // 'deadbeef' | ||
*/ | ||
export declare function bytesToHex(uint8a: Uint8Array): string; | ||
/** | ||
* @example hexToBytes('deadbeef') | ||
* @example hexToBytes('deadbeef') // Uint8Array.from([0xde, 0xad, 0xbe, 0xef]) | ||
*/ | ||
@@ -20,3 +20,3 @@ export declare function hexToBytes(hex: string): Uint8Array; | ||
export declare function utf8ToBytes(str: string): Uint8Array; | ||
export declare type Input = Uint8Array | string; | ||
export type Input = Uint8Array | string; | ||
export declare function toBytes(data: Input): Uint8Array; | ||
@@ -34,3 +34,15 @@ /** | ||
abstract digest(): Uint8Array; | ||
/** | ||
* Resets internal state. Makes Hash instance unusable. | ||
* Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed | ||
* by user, they will need to manually call `destroy()` when zeroing is necessary. | ||
*/ | ||
abstract destroy(): void; | ||
/** | ||
* Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()` | ||
* when no options are passed. | ||
* Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal | ||
* buffers are overwritten => causes buffer overwrite which is used for digest in some cases. | ||
* There are no guarantees for clean-up because it's impossible in JS. | ||
*/ | ||
abstract _cloneInto(to?: T): T; | ||
@@ -42,11 +54,12 @@ clone(): T; | ||
* Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name. | ||
* When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot destroy state, next call can require more bytes. | ||
* When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot | ||
* destroy state, next call can require more bytes. | ||
*/ | ||
export declare type HashXOF<T extends Hash<T>> = Hash<T> & { | ||
export type HashXOF<T extends Hash<T>> = Hash<T> & { | ||
xof(bytes: number): Uint8Array; | ||
xofInto(buf: Uint8Array): Uint8Array; | ||
}; | ||
declare type EmptyObj = {}; | ||
type EmptyObj = {}; | ||
export declare function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(defaults: T1, opts?: T2): T1 & T2; | ||
export declare type CHash = ReturnType<typeof wrapConstructor>; | ||
export type CHash = ReturnType<typeof wrapConstructor>; | ||
export declare function wrapConstructor<T extends Hash<T>>(hashConstructor: () => Hash<T>): { | ||
@@ -65,5 +78,5 @@ (message: Input): Uint8Array; | ||
/** | ||
* Secure PRNG | ||
* Secure PRNG. Uses `globalThis.crypto` or node.js crypto module. | ||
*/ | ||
export declare function randomBytes(bytesLength?: number): Uint8Array; | ||
export {}; |
33
utils.js
@@ -5,4 +5,7 @@ "use strict"; | ||
exports.randomBytes = exports.wrapConstructorWithOpts = exports.wrapConstructor = exports.checkOpts = exports.Hash = exports.concatBytes = exports.toBytes = exports.utf8ToBytes = exports.asyncLoop = exports.nextTick = exports.hexToBytes = exports.bytesToHex = exports.isLE = exports.rotr = exports.createView = exports.u32 = exports.u8 = void 0; | ||
// The import here is via the package name. This is to ensure | ||
// that exports mapping/resolution does fall into place. | ||
// We use `globalThis.crypto`, but node.js versions earlier than v19 don't | ||
// declare it in global scope. For node.js, package.json#exports field mapping | ||
// rewrites import from `crypto` to `cryptoNode`, which imports native module. | ||
// Makes the utils un-importable in browsers without a bundler. | ||
// Once node.js 18 is deprecated, we can just drop the import. | ||
const crypto_1 = require("@noble/hashes/crypto"); | ||
@@ -20,5 +23,5 @@ // Cast array to different type | ||
exports.rotr = rotr; | ||
// big-endian hardware is rare. Just in case someone still decides to run hashes: | ||
// early-throw an error because we don't support BE yet. | ||
exports.isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; | ||
// There is almost no big endian hardware, but js typed arrays uses platform specific endianness. | ||
// So, just to be sure not to corrupt anything. | ||
if (!exports.isLE) | ||
@@ -28,3 +31,3 @@ throw new Error('Non little-endian hardware is not supported'); | ||
/** | ||
* @example bytesToHex(Uint8Array.from([0xde, 0xad, 0xbe, 0xef])) | ||
* @example bytesToHex(Uint8Array.from([0xde, 0xad, 0xbe, 0xef])) // 'deadbeef' | ||
*/ | ||
@@ -43,3 +46,3 @@ function bytesToHex(uint8a) { | ||
/** | ||
* @example hexToBytes('deadbeef') | ||
* @example hexToBytes('deadbeef') // Uint8Array.from([0xde, 0xad, 0xbe, 0xef]) | ||
*/ | ||
@@ -64,4 +67,5 @@ function hexToBytes(hex) { | ||
exports.hexToBytes = hexToBytes; | ||
// There is no setImmediate in browser and setTimeout is slow. However, call to async function will return Promise | ||
// which will be fullfiled only on next scheduler queue processing step and this is exactly what we need. | ||
// There is no setImmediate in browser and setTimeout is slow. | ||
// call of async fn will return Promise, which will be fullfiled only on | ||
// next scheduler queue processing step and this is exactly what we need. | ||
const nextTick = async () => { }; | ||
@@ -153,16 +157,11 @@ exports.nextTick = nextTick; | ||
/** | ||
* Secure PRNG | ||
* Secure PRNG. Uses `globalThis.crypto` or node.js crypto module. | ||
*/ | ||
function randomBytes(bytesLength = 32) { | ||
if (crypto_1.crypto.web) { | ||
return crypto_1.crypto.web.getRandomValues(new Uint8Array(bytesLength)); | ||
if (crypto_1.crypto && typeof crypto_1.crypto.getRandomValues === 'function') { | ||
return crypto_1.crypto.getRandomValues(new Uint8Array(bytesLength)); | ||
} | ||
else if (crypto_1.crypto.node) { | ||
return new Uint8Array(crypto_1.crypto.node.randomBytes(bytesLength).buffer); | ||
} | ||
else { | ||
throw new Error("The environment doesn't have randomBytes function"); | ||
} | ||
throw new Error('crypto.getRandomValues must be defined'); | ||
} | ||
exports.randomBytes = randomBytes; | ||
//# sourceMappingURL=utils.js.map |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
737372
5
541
10209