![38% of CISOs Fear They’re Not Moving Fast Enough on AI](https://cdn.sanity.io/images/cgdhsj6q/production/faa0bc28df98f791e11263f8239b34207f84b86f-1024x1024.webp?w=400&fit=max&auto=format)
Security News
38% of CISOs Fear They’re Not Moving Fast Enough on AI
CISOs are racing to adopt AI for cybersecurity, but hurdles in budgets and governance may leave some falling behind in the fight against cyber threats.
@noble/secp256k1
Advanced tools
Fastest 4KB JS implementation of secp256k1 ECDH & ECDSA signatures compliant with RFC6979
@noble/secp256k1 is a JavaScript library for elliptic curve cryptography, specifically for the secp256k1 curve. It is commonly used in blockchain and cryptocurrency applications for key generation, signing, and verification.
Key Generation
This feature allows you to generate a random private key and derive the corresponding public key using the secp256k1 curve.
const secp = require('@noble/secp256k1');
const privateKey = secp.utils.randomPrivateKey();
const publicKey = secp.getPublicKey(privateKey);
console.log('Private Key:', privateKey);
console.log('Public Key:', publicKey);
Signing
This feature allows you to sign a message using a private key. The message is an array of bytes, and the signature is generated using the secp256k1 curve.
const secp = require('@noble/secp256k1');
const message = new Uint8Array([1, 2, 3]);
const privateKey = secp.utils.randomPrivateKey();
const signature = secp.sign(message, privateKey);
console.log('Signature:', signature);
Verification
This feature allows you to verify a signature using the corresponding public key and the original message. It returns a boolean indicating whether the signature is valid.
const secp = require('@noble/secp256k1');
const message = new Uint8Array([1, 2, 3]);
const privateKey = secp.utils.randomPrivateKey();
const publicKey = secp.getPublicKey(privateKey);
const signature = secp.sign(message, privateKey);
const isValid = secp.verify(signature, message, publicKey);
console.log('Is the signature valid?', isValid);
Elliptic is a widely-used JavaScript library for elliptic curve cryptography. It supports multiple curves, including secp256k1. Compared to @noble/secp256k1, elliptic is more versatile but may be less optimized for performance in secp256k1-specific use cases.
Secp256k1 is a native Node.js binding to the secp256k1 library used in Bitcoin. It is highly optimized for performance but requires native compilation, which can be a drawback for some users. @noble/secp256k1, being a pure JavaScript implementation, is easier to use in browser environments.
BitcoinJS is a library for Bitcoin-related operations, including key generation, signing, and verification using secp256k1. While it offers a broader range of Bitcoin-specific functionalities, it is less focused on general elliptic curve cryptography compared to @noble/secp256k1.
Fastest 4KB 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: Common.js, Schnorr signatures, DER encoding or support for different hash functions. To upgrade from v1 to v2, see Upgrading.
noble-cryptography — high-security, easily auditable set of contained cryptographic libraries and tools.
npm install @noble/secp256k1
deno add @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';
// import * as secp from "https://unpkg.com/@noble/secp256k1"; // Unpkg
(async () => {
// Uint8Arrays or hex strings are accepted:
// Uint8Array.from([0xde, 0xad, 0xbe, 0xef]) is equal to 'deadbeef'
const privKey = secp.utils.randomPrivateKey(); // Secure random private key
// sha256 of 'hello world'
const msgHash = 'b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9';
const pubKey = secp.getPublicKey(privKey);
const signature = await secp.signAsync(msgHash, privKey); // Sync methods below
const isValid = secp.verify(signature, msgHash, pubKey);
const alicesPubkey = secp.getPublicKey(secp.utils.randomPrivateKey());
secp.getSharedSecret(privKey, alicesPubkey); // Elliptic curve diffie-hellman
signature.recoverPublicKey(msgHash); // Public key recovery
})();
Additional polyfills for some environments:
// 1. Enable synchronous methods.
// Only async methods are available by default, to keep the library dependency-free.
import { hmac } from '@noble/hashes/hmac';
import { sha256 } from '@noble/hashes/sha256';
secp.etc.hmacSha256Sync = (k, ...m) => hmac(sha256, k, secp.etc.concatBytes(...m));
// Sync methods can be used now:
// secp.sign(msgHash, privKey);
// 2. node.js 18 and older, requires polyfilling globalThis.crypto
import { webcrypto } from 'node:crypto';
// @ts-ignore
if (!globalThis.crypto) globalThis.crypto = webcrypto;
// 3. React Native needs crypto.getRandomValues polyfill and sha512
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));
There are 3 main methods: getPublicKey(privateKey)
,
sign(messageHash, privateKey)
and
verify(signature, messageHash, publicKey)
.
We accept Hex type everywhere:
type Hex = Uint8Array | string;
function getPublicKey(privateKey: Hex, isCompressed?: boolean): Uint8Array;
Generates 33-byte compressed public key from 32-byte private key.
false
.ProjectivePoint.fromPrivateKey(privateKey)
for Point instance.ProjectivePoint.fromHex(publicKey)
to convert Hex / Uint8Array into Point.function sign(
messageHash: Hex, // message hash (not message) which would be signed
privateKey: Hex, // private key which will sign the hash
opts?: { lowS: boolean; extraEntropy: boolean | Hex } // optional params
): Signature;
function signAsync(
messageHash: Hex,
privateKey: Hex,
opts?: { lowS: boolean; extraEntropy: boolean | Hex }
): Promise<Signature>;
sign(msgHash, privKey, { lowS: false }); // Malleable signature
sign(msgHash, privKey, { extraEntropy: true }); // Improved security
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:
k
gen.
Exposing k
could leak private keysr
/ s
, which means they
would still be valid, but may break some test vectors if you're
cross-testing against other libsfunction verify(
signature: Hex | Signature, // returned by the `sign` function
messageHash: Hex, // message hash (not message) that must be verified
publicKey: Hex, // public (not private) key
opts?: { lowS: boolean } // optional params; { lowS: true } by default
): boolean;
Verifies ECDSA signature and ensures it has lowS (compatible with BTC/ETH).
lowS: false
turns off malleability check, but makes it OpenSSL-compatible.
function getSharedSecret(
privateKeyA: Uint8Array | string, // Alices's private key
publicKeyB: Uint8Array | string, // Bob's public key
isCompressed = true // optional arg. (default) true=33b key, false=65b.
): 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
signature.recoverPublicKey(
msgHash: Uint8Array | string
): Uint8Array | undefined;
Recover public key from Signature instance with recovery
bit set.
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; // Uses CSPRNG https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues
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; // curve prime; order; equation params, generator coordinates
The module is production-ready. While noble-curves provide improved security, we cross-test against curves.
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. Nonetheless we're targetting algorithmic constant time.
npm-diff
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 install. Our goal is to minimize this attack vector.
If you see anything unusual: investigate and report.
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.
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
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:
utils.precompute()
for non-base pointOther changes for upgrading from @noble/secp256k1 1.7 to 2.0:
getPublicKey
isCompressed
to false
: getPublicKey(priv, false)
sign
signAsync
for async versionSignature
instance with { r, s, recovery }
propertiescanonical
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:
fromCompact
, toCompactRawBytes
, toCompactHex
.
Compact encoding is simply a concatenation of 32-byte r and 32-byte s.verify
strict
option was renamed to lowS
getSharedSecret
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 benchmarks, which may need their deps first (npm run bench:install
)npm run loc
will count total output size, important to be less than 4KBCheck out github.com/paulmillr/guidelines for general coding practices and rules.
See paulmillr.com/noble for useful resources, articles, documentation and demos related to the library.
MIT (c) Paul Miller (https://paulmillr.com), see LICENSE file.
FAQs
Fastest 4KB JS implementation of secp256k1 ECDH & ECDSA signatures compliant with RFC6979
The npm package @noble/secp256k1 receives a total of 269,795 weekly downloads. As such, @noble/secp256k1 popularity was classified as popular.
We found that @noble/secp256k1 demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer 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
CISOs are racing to adopt AI for cybersecurity, but hurdles in budgets and governance may leave some falling behind in the fight against cyber threats.
Research
Security News
Socket researchers uncovered a backdoored typosquat of BoltDB in the Go ecosystem, exploiting Go Module Proxy caching to persist undetected for years.
Security News
Company News
Socket is joining TC54 to help develop standards for software supply chain security, contributing to the evolution of SBOMs, CycloneDX, and Package URL specifications.