Fastest 5KB JS implementation of secp256k1 signatures & ECDH.
The module is a sister project of noble-curves, focusing on smaller attack surface & better auditability. Curves are drop-in replacement and have more features: MSM, DER encoding, endomorphism, prehashing, custom point precomputes, hash-to-curve, oprf. To upgrade from earlier version, see Upgrading.
898-byte version of the library is available for learning purposes in test/misc/1kb.min.js,
it was created for the article Learning fast elliptic-curve cryptography.
noble-cryptography — high-security, easily auditable set of contained cryptographic libraries and tools.
npm install @noble/secp256k1
deno add jsr:@noble/secp256k1
We support all major platforms and runtimes. For React Native, additional polyfills are needed: see below.
import * as secp from '@noble/secp256k1';
(async () => {
const { secretKey, publicKey } = secp.keygen();
// const publicKey = secp.getPublicKey(secretKey);
const msg = new TextEncoder().encode('hello noble');
const sig = await secp.signAsync(msg, secretKey);
const isValid = await secp.verifyAsync(sig, msg, publicKey);
const bobsKeys = secp.keygen();
const shared = secp.getSharedSecret(secretKey, bobsKeys.publicKey); // Diffie-Hellman
const sigr = await secp.signAsync(msg, secretKey, { format: 'recovered' });
const publicKey2 = secp.recoverPublicKey(sigr, msg);
})();
// Schnorr signatures from BIP340
(async () => {
const schnorr = secp.schnorr;
const { secretKey, publicKey } = schnorr.keygen();
const msg = new TextEncoder().encode('hello noble');
const sig = await schnorr.signAsync(msg, secretKey);
const isValid = await schnorr.verifyAsync(sig, msg, publicKey);
})();
Only async methods are available by default, to keep the library dependency-free. To enable sync methods:
import { hmac } from '@noble/hashes/hmac.js';
import { sha256 } from '@noble/hashes/sha2.js';
secp.hashes.hmacSha256 = (key, msg) => hmac(sha256, key, msg);
secp.hashes.sha256 = sha256;
import 'react-native-get-random-values';
import { hmac } from '@noble/hashes/hmac.js';
import { sha256 } from '@noble/hashes/sha2.js';
secp.hashes.hmacSha256 = (key, msg) => hmac(sha256, key, msg);
secp.hashes.sha256 = sha256;
secp.hashes.hmacSha256Async = async (key, msg) => hmac(sha256, key, msg);
secp.hashes.sha256Async = async (msg) => sha256(msg);
There are 4 main methods, which accept Uint8Array-s:
keygen()getPublicKey(secretKey)sign(messageHash, secretKey) and signAsync(messageHash, secretKey)verify(signature, messageHash, publicKey) and verifyAsync(signature, messageHash, publicKey)import * as secp from '@noble/secp256k1';
(async () => {
const keys = secp.keygen();
const { secretKey, publicKey } = keys;
})();
import * as secp from '@noble/secp256k1';
const secretKey = secp.utils.randomSecretKey();
const pubKey33b = secp.getPublicKey(secretKey);
// Variants
const pubKey65b = secp.getPublicKey(secretKey, false);
const pubKeyPoint = secp.Point.fromBytes(pubKey65b);
const samePoint = pubKeyPoint.toBytes();
Generates 33-byte compressed (default) or 65-byte public key from 32-byte private key.
import * as secp from '@noble/secp256k1';
const { secretKey } = secp.keygen();
const msg = 'hello noble';
const sig = secp.sign(msg, secretKey);
// async
const sigB = await secp.signAsync(msg, secretKey);
// recovered, allows `recoverPublicKey(sigR, msg)`
const sigR = secp.sign(msg, secretKey, { format: 'recovered' });
// custom hash
import { keccak256 } from '@noble/hashes/sha3.js';
const sigH = secp.sign(keccak256(msg), secretKey, { prehash: false });
// hedged sig
const sigC = secp.sign(msg, secretKey, { extraEntropy: true });
const sigC2 = secp.sign(msg, secretKey, { extraEntropy: Uint8Array.from([0xca, 0xfe]) });
// malleable sig
const sigD = secp.sign(msg, secretKey, { lowS: false });
Generates low-s deterministic-k RFC6979 ECDSA signature.
{ prehash: false }.extraEntropy: true enables hedged signatures. They incorporate
extra randomness into RFC6979 (described in section 3.6),
to provide additional protection against fault attacks.
Check out blog post Deterministic signatures are not your friends.
Even if their RNG is broken, they will fall back to determinism.lowS: true prohibits signatures which have (sig.s >= CURVE.n/2n) and is compatible with BTC/ETH. Setting lowS: false allows to create malleable signatures, which is default openssl behavior. Non-malleable signatures can still be successfully verified in openssl.import * as secp from '@noble/secp256k1';
const { secretKey, publicKey } = secp.keygen();
const msg = 'hello noble';
const sig = secp.sign(msg, secretKey);
const isValid = secp.verify(sig, msg, publicKey);
// custom hash
import { keccak256 } from '@noble/hashes/sha3.js';
const sigH = secp.sign(keccak256(msg), secretKey, { prehash: false });
Verifies ECDSA signature.
{ prehash: false }.lowS: true prohibits malleable signatures which have (sig.s >= CURVE.n/2n) and
is compatible with BTC / ETH.
Setting lowS: false allows to create signatures, which is default openssl behavior.import * as secp from '@noble/secp256k1';
const alice = secp.keygen();
const bob = secp.keygen();
const shared33b = secp.getSharedSecret(alice.secretKey, bob.publicKey);
const shared65b = secp.getSharedSecret(bob.secretKey, alice.publicKey, false);
const sharedPoint = secp.Point.fromBytes(bob.publicKey).multiply(
secp.etc.secretKeyToScalar(alice.secretKey)
);
Computes ECDH (Elliptic Curve Diffie-Hellman) shared secret between key A and different key B.
import * as secp from '@noble/secp256k1';
const { secretKey, publicKey } = secp.keygen();
const msg = 'hello noble';
const sigR = secp.sign(msg, secretKey, { format: 'recovered' });
const publicKey2 = secp.recoverPublicKey(sigR, msg);
// custom hash
import { keccak256 } from '@noble/hashes/sha3.js';
const sigR = secp.sign(keccak256(msg), secretKey, { format: 'recovered', prehash: false });
const publicKey2 = secp.recoverPublicKey(sigR, keccak256(msg), { prehash: false });
Recover public key from Signature instance with recovery bit set.
import { schnorr } from '@noble/secp256k1';
const { secretKey, publicKey } = schnorr.keygen();
const msg = new TextEncoder().encode('hello noble');
const sig = schnorr.sign(msg, secretKey);
const isValid = schnorr.verify(sig, msg, publicKey);
const sig = await schnorr.signAsync(msg, secretKey);
const isValid = await schnorr.verifyAsync(sig, msg, publicKey);
Schnorr signatures compliant with BIP340 are supported.
A bunch of useful utilities are also exposed:
import * as secp from '@noble/secp256k1';
const { bytesToHex, hexToBytes, concatBytes, mod, invert, randomBytes } = secp.etc;
const { isValidSecretKey, isValidPublicKey, randomSecretKey } = secp.utils;
const { Point } = secp;
console.log(Point.CURVE(), Point.BASE);
/*
class Point {
static BASE: Point;
static ZERO: Point;
readonly X: bigint;
readonly Y: bigint;
readonly Z: bigint;
constructor(X: bigint, Y: bigint, Z: bigint);
static CURVE(): WeierstrassOpts<bigint>;
static fromAffine(ap: AffinePoint): Point;
static fromBytes(bytes: Bytes): Point;
static fromHex(hex: string): Point;
get x(): bigint;
get y(): bigint;
equals(other: Point): boolean;
is0(): boolean;
negate(): Point;
double(): Point;
add(other: Point): Point;
subtract(other: Point): Point;
multiply(n: bigint): Point;
multiplyUnsafe(scalar: bigint): Point;
toAffine(): AffinePoint;
assertValidity(): Point;
toBytes(isCompressed?: boolean): Bytes;
toHex(isCompressed?: boolean): string;
}
*/
The module is production-ready.
We cross-test against sister project noble-curves, which was audited and provides improved security.
We're targetting algorithmic constant time. JIT-compiler and Garbage Collector make "constant time" extremely hard to achieve timing attack resistance 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 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.
npm-diffFor this package, there are 0 dependencies; and a few dev dependencies:
We're deferring to built-in crypto.getRandomValues which is considered cryptographically secure (CSPRNG).
In the past, browsers had bugs that made it weak: it may happen again. Implementing a userspace CSPRNG to get resilient to the weakness is even worse: there is no reliable userspace source of quality entropy.
Cryptographically relevant quantum computer, if built, will allow to break elliptic curve cryptography (both ECDSA / EdDSA & ECDH) using Shor's algorithm.
Consider switching to newer / hybrid algorithms, such as SPHINCS+. They are available in noble-post-quantum.
NIST prohibits classical cryptography (RSA, DSA, ECDSA, ECDH) after 2035. Australian ASD prohibits it after 2030.
npm run bench
Benchmarks measured with Apple M4. noble-curves enable faster performance.
keygen x 7,643 ops/sec @ 130μs/op
sign x 7,620 ops/sec @ 131μs/op
verify x 823 ops/sec @ 1ms/op
getSharedSecret x 707 ops/sec @ 1ms/op
recoverPublicKey x 790 ops/sec @ 1ms/op
signAsync x 4,874 ops/sec @ 205μs/op
verifyAsync x 811 ops/sec @ 1ms/op
Point.fromBytes x 13,656 ops/sec @ 73μs/op
v3 brings the package closer to noble-curves v2.
keygen, keygenAsync method{prehash: false}{format: 'der'}.
This reduces malleabilitysignature.toBytes()hashes object. Also sha256 needs to be set now for prehash: true:// before
// etc.hmacSha256Sync = (key, ...messages) => hmac(sha256, key, etc.concatBytes(...messages));
// etc.hmacSha256Async = (key, ...messages) => Promise.resolve(etc.hmacSha256Sync(key, ...messages));
// after
hashes.hmacSha256 = (key, msg) => hmac(sha256, key, msg);
hashes.sha256 = sha256;
hashes.hmacSha256Async = async (key, msg) => hmac(sha256, key, msg);
hashes.sha256Async = async (msg) => sha256(msg);
v2 improves security and reduces attack surface. The goal of v2 is to provide minimum possible JS library which is safe and fast.
utils.precompute() for non-base pointgetPublicKey
isCompressed to false: getPublicKey(priv, false)sign
signAsync for async versionSignature instance with { r, s, recovery } propertiescanonical option was renamed to lowSrecovered option has been removed because recovery bit is always returned nowder option has been removed. There are 2 options:
fromCompact, toBytes, toCompactHex.
Compact encoding is simply a concatenation of 32-byte r and 32-byte s.verify
strict option was renamed to lowSgetSharedSecret
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)npm install && npm run build && npm test will build the code and run tests.npm run bench will run benchmarksnpm run build:release will build single non-module fileSee paulmillr.com/noble for useful resources, articles, documentation and demos related to the library.
The MIT License (MIT)
Copyright (c) 2019 Paul Miller (https://paulmillr.com)
See LICENSE file.