Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
J

js-ethereum-cryptography

> 编程语言
Open source

Audited pure JS library containing all Ethereum-related cryptographic primitives

755 stars0 likes2 views
WebsiteGitHub

About

Audited pure JS library containing all Ethereum-related cryptographic primitives

ethereum-cryptography

Audited pure JS library containing all Ethereum-related cryptographic primitives. Implemented with 6 noble & scure dependencies.

Check out Changelog / Upgrading and an article about the library: A safer, smaller, and faster Ethereum cryptography stack.

Usage

bash
npm install ethereum-cryptography

We explicitly support major browsers and Node.js on x86 and arm64. Other major runtimes and platforms are supported on a best-effort basis. Refer to engines field of package.json for runtime support information for each version. Tests are being ran with Webpack, Rollup, Parcel and Browserify.

This package has no single entry-point, but submodule for each cryptographic primitive. 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.

  • Usage
    • Dependencies
    • hashes: sha256, sha512, keccak, ripemd160, blake2b
    • kdfs: pbkdf2, scrypt
    • random: secure randomness
    • secp256k1: curve operations
    • bn: pairing-friendly curve
    • bls: pairing-friendly curve
    • aes: encryption
    • hdkey: bip32 HD wallets
    • bip39: mnemonic phrases
    • math: utilities
    • utils: generic utilities
    • secp256k1-compat: compatibility layer with other libraries
    • All imports
  • Caveats
    • Browser usage: Rollup setup
    • AES
      • Encrypting with passwords
      • Operation modes
      • Padding plaintext messages
      • How to use the IV parameter
      • How to handle errors with this module
  • Upgrading
    • Changelog
    • From v2 to v3
    • From v1 to v2
    • From v0.1 to v1
  • Security
  • License

Dependencies

All functionality of the module is simple re-export of 6 audited noble & scure libraries:

  • noble-curves, noble-ciphers, noble-hashes
  • scure-base, scure-bip32, scure-bip39

ethereum-cryptography pins versions of the libraries to ensure good protection against supply chain attacks. Ideally, your app would also pin version of ethereum-cryptography. That means, no ^3.1.0 - use 3.1.0 instead.

hashes: sha256, sha512, keccak, ripemd160, blake2b

…

kdfs: pbkdf2, scrypt

javascript
import { pbkdf2, pbkdf2Sync } from "ethereum-cryptography/pbkdf2.js";
import { scrypt, scryptSync } from "ethereum-cryptography/scrypt.js";
import { utf8ToBytes } from "ethereum-cryptography/utils.js";

// Pass Uint8Array, or convert strings to Uint8Array
const pass = utf8ToBytes("password");
const salt = utf8ToBytes("salt");
const iters = 131072;
const outLength = 32;
console.log(await pbkdf2(pass, salt, iters, outLength, "sha256"));

const N = 262144;
const r = 8;
const p = 1;
const outLengths = 32;
console.log(await scrypt(pass, salt, N, r, p, outLengths));

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 notes before using these submodules.

random: secure randomness

javascript
import { getRandomBytesSync } from "ethereum-cryptography/random.js";
console.log(getRandomBytesSync(32));

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.

secp256k1: curve operations

javascript
import { secp256k1 } from "ethereum-cryptography/secp256k1.js";
// You pass either a hex string, or Uint8Array
const privateKey =
  "6b911fd37cdf5c81d4c0adb1ab7fa822ed253ab0ad9aa18d77257c88b29b718e";
const messageHash =
  "a33321f98e4ff1c283c76998f14f57447545d339b3db534c6d886decb4209f28";
const publicKey = secp256k1.getPublicKey(privateKey);
const signature = secp256k1.sign(messageHash, privateKey);
const isSigned = secp256k1.verify(signature, messageHash, publicKey);

Elliptic curve operations on the curve secp256k1. Check out noble-curves docs for more info.

secp256k1 private keys need to be cryptographically secure random numbers with certain characteristics. If this is not the case, the security of secp256k1 is compromised.

bn: pairing-friendly curve

javascript
import { bn } from "ethereum-cryptography/bls.js";

console.log(bn254.G1, bn254.G2, bn254.pairing);

For example usage, check out the implementation of bn254 EVM precompiles.

bls: pairing-friendly curve

…

For example usage, check out the implementation of BLS EVM precompiles.

aes: encryption

…

hdkey: bip32 HD wallets

javascript
import { HDKey } from "ethereum-cryptography/hdkey.js";
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);

Hierarchical deterministic (HD) wallets that conform to BIP32.

bip39: mnemonic phrases

…

The bip39 submodule provides functions to generate, validate and use seed recovery phrases according to BIP39.

Wordlists for different languages are not imported by default, as that would increase bundle sizes too much. Instead, you should import and use them explicitly.

math: utilities

javascript
import { modPow, modInvert } from "ethereum-cryptography/math.js";
modPow(123n, 456n, 789n);
modInvert(22n, 5n);

utils: generic utilities

javascript
import { hexToBytes, toHex, utf8ToBytes } from "ethereum-cryptography/utils.js";

secp256k1-compat: compatibility layer with other libraries

javascript
import {
  createPrivateKeySync,
  ecdsaSign,
} from "ethereum-cryptography/secp256k1-compat";
const msgHash = Uint8Array.from(
  "82ff40c0a986c6a5cfad4ddf4c3aa6996f1a7837f9c398e17e5de5cbd5a12b28",
  "hex"
);
const privateKey = createPrivateKeySync();
console.log(Uint8Array.from(ecdsaSign(msgHash, privateKey).signature));

Warning: use secp256k1 instead. This module is only for users who upgraded from ethereum-cryptography v0.1. It could be removed in the future.

The API of secp256k1-compat is the same as secp256k1-node:

All imports

…

Caveats

Browser usage: Rollup setup

Using this library with Rollup requires the following plugins:

  • @rollup/plugin-commonjs
  • @rollup/plugin-node-resolve

These can be used by setting your plugins array like this:

javascript
plugins: [
  commonjs(),
  resolve({
    browser: true,
    preferBuiltins: false,
  }),
];

AES

Encrypting with passwords

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.

Operation modes

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.

Padding plaintext messages

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.

How to use the IV parameter

The iv parameter of the encrypt function must be unique, or the security of the encryption algorithm can be compromised.

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.

How to handle errors with this module

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.

Upgrading

Changelog

  • v3.0 (Sep 2024): new modules bls, bn, math change async AES to non-native sync, improve typescript compatibility, new dependency noble-ciphers
  • v2.0 (Apr 2023): switched [noble-secp256k1](http

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

TypeScriptaesbip32bls12-381bn254

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言