Security News
JSR Working Group Kicks Off with Ambitious Roadmap and Plans for Open Governance
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
ethereum-cryptography
Advanced tools
The ethereum-cryptography package provides a set of cryptographic functions that are commonly used in Ethereum-related projects. It includes functionalities such as hashing, key derivation, and signature verification, which are essential for creating and managing Ethereum wallets, signing transactions, and ensuring secure communication within the Ethereum network.
Keccak-256 Hashing
This feature allows you to compute the Keccak-256 hash of an input, which is a common cryptographic hash function used in Ethereum for various purposes, including hashing transaction data.
const { keccak256 } = require('ethereum-cryptography/keccak');
const hash = keccak256(Buffer.from('hello'));
Public Key Recovery
This feature enables the recovery of a public key from a signature, which is useful for verifying the signer of a message or transaction in Ethereum.
const { ecdsaRecover } = require('ethereum-cryptography/secp256k1');
const publicKey = ecdsaRecover(signature, recovery, hash, compressed);
BIP39 Mnemonic Generation
This feature is used to generate a BIP39 mnemonic phrase, which can be used to derive a wallet's private keys in a human-readable form.
const { generateMnemonic } = require('ethereum-cryptography/bip39');
const mnemonic = generateMnemonic();
The web3 package is a collection of libraries that allow you to interact with a local or remote Ethereum node using HTTP, IPC, or WebSocket. It includes similar cryptographic functionalities for signing transactions, generating accounts, and handling smart contract interactions.
Ethers is a lightweight JavaScript library that aims to be a complete and compact library for interacting with the Ethereum Blockchain and its ecosystem. It provides utilities for wallet creation, signing, and transaction building, similar to ethereum-cryptography but with a broader scope including full Ethereum node interaction.
Crypto-browserify is a port of Node.js' crypto module to the browser. It offers a range of cryptographic functions, including hashing and encryption, which can be used in Ethereum-related applications, although it is not specifically tailored to Ethereum's cryptography needs.
All pure-js cryptographic primitives normally used when developing Javascript / TypeScript applications and tools for Ethereum.
January 2022 update: We've released v1.0 of the package, a complete rewrite:
The cryptographic primitives included are:
Use NPM / Yarn in node.js / browser:
# NPM
npm install ethereum-cryptography
# Yarn
yarn add ethereum-cryptography
See browser usage for information on using the package with major Javascript bundlers. It is tested with Webpack, Rollup, Parcel and Browserify.
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.
// Hashes
const { sha256 } = require("ethereum-cryptography/sha256");
const { keccak256 } = require("ethereum-cryptography/keccak");
const { ripemd160 } = require("ethereum-cryptography/ripemd160");
const { blake2b } = require("ethereum-cryptography/blake2b");
// KDFs
const { pbkdf2Sync } = require("ethereum-cryptography/pbkdf2");
const { scryptSync } = require("ethereum-cryptography/scrypt");
// Random
const { getRandomBytesSync } = require("ethereum-cryptography/random");
// AES encryption
const { encrypt } = require("ethereum-cryptography/aes");
// secp256k1 elliptic curve operations
const { createPrivateKeySync, ecdsaSign } = require("ethereum-cryptography/secp256k1");
// BIP32 HD Keygen, BIP39 Mnemonic Phrases
const { HDKey } = require("ethereum-cryptography/hdkey");
const { generateMnemonic } = require("ethereum-cryptography/bip39");
const { wordlist } = require("ethereum-cryptography/bip39/wordlists/english");
// utilities
const { hexToBytes, toHex, utf8ToBytes } = require("ethereum-cryptography/utils");
function sha256(msg: Uint8Array): Uint8Array;
function sha512(msg: Uint8Array): Uint8Array;
function keccak256(msg: Uint8Array): Uint8Array;
function ripemd160(msg: Uint8Array): Uint8Array;
function blake2b(msg: Uint8Array, outputLength = 64): Uint8Array;
Exposes following cryptographic hash functions:
keccak224
, keccak384
,
and keccak512
)const { sha256 } = require("ethereum-cryptography/sha256");
const { sha512 } = require("ethereum-cryptography/sha512");
const { keccak256, keccak224, keccak384, keccak512 } = require("ethereum-cryptography/keccak");
const { ripemd160 } = require("ethereum-cryptography/ripemd160");
const { blake2b } = require("ethereum-cryptography/blake2b");
sha256(Uint8Array.from([1, 2, 3]))
// Can be used with strings
const { utf8ToBytes } = require("ethereum-cryptography/utils");
sha256(utf8ToBytes("abc"))
// If you need hex
const { bytesToHex as toHex } = require("ethereum-cryptography/utils");
toHex(sha256(utf8ToBytes("abc")))
function pbkdf2(password: Uint8Array, salt: Uint8Array, iterations: number, keylen: number, digest: string): Promise<Uint8Array>;
function pbkdf2Sync(password: Uint8Array, salt: Uint8Array, iterations: number, keylen: number, digest: string): Uint8Array;
function scrypt(password: Uint8Array, salt: Uint8Array, N: number, p: number, r: number, dkLen: number, onProgress?: (progress: number) => void): Promise<Uint8Array>;
function scryptSync(password: Uint8Array, salt: Uint8Array, N: number, p: number, r: number, dkLen: number, onProgress?: (progress: number) => void)): Uint8Array;
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. The KDF supports sha256
and sha512
digests.
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 these submodules.
const { pbkdf2 } = require("ethereum-cryptography/pbkdf2");
const { utf8ToBytes } = require("ethereum-cryptography/utils");
// Pass Uint8Array, or convert strings to Uint8Array
console.log(await pbkdf2(utf8ToBytes("password"), utf8ToBytes("salt"), 131072, 32, "sha256"));
const { scrypt } = require("ethereum-cryptography/scrypt");
const { utf8ToBytes } = require("ethereum-cryptography/utils");
console.log(await scrypt(utf8ToBytes("password"), utf8ToBytes("salt"), 262144, 8, 1, 32));
function getRandomBytes(bytes: number): Promise<Uint8Array>;
function getRandomBytesSync(bytes: number): Uint8Array;
The random
submodule has functions to generate cryptographically strong
pseudo-random data in synchronous and asynchronous ways.
Backed by crypto.getRandomValues
in browser and by crypto.randomBytes
in node.js. If backends are somehow not available, the module would throw an error and won't work, as keeping them working would be insecure.
const { getRandomBytesSync } = require("ethereum-cryptography/random");
console.log(getRandomBytesSync(32));
function getPublicKey(privateKey: Uint8Array, isCompressed?: false): Uint8Array;
function getSharedSecret(privateKeyA: Uint8Array, publicKeyB: Uint8Array): Uint8Array;
function sign(msgHash: Uint8Array, privateKey: Uint8Array, opts?: Options): Promise<Uint8Array>;
function signSync(msgHash: Uint8Array, privateKey: Uint8Array, opts?: Options): Uint8Array;
function verify(signature: Uint8Array, msgHash: Uint8Array, publicKey: Uint8Array): boolean
function recoverPublicKey(msgHash: Uint8Array, signature: Uint8Array, recovery: number): Uint8Array | undefined;
function utils.randomPrivateKey(): Uint8Array;
The secp256k1
submodule provides a library for elliptic curve operations on
the curve secp256k1. For detailed documentation, follow README of noble-secp256k1
, which the module uses as a backend.
secp256k1 private keys need to be cryptographically secure random numbers with
certain caracteristics. If this is not the case, the security of secp256k1 is
compromised. We strongly recommend using utils.randomPrivateKey()
to generate them.
const secp = require("ethereum-cryptography/secp256k1");
(async () => {
// You pass either a hex string, or Uint8Array
const privateKey = "6b911fd37cdf5c81d4c0adb1ab7fa822ed253ab0ad9aa18d77257c88b29b718e";
const messageHash = "a33321f98e4ff1c283c76998f14f57447545d339b3db534c6d886decb4209f28";
const publicKey = secp.getPublicKey(privateKey);
const signature = await secp.sign(messageHash, privateKey);
const isSigned = secp.verify(signature, messageHash, publicKey);
})();
Note: if you've been using ethereum-cryptography v0.1, it had different API. We're providing a compatibility layer for users who want to upgrade without hassle. Check out the legacy documentation.
Hierarchical deterministic (HD) wallets that conform to BIP32 standard. Also available as standalone package scure-bip32.
This module exports a single class HDKey
, which should be used like this:
const { HDKey } = require("ethereum-cryptography/hdkey");
const hdkey1 = HDKey.fromMasterSeed(seed);
const hdkey2 = HDKey.fromExtendedKey(base58key);
const hdkey3 = HDKey.fromJSON({ xpriv: string });
// props
[hdkey1.depth, hdkey1.index, hdkey1.chainCode];
console.log(hdkey2.privateKey, hdkey2.publicKey);
console.log(hdkey3.derive("m/0/2147483647'/1"));
const sig = hdkey3.sign(hash);
hdkey3.verify(hash, sig);
Note: chainCode
property is essentially a private part
of a secret "master" key, it should be guarded from unauthorized access.
The full API is:
class HDKey {
public static HARDENED_OFFSET: number;
public static fromMasterSeed(seed: Uint8Array, versions: Versions): HDKey;
public static fromExtendedKey(base58key: string, versions: Versions): HDKey;
public static fromJSON(json: { xpriv: string }): HDKey;
readonly versions: Versions;
readonly depth: number = 0;
readonly index: number = 0;
readonly chainCode: Uint8Array | null = null;
readonly parentFingerprint: number = 0;
get fingerprint(): number;
get identifier(): Uint8Array | undefined;
get pubKeyHash(): Uint8Array | undefined;
get privateKey(): Uint8Array | null;
get publicKey(): Uint8Array | null;
get privateExtendedKey(): string;
get publicExtendedKey(): string;
derive(path: string): HDKey;
deriveChild(index: number): HDKey;
sign(hash: Uint8Array): Uint8Array;
verify(hash: Uint8Array, signature: Uint8Array): boolean;
wipePrivateData(): this;
}
interface Versions {
private: number;
public: number;
}
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.
The implementation is loosely based on hdkey, which has MIT License.
function generateMnemonic(wordlist: string[], strength: number = 128): string;
function mnemonicToEntropy(mnemonic: string, wordlist: string[]): Uint8Array;
function entropyToMnemonic(entropy: Uint8Array, wordlist: string[]): string;
function validateMnemonic(mnemonic: string, wordlist: string[]): boolean;
async function mnemonicToSeed(mnemonic: string, passphrase: string = ""): Promise<Uint8Array>;
function mnemonicToSeedSync(mnemonic: string, passphrase: string = ""): Uint8Array;
The bip39
submodule provides functions to generate, validate and use seed
recovery phrases according to BIP39.
Also available as standalone package scure-bip39.
const { generateMnemonic } = require("ethereum-cryptography/bip39");
const { wordlist } = require("ethereum-cryptography/bip39/wordlists/english");
console.log(generateMnemonic(wordlist));
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
function encrypt(msg: Uint8Array, key: Uint8Array, iv: Uint8Array, mode = "aes-128-ctr", pkcs7PaddingEnabled = true): Promise<Uint8Array>;
function decrypt(cypherText: Uint8Array, key: Uint8Array, iv: Uint8Array, mode = "aes-128-ctr", pkcs7PaddingEnabled = true): Promise<Uint8Array>;
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. If you are using this module in a new application, we recommend using the default.
While this module may work with any mode supported by OpenSSL, we only test it
with aes-128-ctr
, aes-128-cbc
, and aes-256-cbc
. If you use another module
a warning will be printed in the console.
We only recommend using aes-128-cbc
and aes-256-cbc
to decrypt already
encrypted data.
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
.
This option is only present to enable the decryption of already encrypted data. To encrypt new data, we recommend using the default.
The iv
parameter of the encrypt
function must be unique, or the security
of the encryption algorithm can be compromissed.
You can generate a new iv
using the random
module.
Note that to decrypt a value, you have to provide the same iv
used to encrypt
it.
Sensitive information can be leaked via error messages when using this module. To avoid this, you should make sure that the errors you return don't contain the exact reason for the error. Instead, errors must report general encryption/decryption failures.
Note that implementing this can mean catching all errors that can be thrown when calling on of this module's functions, and just throwing a new generic exception.
const { encrypt } = require("ethereum-cryptography/aes");
const { hexToBytes, utf8ToBytes } = require("ethereum-cryptography/utils");
console.log(
encrypt(
utf8ToBytes("message"),
hexToBytes("2b7e151628aed2a6abf7158809cf4f3c"),
hexToBytes("f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff")
)
);
Using this library with Rollup requires the following plugins:
These can be used by setting your plugins
array like this:
plugins: [
commonjs(),
resolve({
browser: true,
preferBuiltins: false,
}),
]
Note: consider using secp256k1
instead;
This module is only for users who upgraded
from ethereum-cryptography v0.1. It could be removed in the future,
but we're keeping it around for now, for backwards-compatibility.
The API of secp256k1-compat
is the same as secp256k1-node:
const { createPrivateKeySync, ecdsaSign } = require("ethereum-cryptography/secp256k1-compat");
const msgHash = Uint8Array.from(
"82ff40c0a986c6a5cfad4ddf4c3aa6996f1a7837f9c398e17e5de5cbd5a12b28",
"hex"
);
const privateKey = createPrivateKeySync();
console.log(Uint8Array.from(ecdsaSign(msgHash, privateKey).signature));
This package intentionally excludes the the cryptographic primitives necessary to implement the following EIPs:
F
precompileFeel free to open an issue if you want this decision to be reconsidered, or if you found another primitive that is missing.
Version 1.0 changes from 0.1:
Same functionality, all old APIs remain the same except for the breaking changes:
Uint8Array
from all methods that worked with Buffer
before.
Buffer
has never been supported in browsers, while Uint8Array
s are supported natively in both
browsers and node.js.ethereum-cryptography@0.1
secp256k1
, rename it to secp256k1-compat
const { sha256 } = require("ethereum-cryptography/sha256");
// Old usage
const hasho = sha256(Buffer.from("string", "utf8")).toString("hex");
// New usage
const { toHex } = require("ethereum-cryptography/utils");
const hashn = toHex(sha256("string"));
// If you have `Buffer` module and want to preserve it:
const hashb = Buffer.from(sha256("string"));
const hashbo = hashb.toString("hex");
Audited by Cure53 on Jan 5, 2022. Check out the audit PDF & URL.
ethereum-cryptography
is released under The MIT License (MIT)
Copyright (c) 2021 Patricio Palladino, Paul Miller, ethereum-cryptography contributors
See LICENSE file.
hdkey
is loosely based on hdkey,
which had MIT License
Copyright (c) 2018 cryptocoinjs
FAQs
All the cryptographic primitives used in Ethereum
The npm package ethereum-cryptography receives a total of 1,480,118 weekly downloads. As such, ethereum-cryptography popularity was classified as popular.
We found that ethereum-cryptography demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
Security News
Research
An advanced npm supply chain attack is leveraging Ethereum smart contracts for decentralized, persistent malware control, evading traditional defenses.
Security News
Research
Attackers are impersonating Sindre Sorhus on npm with a fake 'chalk-node' package containing a malicious backdoor to compromise developers' projects.