noble-secp256k1
Fastest 4KB JS implementation of secp256k1 signatures & ECDH.
- ✍️ Deterministic ECDSA
signatures compliant with RFC6979
- 🤝 Elliptic Curve Diffie-Hellman ECDH
- 📦 Pure ESM, can be imported without transpilers
- 🪶 4KB gzipped, 450 lines of code
Use larger drop-in replacement noble-curves instead,
if you need additional features such as common.js, Schnorr signatures, DER encoding or support for different hash functions. To upgrade from v1 to v2, see Upgrading.
This library belongs to noble cryptography
noble-cryptography — high-security, easily auditable set of contained cryptographic libraries and tools.
Usage
npm install @noble/secp256k1
We support all major platforms and runtimes. For node.js <= 18 and React Native, additional polyfills are needed: see below.
import * as secp from '@noble/secp256k1';
(async () => {
const privKey = secp.utils.randomPrivateKey();
const msgHash = 'b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9';
const pubKey = secp.getPublicKey(privKey);
const signature = await secp.signAsync(msgHash, privKey);
const isValid = secp.verify(signature, msgHash, pubKey);
const alicesPubkey = secp.getPublicKey(secp.utils.randomPrivateKey());
secp.getSharedSecret(privKey, alicesPubkey);
signature.recoverPublicKey(msgHash);
})();
Additional polyfills for some environments:
import { hmac } from '@noble/hashes/hmac';
import { sha256 } from '@noble/hashes/sha256';
secp.etc.hmacSha256Sync = (k, ...m) => hmac(sha256, k, secp.etc.concatBytes(...m))
import { webcrypto } from 'node:crypto';
if (!globalThis.crypto) globalThis.crypto = webcrypto;
import 'react-native-get-random-values';
import { hmac } from '@noble/hashes/hmac';
import { sha256 } from '@noble/hashes/sha256';
secp.etc.hmacSha256Sync = (k, ...m) => hmac(sha256, k, secp.etc.concatBytes(...m));
secp.etc.hmacSha256Async = (k, ...m) => Promise.resolve(secp.etc.hmacSha256Sync(k, ...m));
API
There are 3 main methods: getPublicKey(privateKey)
,
sign(messageHash, privateKey)
and
verify(signature, messageHash, publicKey)
.
We accept Hex type everywhere:
type Hex = Uint8Array | string
getPublicKey
function getPublicKey(privateKey: Hex, isCompressed?: boolean): Uint8Array;
Generates 33-byte compressed public key from 32-byte private key.
- If you need uncompressed 65-byte public key, set second argument to
false
. - Use
ProjectivePoint.fromPrivateKey(privateKey)
for Point instance. - Use
ProjectivePoint.fromHex(publicKey)
to convert Hex / Uint8Array into Point.
sign
function sign(
messageHash: Hex,
privateKey: Hex,
opts?: { lowS: boolean, extraEntropy: boolean | Hex }
): Signature;
function signAsync(
messageHash: Hex,
privateKey: Hex,
opts?: { lowS: boolean; extraEntropy: boolean | Hex }
): Promise<Signature>;
sign(msgHash, privKey, { lowS: false });
sign(msgHash, privKey, { extraEntropy: true });
Generates low-s deterministic-k RFC6979 ECDSA signature. Assumes hash of message,
which means you'll need to do something like sha256(message)
before signing.
lowS: false
allows to create malleable signatures, for compatibility with openssl.
Default lowS: true
prohibits signatures which have (sig.s >= CURVE.n/2n) and is compatible with BTC/ETH.extraEntropy: true
improves security by adding entropy, follows section 3.6 of RFC6979:
- No disadvantage: if an entropy generator is broken, sigs would be the same
as they are without the option
- It would help a lot in case there is an error somewhere in
k
gen.
Exposing k
could leak private keys - Sigs with extra entropy would have different
r
/ s
, which means they
would still be valid, but may break some test vectors if you're
cross-testing against other libs
verify
function verify(
signature: Hex | Signature,
messageHash: Hex,
publicKey: Hex,
opts?: { lowS: boolean }
): boolean;
Verifies ECDSA signature and ensures it has lowS (compatible with BTC/ETH).
lowS: false
turns off malleability check, but makes it OpenSSL-compatible.
getSharedSecret
function getSharedSecret(
privateKeyA: Uint8Array | string,
publicKeyB: Uint8Array | string,
isCompressed = true
): Uint8Array;
Computes ECDH (Elliptic Curve Diffie-Hellman) shared secret between
key A and different key B.
Use ProjectivePoint.fromHex(publicKeyB).multiply(privateKeyA)
for Point instance
recoverPublicKey
signature.recoverPublicKey(
msgHash: Uint8Array | string
): Uint8Array | undefined;
Recover public key from Signature instance with recovery
bit set.
utils
A bunch of useful utilities are also exposed:
type Bytes = Uint8Array;
const etc: {
hexToBytes: (hex: string) => Bytes;
bytesToHex: (b: Bytes) => string;
concatBytes: (...arrs: Bytes[]) => Bytes;
bytesToNumberBE: (b: Bytes) => bigint;
numberToBytesBE: (num: bigint) => Bytes;
mod: (a: bigint, b?: bigint) => bigint;
invert: (num: bigint, md?: bigint) => bigint;
hmacSha256Async: (key: Bytes, ...msgs: Bytes[]) => Promise<Bytes>;
hmacSha256Sync: HmacFnSync;
hashToPrivateKey: (hash: Hex) => Bytes;
randomBytes: (len: number) => Bytes;
};
const utils: {
normPrivateKeyToScalar: (p: PrivKey) => bigint;
randomPrivateKey: () => Bytes;
isValidPrivateKey: (key: Hex) => boolean;
precompute(p: ProjectivePoint, windowSize?: number): ProjectivePoint;
};
class ProjectivePoint {
constructor(px: bigint, py: bigint, pz: bigint);
static readonly BASE: ProjectivePoint;
static readonly ZERO: ProjectivePoint;
static fromAffine(point: AffinePoint): ProjectivePoint;
static fromHex(hex: Hex): ProjectivePoint;
static fromPrivateKey(n: PrivKey): ProjectivePoint;
get x(): bigint;
get y(): bigint;
add(other: ProjectivePoint): ProjectivePoint;
assertValidity(): void;
equals(other: ProjectivePoint): boolean;
multiply(n: bigint): ProjectivePoint;
negate(): ProjectivePoint;
subtract(other: ProjectivePoint): ProjectivePoint;
toAffine(): AffinePoint;
toHex(isCompressed?: boolean): string;
toRawBytes(isCompressed?: boolean): Bytes;
}
class Signature {
constructor(r: bigint, s: bigint, recovery?: number | undefined);
static fromCompact(hex: Hex): Signature;
readonly r: bigint;
readonly s: bigint;
readonly recovery?: number | undefined;
ok(): Signature;
hasHighS(): boolean;
normalizeS(): Signature;
recoverPublicKey(msgh: Hex): Point;
toCompactRawBytes(): Bytes;
toCompactHex(): string;
}
CURVE
Security
The module is production-ready.
It is cross-tested against noble-curves,
and has similar security.
- The current version is rewrite of v1, which has been audited by cure53:
PDF (funded by Umbra.cash & community).
- It's being fuzzed by Guido Vranken's cryptofuzz:
run the fuzzer by yourself to check.
Our EC multiplication is hardened to be algorithmically constant time.
We're using built-in JS BigInt
, which is potentially vulnerable to
timing attacks as
per MDN.
But, JIT-compiler and Garbage Collector make "constant time" extremely hard
to achieve in a scripting language. Which means any other JS library doesn't
use constant-time bigints. Including bn.js or anything else.
Even statically typed Rust, a language without GC,
makes it harder to achieve constant-time
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.
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.
As for key generation, we're deferring to built-in
crypto.getRandomValues
which is considered cryptographically secure (CSPRNG).
Speed
Use noble-curves if you need even higher performance.
Benchmarks measured with Apple M2 on MacOS 13 with node.js 20.
getPublicKey(utils.randomPrivateKey()) x 6,430 ops/sec @ 155μs/op
sign x 3,367 ops/sec @ 296μs/op
verify x 600 ops/sec @ 1ms/op
getSharedSecret x 505 ops/sec @ 1ms/op
recoverPublicKey x 612 ops/sec @ 1ms/op
Point.fromHex (decompression) x 9,185 ops/sec @ 108μs/op
Compare to other libraries on M1 (openssl
uses native bindings, not JS):
elliptic#getPublicKey x 1,940 ops/sec
sjcl#getPublicKey x 211 ops/sec
elliptic#sign x 1,808 ops/sec
sjcl#sign x 199 ops/sec
openssl#sign x 4,243 ops/sec
ecdsa#sign x 116 ops/sec
elliptic#verify x 812 ops/sec
sjcl#verify x 166 ops/sec
openssl#verify x 4,452 ops/sec
ecdsa#verify x 80 ops/sec
elliptic#ecdh x 971 ops/sec
Contributing
- Clone the repository.
npm install
to install build dependencies like TypeScriptnpm run build
to compile TypeScript codenpm test
to run jest on test/index.ts
Special thanks to Roman Koblov, who have
helped to improve scalar multiplication speed.
Upgrading
noble-secp256k1 v2 features improved security and smaller attack surface.
The goal of v2 is to provide minimum possible JS library which is safe and fast.
That means the library was reduced 4x, to just over 400 lines. In order to
achieve the goal, some features were moved to
noble-curves, which is
even safer and faster drop-in replacement library with same API.
Switch to curves if you intend to keep using these features:
- DER encoding: toDERHex, toDERRawBytes, signing / verification of DER sigs
- Schnorr signatures
- Using
utils.precompute()
for non-base point - Support for environments which don't support bigint literals
- Common.js support
- Support for node.js 18 and older without shim
Other changes for upgrading from @noble/secp256k1 1.7 to 2.0:
getPublicKey
- now produce 33-byte compressed signatures by default
- to use old behavior, which produced 65-byte uncompressed keys, set
argument
isCompressed
to false
: getPublicKey(priv, false)
sign
- is now sync; use
signAsync
for async version - now returns
Signature
instance with { r, s, recovery }
properties canonical
option was renamed to lowS
recovered
option has been removed because recovery bit is always returned nowder
option has been removed. There are 2 options:
- Use compact encoding:
fromCompact
, toCompactRawBytes
, toCompactHex
.
Compact encoding is simply a concatenation of 32-byte r and 32-byte s. - If you must use DER encoding, switch to noble-curves (see above).
verify
strict
option was renamed to lowS
getSharedSecret
- now produce 33-byte compressed signatures by default
- to use old behavior, which produced 65-byte uncompressed keys, set
argument
isCompressed
to false
: getSharedSecret(a, b, false)
recoverPublicKey(msg, sig, rec)
was changed to sig.recoverPublicKey(msg)
number
type for private keys have been removed: use bigint
insteadPoint
(2d xy) has been changed to ProjectivePoint
(3d xyz)utils
were split into utils
(same api as in noble-curves) and
etc
(hmacSha256Sync
and others)
License
MIT (c) Paul Miller (https://paulmillr.com), see LICENSE file.