This npm package contains all the cryptographic primitives normally used when developing Javascript/TypeScript applications and tools for Ethereum.
Pure Javascript implementations of all the primitives are included, so it can be used out of the box for web applications and libraries.
In Node, it takes advantage of the built-in implementations when possible. To improve performance of some primitives, you can install a second package with native implementations that will be detected and used by this one.
The cryptographic primitives included are:
- Pseudorandom number generation
- Keccak
- Scrypt
- PBKDF2
- SHA-256
- RIPEMD-160
- BLAKE2b
- AES
- Secp256k1
- Hierarchical Deterministic keys derivation
- Seed recovery phrases
Via npm
:
$ npm install ethereum-cryptography
Via yarn
:
$ yarn add ethereum-cryptography
This package has no single entry-point, but submodule for each cryptographic primitive. Read each primitive's section of this document to learn how to use them.
The reason for this is that importing everything from a single file will lead to huge bundles when using this package for the web. This could be avoided through tree-shaking, but the possibility of it not working properly on one of the supported bundlers is too high.
The random
submodule has functions to generate cryptographically strong
pseudo-random data in synchronous and asynchronous ways.
In Node, this functions are backed by crypto.randomBytes
.
In the browser, crypto.getRandomValues
is used. If not available, this module won't work, as that would be insecure.
function getRandomBytes(bytes: number): Promise<Buffer>;
function getRandomBytesSync(bytes: number): Buffer;
const { getRandomBytesSync } = require("ethereum-cryptography/random");
console.log(getRandomBytesSync(32).toString("hex"));
The keccak
submodule has four functions that implement different variations of
the Keccak hashing algorithm. These are keccak224
, keccak256
, keccak384
,
and keccak512
.
function keccak224(msg: Buffer): Buffer;
function keccak256(msg: Buffer): Buffer;
function keccak384(msg: Buffer): Buffer;
function keccak512(msg: Buffer): Buffer;
const { keccak256 } = require("ethereum-cryptography/keccak");
console.log(keccak256(Buffer.from("Hello, world!", "ascii")).toString("hex"));
The scrypt
submodule has two functions implementing the Scrypt key
derivation algorithm in synchronous and asynchronous ways. This algorithm is
very slow, and using the synchronous version in the browser is not recommended,
as it will block its main thread and hang your UI.
Encoding passwords is a frequent source of errors. Please read these notes before using this submodule.
function scrypt(password: Buffer, salt: Buffer, n: number, p: number, r: number, dklen: number): Promise<Buffer>;
function scryptSync(password: Buffer, salt: Buffer, n: number, p: number, r: number, dklen: number): Buffer;
const { scryptSync } = require("ethereum-cryptography/scrypt");
console.log(
scryptSync(
Buffer.from("ascii password", "ascii"),
Buffer.from("salt", "hex"),
16,
1,
1,
64
).toString("hex")
);
The pbkdf2
submodule has two functions implementing the PBKDF2 key
derivation algorithm in synchronous and asynchronous ways. This algorithm is
very slow, and using the synchronous version in the browser is not recommended,
as it will block its main thread and hang your UI.
Encoding passwords is a frequent source of errors. Please read these notes before using this submodule.
In Node this submodule uses the built-in implementation and supports any digest
returned by crypto.getHashes
.
In the browser, it is tested to support at least sha256
, the only digest
normally used with pbkdf2
in Ethereum. It may support more.
function pbkdf2(password: Buffer, salt: Buffer, iterations: number, keylen: number, digest: string): Promise<Buffer>;
function pbkdf2Sync(password: Buffer, salt: Buffer, iterations: number, keylen: number, digest: string): Buffer;
const { pbkdf2Sync } = require("ethereum-cryptography/pbkdf2");
console.log(
pbkdf2Sync(
Buffer.from("ascii password", "ascii"),
Buffer.from("salt", "hex"),
4096,
32,
'sha256'
).toString("hex")
);
The sha256
submodule contains a single function implementing the SHA-256
hashing algorithm.
function sha256(msg: Buffer): Buffer;
const { sha256 } = require("ethereum-cryptography/sha256");
console.log(sha256(Buffer.from("message", "ascii")).toString("hex"));
The ripemd160
submodule contains a single function implementing the
RIPEMD-160 hashing algorithm.
function ripemd160(msg: Buffer): Buffer;
const { ripemd160 } = require("ethereum-cryptography/ripemd160");
console.log(ripemd160(Buffer.from("message", "ascii")).toString("hex"));
The blake2b
submodule contains a single function implementing the
BLAKE2b non-keyed hashing algorithm.
function blake2b(input: Buffer, outputLength = 64): Buffer;
const { blake2b } = require("ethereum-cryptography/blake2b");
console.log(blake2b(Buffer.from("message", "ascii")).toString("hex"));
The aes
submodule contains encryption and decryption functions implementing
the Advanced Encryption Standard
algorithm.
AES is not supposed to be used directly with a password. Doing that will compromise your users' security.
The key
parameters in this submodule are meant to be strong cryptographic
keys. If you want to obtain such a key from a password, please use a
key derivation function
like pbkdf2 or scrypt.
This submodule works with different block cipher modes of operation.
To choose one of them, you should pass the mode
parameter a string with the
same format as OpenSSL and Node use. You can take a look at them by running
openssl list -cipher-algorithms
.
In Node, any mode that its OpenSSL version supports can be used.
In the browser, we test it to work with the modes that are normally used in
Ethereum libraries and applications. Those are aes-128-ctr
, aes-126-cbc
, and
aes-256-cbc
, but other modes may work.
Some operation modes require the plaintext message to be a multiple of 16
. If
that isn't the case, your message has to be padded.
By default, this module automatically pads your messages according to PKCS#7. Note that this padding scheme always adds at least 1 byte of padding. If you are unsure what anything of this means, we strongly recommend you to use the defaults.
If you need to encrypt without padding or want to use another padding scheme,
you can disable PKCS#7 padding by passing false
as the last argument and
handling padding yourself. Note that if you do this and your operation mode
requires padding, encrypt
will throw if your plaintext message isn't a
multiple of `16.
function encrypt(msg: Buffer, key: Buffer, iv: Buffer, mode: string, pkcs7PaddingEnabled = true): Buffer;
function decrypt(cypherText: Buffer, key: Buffer, iv: Buffer, mode: string, pkcs7PaddingEnabled = true): Buffer
const { encrypt } = require("ethereum-cryptography/aes");
console.log(
encrypt(
Buffer.from("message", "ascii"),
Buffer.from("2b7e151628aed2a6abf7158809cf4f3c", "hex"),
Buffer.from("f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff", "hex"),
"aes-128-cbc"
).toString("hex")
);
The secp256k1
submodule provides a library for elliptic curve operations on
the curve Secp256k1.
It has the exact same API than the version 3.x
of the native module
secp256k1
from cryptocoinjs,
but it's backed by elliptic
.
Go to secp256k1
's documentation
to learn how to use it.
const { sign } = require("ethereum-cryptography/secp256k1");
const msgHash = Buffer.from(
"82ff40c0a986c6a5cfad4ddf4c3aa6996f1a7837f9c398e17e5de5cbd5a12b28",
"hex"
);
const privateKey = Buffer.from(
"3c9229289a6125f7fdf1885a77bb12c37a8d3b4962d936f7e3084dece32a3ca1",
"hex"
);
console.log(sign(msgHash, privateKey).signature.toString("hex"));
The hdkey
submodule provides a library for keys derivation according to
BIP32.
It has almost the exact same API than the version 1.x
of
hdkey
from cryptocoinjs,
but it's backed by this package's primitives, and has built-in TypeScript types.
Its only difference is that it has to be be used with a named import.
This module exports a single class whose type is
class HDKey {
public static HARDENED_OFFSET: number;
public static fromMasterSeed(seed: Buffer, versions: Versions): HDKey;
public static fromExtendedKey(base58key: string, versions: Versions): HDKey;
public static fromJSON(json: { xpriv: string }): HDKey;
public versions: Versions;
public depth: number;
public index: number;
public chainCode: Buffer | null;
public privateKey: Buffer | null;
public publicKey: Buffer | null;
public fingerprint: number;
public parentFingerprint: number;
public pubKeyHash: Buffer | undefined;
public identifier: Buffer | undefined;
public privateExtendedKey: string;
public publicExtendedKey: string;
private constructor(versios: Versions);
public derive(path: string): HDKey;
public deriveChild(index: number): HDKey;
public sign(hash: Buffer): Buffer;
public verify(hash: Buffer, signature: Buffer): boolean;
public wipePrivateData(): this;
public toJSON(): { xpriv: string; xpub: string };
}
interface Versions {
private: number;
public: number;
}
const { HDKey } = require("ethereum-cryptography/hdkey");
const seed = "fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542";
const hdkey = HDKey.fromMasterSeed(Buffer.from(seed, "hex"));
const childkey = hdkey.derive("m/0/2147483647'/1");
console.log(childkey.privateExtendedKey);
The bip39
submodule provides functions to generate, validate and use seed
recovery phrases according to BIP39.
function generateMnemonic(wordlist: string[], strength: number = 128): string;
function mnemonicToEntropy(mnemonic: string, wordlist: string[]): Buffer;
function entropyToMnemonic(entropy: Buffer, wordlist: string[]): string;
function validateMnemonic(mnemonic: string, wordlist: string[]): boolean;
async function mnemonicToSeed(mnemonic: string, passphrase: string = ""): Promise<Buffer>;
function mnemonicToSeedSync(mnemonic: string, passphrase: string = ""): Buffer;
This submodule also contains the word lists defined by BIP39 for Czech, English, French, Italian, Japanese, Korean, Simplified and Traditional Chinese, and Spanish. These are not imported by default, as that would increase bundle sizes too much. Instead, you should import and use them explicitly.
The word lists are exported as a wordlist
variable in each of these submodules:
-
ethereum-cryptography/bip39/wordlists/czech.js
-
ethereum-cryptography/bip39/wordlists/english.js
-
ethereum-cryptography/bip39/wordlists/french.js
-
ethereum-cryptography/bip39/wordlists/italian.js
-
ethereum-cryptography/bip39/wordlists/japanese.js
-
ethereum-cryptography/bip39/wordlists/korean.js
-
ethereum-cryptography/bip39/wordlists/simplified-chinese.js
-
ethereum-cryptography/bip39/wordlists/spanish.js
-
ethereum-cryptography/bip39/wordlists/traditional-chinese.js
const { generateMnemonic } = require("ethereum-cryptography/bip39");
const { wordlist } = require("ethereum-cryptography/bip39/wordlists/english");
console.log(generateMnemonic(wordlist));
This package works with all the major Javascript bundlers. It is
tested with webpack
, Rollup
, Parcel
, and Browserify
.
For using it with Rollup
you need to use these plugins:
rollup-plugin-node-builtins
with thebrowser
option set totrue
, andpreferBuiltins
tofalse
.rollup-plugin-node-globals
rollup-plugin-json
.
If you are using this package in Node, you can install
ethereum-cryptography-native
to opt-in to use native implementations of some of the cryptographic primitives
provided by this package.
No extra work is needed for this to work. This package will detect that
ethereum-cryptography-native
is installed, and use it.
While installing ethereum-cryptography-native
will generally improve the
performance of your application, we recommend leaving the decision of installing
it to your users. It has multiple native dependencies that need to be compiled,
and this can be problematic in some environments.
This package intentionally excludes the the cryptographic primitives necessary to implement the following EIPs:
- EIP 196: Precompiled contracts for addition and scalar multiplication on the elliptic curve alt_bn128
- EIP 197: Precompiled contracts for optimal ate pairing check on the elliptic curve alt_bn128
- EIP 198: Big integer modular exponentiation
- EIP 152: Add Blake2 compression function
F
precompile
Feel free to open an issue if you want this decision to be reconsidered, or if you found another primitive that is missing.
ethereum-cryptography
is released under the MIT License.