{"name":"@noble/curves","version":"1.8.1","description":"Audited & minimal JS implementation of elliptic curve cryptography","scripts":{"bench":"cd benchmark; node secp256k1.js; node curves.js; node ecdh.js; node hash-to-curve.js; node modular.js; node bls.js; node ristretto255.js; node decaf448.js","bench:install":"cd benchmark; npm install; npm install .. --install-links","build":"tsc && tsc -p tsconfig.cjs.json","build:release":"npx jsbt esbuild test/build","build:clean":"rm {.,esm,abstract,esm/abstract}/*.{js,d.ts,d.ts.map,js.map} 2> /dev/null","lint":"prettier --check 'src/**/*.{js,ts}' 'test/*.js'","format":"prettier --write 'src/**/*.{js,ts}' 'test/*.js'","test":"node test/index.js","test:bun":"bun test/index.js","test:deno":"deno --allow-env --allow-read test/index.js","test:coverage":"npm install --no-save c8@10.1.2 && npx c8 npm test"},"author":{"name":"Paul Miller","url":"https://paulmillr.com"},"homepage":"https://paulmillr.com/noble/","repository":{"type":"git","url":"git+https://github.com/paulmillr/noble-curves.git"},"license":"MIT","dependencies":{"@noble/hashes":"1.7.1"},"devDependencies":{"@paulmillr/jsbt":"0.3.1","fast-check":"3.0.0","micro-bmark":"0.4.0","micro-should":"0.5.1","prettier":"3.3.2","typescript":"5.5.2"},"sideEffects":false,"main":"index.js","exports":{".":{"import":"./esm/index.js","require":"./index.js"},"./abstract/bls":{"import":"./esm/abstract/bls.js","require":"./abstract/bls.js"},"./abstract/curve":{"import":"./esm/abstract/curve.js","require":"./abstract/curve.js"},"./abstract/edwards":{"import":"./esm/abstract/edwards.js","require":"./abstract/edwards.js"},"./abstract/hash-to-curve":{"import":"./esm/abstract/hash-to-curve.js","require":"./abstract/hash-to-curve.js"},"./abstract/modular":{"import":"./esm/abstract/modular.js","require":"./abstract/modular.js"},"./abstract/montgomery":{"import":"./esm/abstract/montgomery.js","require":"./abstract/montgomery.js"},"./abstract/poseidon":{"import":"./esm/abstract/poseidon.js","require":"./abstract/poseidon.js"},"./abstract/tower":{"import":"./esm/abstract/tower.js","require":"./abstract/tower.js"},"./abstract/utils":{"import":"./esm/abstract/utils.js","require":"./abstract/utils.js"},"./abstract/weierstrass":{"import":"./esm/abstract/weierstrass.js","require":"./abstract/weierstrass.js"},"./_shortw_utils":{"import":"./esm/_shortw_utils.js","require":"./_shortw_utils.js"},"./bls12-381":{"import":"./esm/bls12-381.js","require":"./bls12-381.js"},"./bn254":{"import":"./esm/bn254.js","require":"./bn254.js"},"./ed25519":{"import":"./esm/ed25519.js","require":"./ed25519.js"},"./ed448":{"import":"./esm/ed448.js","require":"./ed448.js"},"./index":{"import":"./esm/index.js","require":"./index.js"},"./jubjub":{"import":"./esm/jubjub.js","require":"./jubjub.js"},"./p256":{"import":"./esm/p256.js","require":"./p256.js"},"./p384":{"import":"./esm/p384.js","require":"./p384.js"},"./p521":{"import":"./esm/p521.js","require":"./p521.js"},"./pasta":{"import":"./esm/pasta.js","require":"./pasta.js"},"./secp256k1":{"import":"./esm/secp256k1.js","require":"./secp256k1.js"}},"engines":{"node":"^14.21.3 || >=16"},"keywords":["elliptic","curve","cryptography","secp256k1","ed25519","p256","p384","p521","secp256r1","ed448","x25519","ed25519","bls12-381","bn254","alt_bn128","bls","noble","ecc","ecdsa","eddsa","weierstrass","montgomery","edwards","schnorr"],"funding":"https://paulmillr.com/funding/","_id":"@noble/curves@1.8.1","gitHead":"57a240423aae515e32b86efe638d1baf6f898748","types":"./index.d.ts","bugs":{"url":"https://github.com/paulmillr/noble-curves/issues"},"_nodeVersion":"22.13.0","_npmVersion":"10.9.2","dist":{"integrity":"sha512-warwspo+UYUPep0Q+vtdVB4Ugn8GGQj8iyB3gnRWsztmUHTI3S1nhdiWNsPUGL0vud7JlRRk1XEu7Lq1KGTnMQ==","shasum":"19bc3970e205c99e4bdb1c64a4785706bce497ff","tarball":"http://registry-npm.ywwl.com/@noble/curves/download/@noble/curves-1.8.1.tgz","fileCount":203,"unpackedSize":1643752,"attestations":{"url":"https://registry.npmjs.org/-/npm/v1/attestations/@noble%2fcurves@1.8.1","provenance":{"predicateType":"https://slsa.dev/provenance/v1"}},"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQCzkFkQm6o9K2jgWin26FcxeznV0XixvepXleDJ4x3E+gIgNnUOjcx08IJPwCQLQ+Zi7eMQkCt9z65SxxPIddjf634="}],"size":296077,"noattachment":false,"key":"/@noble/curves/-/@noble/curves-1.8.1.tgz"},"_npmUser":{"name":"paulmillr","email":"paul@paulmillr.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/curves_1.8.1_1737191826586_0.13206872775224854"},"_hasShrinkwrap":false,"readme":"# noble-curves\n\nAudited & minimal JS implementation of elliptic curve cryptography.\n\n- 🔒 [**Audited**](#security) by independent security firms\n- 🔻 Tree-shakeable: unused code is excluded from your builds\n- 🏎 Fast: hand-optimized for caveats of JS engines\n- 🔍 Reliable: cross-library / wycheproof tests and fuzzing ensure correctness\n- ➰ Short Weierstrass, Edwards, Montgomery curves\n- ✍️ ECDSA, EdDSA, Schnorr, BLS, ECDH, hashing to curves, Poseidon ZK-friendly hash\n- 🔖 SUF-CMA, SBS (non-repudiation), ZIP215 (consensus friendliness) features for ed25519 & ed448\n- 🪶 93KB for everything with hashes, 26KB (11KB gzipped) for single-curve build\n\nCurves have 4KB sister projects\n[secp256k1](https://github.com/paulmillr/noble-secp256k1) & [ed25519](https://github.com/paulmillr/noble-ed25519).\nThey have smaller attack surface, but less features.\n\nTake a glance at [GitHub Discussions](https://github.com/paulmillr/noble-curves/discussions) for questions and support.\n\n### This library belongs to _noble_ cryptography\n\n> **noble cryptography** — high-security, easily auditable set of contained cryptographic libraries and tools.\n\n- Zero or minimal dependencies\n- Highly readable TypeScript / JS code\n- PGP-signed releases and transparent NPM builds\n- All libraries:\n  [ciphers](https://github.com/paulmillr/noble-ciphers),\n  [curves](https://github.com/paulmillr/noble-curves),\n  [hashes](https://github.com/paulmillr/noble-hashes),\n  [post-quantum](https://github.com/paulmillr/noble-post-quantum),\n  4kb [secp256k1](https://github.com/paulmillr/noble-secp256k1) /\n  [ed25519](https://github.com/paulmillr/noble-ed25519)\n- [Check out homepage](https://paulmillr.com/noble/)\n  for reading resources, documentation and apps built with noble\n\n## Usage\n\n> `npm install @noble/curves`\n\n> `deno add jsr:@noble/curves`\n\n> `deno doc jsr:@noble/curves`  # command-line documentation\n\nWe support all major platforms and runtimes.\nFor React Native, you may need a [polyfill for getRandomValues](https://github.com/LinusU/react-native-get-random-values).\nA standalone file [noble-curves.js](https://github.com/paulmillr/noble-curves/releases) is also available.\n\n```js\n// import * from '@noble/curves'; // Error: use sub-imports, to ensure small app size\nimport { secp256k1 } from '@noble/curves/secp256k1'; // ESM and Common.js\n// import { secp256k1 } from 'npm:@noble/curves@1.6.0/secp256k1'; // Deno\n```\n\n- [Implementations](#implementations)\n  - [ECDSA signatures over secp256k1 and others](#ecdsa-signatures-over-secp256k1-and-others)\n  - [ECDSA public key recovery & extra entropy](#ecdsa-public-key-recovery--extra-entropy)\n  - [ECDH: Elliptic Curve Diffie-Hellman](#ecdh-elliptic-curve-diffie-hellman)\n  - [Schnorr signatures over secp256k1, BIP340](#schnorr-signatures-over-secp256k1-bip340)\n  - [ed25519, X25519, ristretto255](#ed25519-x25519-ristretto255)\n  - [ed448, X448, decaf448](#ed448-x448-decaf448)\n  - [bls12-381](#bls12-381)\n  - [bn254 aka alt_bn128](#bn254-aka-alt_bn128)\n  - [Multi-scalar-multiplication](#multi-scalar-multiplication)\n  - [Accessing a curve's variables](#accessing-a-curves-variables)\n  - [All available imports](#all-available-imports)\n- [Abstract API](#abstract-api)\n  - [weierstrass: Short Weierstrass curve](#weierstrass-short-weierstrass-curve)\n  - [edwards: Twisted Edwards curve](#edwards-twisted-edwards-curve)\n  - [montgomery: Montgomery curve](#montgomery-montgomery-curve)\n  - [bls: Barreto-Lynn-Scott curves](#bls-barreto-lynn-scott-curves)\n  - [hash-to-curve: Hashing strings to curve points](#hash-to-curve-hashing-strings-to-curve-points)\n  - [poseidon: Poseidon hash](#poseidon-poseidon-hash)\n  - [modular: Modular arithmetics utilities](#modular-modular-arithmetics-utilities)\n    - [Creating private keys from hashes](#creating-private-keys-from-hashes)\n  - [utils: Useful utilities](#utils-useful-utilities)\n- [Security](#security)\n- [Speed](#speed)\n- [Upgrading](#upgrading)\n- [Contributing & testing](#contributing--testing)\n- [License](#license)\n\n### Implementations\n\nImplementations use [noble-hashes](https://github.com/paulmillr/noble-hashes).\nIf you want to use a different hashing library, [abstract API](#abstract-api) doesn't depend on them.\n\n#### ECDSA signatures over secp256k1 and others\n\n```ts\nimport { secp256k1 } from '@noble/curves/secp256k1';\n// import { p256 } from '@noble/curves/p256'; // or p384 / p521\n\nconst priv = secp256k1.utils.randomPrivateKey();\nconst pub = secp256k1.getPublicKey(priv);\nconst msg = new Uint8Array(32).fill(1); // message hash (not message) in ecdsa\nconst sig = secp256k1.sign(msg, priv); // `{prehash: true}` option is available\nconst isValid = secp256k1.verify(sig, msg, pub) === true;\n\n// hex strings are also supported besides Uint8Array-s:\nconst privHex = '46c930bc7bb4db7f55da20798697421b98c4175a52c630294d75a84b9c126236';\nconst pub2 = secp256k1.getPublicKey(privHex);\n```\n\nThe same code would work for NIST P256 (secp256r1), P384 (secp384r1) & P521 (secp521r1).\n\n#### ECDSA public key recovery & extra entropy\n\n```ts\n// let sig = secp256k1.Signature.fromCompact(sigHex); // or .fromDER(sigDERHex)\n// sig = sig.addRecoveryBit(bit); // bit is not serialized into compact / der format\nsig.recoverPublicKey(msg).toRawBytes(); // === pub; // public key recovery\n\n// extraEntropy https://moderncrypto.org/mail-archive/curves/2017/000925.html\nconst sigImprovedSecurity = secp256k1.sign(msg, priv, { extraEntropy: true });\n```\n\n#### ECDH: Elliptic Curve Diffie-Hellman\n\n```ts\n// 1. The output includes parity byte. Strip it using shared.slice(1)\n// 2. The output is not hashed. More secure way is sha256(shared) or hkdf(shared)\nconst someonesPub = secp256k1.getPublicKey(secp256k1.utils.randomPrivateKey());\nconst shared = secp256k1.getSharedSecret(priv, someonesPub);\n```\n\n#### Schnorr signatures over secp256k1 (BIP340)\n\n```ts\nimport { schnorr } from '@noble/curves/secp256k1';\nconst priv = schnorr.utils.randomPrivateKey();\nconst pub = schnorr.getPublicKey(priv);\nconst msg = new TextEncoder().encode('hello');\nconst sig = schnorr.sign(msg, priv);\nconst isValid = schnorr.verify(sig, msg, pub);\n```\n\n#### ed25519, X25519, ristretto255\n\n```ts\nimport { ed25519 } from '@noble/curves/ed25519';\nconst priv = ed25519.utils.randomPrivateKey();\nconst pub = ed25519.getPublicKey(priv);\nconst msg = new TextEncoder().encode('hello');\nconst sig = ed25519.sign(msg, priv);\ned25519.verify(sig, msg, pub); // Default mode: follows ZIP215\ned25519.verify(sig, msg, pub, { zip215: false }); // RFC8032 / FIPS 186-5\n```\n\nDefault `verify` behavior follows [ZIP215](https://zips.z.cash/zip-0215) and\n[can be used in consensus-critical applications](https://hdevalence.ca/blog/2020-10-04-its-25519am).\nIt has SUF-CMA (strong unforgeability under chosen message attacks).\n`zip215: false` option switches verification criteria to strict\n[RFC8032](https://www.rfc-editor.org/rfc/rfc8032) / [FIPS 186-5](https://csrc.nist.gov/publications/detail/fips/186/5/final)\nand additionally provides [non-repudiation with SBS](#edwards-twisted-edwards-curve).\n\nX25519 follows [RFC7748](https://www.rfc-editor.org/rfc/rfc7748).\n\n```ts\n// Variants from RFC8032: with context, prehashed\nimport { ed25519ctx, ed25519ph } from '@noble/curves/ed25519';\n\n// ECDH using curve25519 aka x25519\nimport { x25519 } from '@noble/curves/ed25519';\nconst priv = 'a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4';\nconst pub = 'e6db6867583030db3594c1a424b15f7c726624ec26b3353b10a903a6d0ab1c4c';\nx25519.getSharedSecret(priv, pub) === x25519.scalarMult(priv, pub); // aliases\nx25519.getPublicKey(priv) === x25519.scalarMultBase(priv);\nx25519.getPublicKey(x25519.utils.randomPrivateKey());\n\n// ed25519 => x25519 conversion\nimport { edwardsToMontgomeryPub, edwardsToMontgomeryPriv } from '@noble/curves/ed25519';\nedwardsToMontgomeryPub(ed25519.getPublicKey(ed25519.utils.randomPrivateKey()));\nedwardsToMontgomeryPriv(ed25519.utils.randomPrivateKey());\n```\n\nristretto255 follows [irtf draft](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448).\n\n```ts\n// hash-to-curve, ristretto255\nimport { utf8ToBytes } from '@noble/hashes/utils';\nimport { sha512 } from '@noble/hashes/sha512';\nimport {\n  hashToCurve,\n  encodeToCurve,\n  RistrettoPoint,\n  hashToRistretto255,\n} from '@noble/curves/ed25519';\n\nconst msg = utf8ToBytes('Ristretto is traditionally a short shot of espresso coffee');\nhashToCurve(msg);\n\nconst rp = RistrettoPoint.fromHex(\n  '6a493210f7499cd17fecb510ae0cea23a110e8d5b901f8acadd3095c73a3b919'\n);\nRistrettoPoint.BASE.multiply(2n).add(rp).subtract(RistrettoPoint.BASE).toRawBytes();\nRistrettoPoint.ZERO.equals(dp) === false;\n// pre-hashed hash-to-curve\nRistrettoPoint.hashToCurve(sha512(msg));\n// full hash-to-curve including domain separation tag\nhashToRistretto255(msg, { DST: 'ristretto255_XMD:SHA-512_R255MAP_RO_' });\n```\n\n#### ed448, X448, decaf448\n\n```ts\nimport { ed448 } from '@noble/curves/ed448';\nconst priv = ed448.utils.randomPrivateKey();\nconst pub = ed448.getPublicKey(priv);\nconst msg = new TextEncoder().encode('whatsup');\nconst sig = ed448.sign(msg, priv);\ned448.verify(sig, msg, pub);\n\n// Variants from RFC8032: prehashed\nimport { ed448ph } from '@noble/curves/ed448';\n```\n\nECDH using Curve448 aka X448, follows [RFC7748](https://www.rfc-editor.org/rfc/rfc7748).\n\n```ts\nimport { x448 } from '@noble/curves/ed448';\nx448.getSharedSecret(priv, pub) === x448.scalarMult(priv, pub); // aliases\nx448.getPublicKey(priv) === x448.scalarMultBase(priv);\n\n// ed448 => x448 conversion\nimport { edwardsToMontgomeryPub } from '@noble/curves/ed448';\nedwardsToMontgomeryPub(ed448.getPublicKey(ed448.utils.randomPrivateKey()));\n```\n\ndecaf448 follows [irtf draft](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448).\n\n```ts\nimport { utf8ToBytes } from '@noble/hashes/utils';\nimport { shake256 } from '@noble/hashes/sha3';\nimport { hashToCurve, encodeToCurve, DecafPoint, hashToDecaf448 } from '@noble/curves/ed448';\n\nconst msg = utf8ToBytes('Ristretto is traditionally a short shot of espresso coffee');\nhashToCurve(msg);\n\nconst dp = DecafPoint.fromHex(\n  'c898eb4f87f97c564c6fd61fc7e49689314a1f818ec85eeb3bd5514ac816d38778f69ef347a89fca817e66defdedce178c7cc709b2116e75'\n);\nDecafPoint.BASE.multiply(2n).add(dp).subtract(DecafPoint.BASE).toRawBytes();\nDecafPoint.ZERO.equals(dp) === false;\n// pre-hashed hash-to-curve\nDecafPoint.hashToCurve(shake256(msg, { dkLen: 112 }));\n// full hash-to-curve including domain separation tag\nhashToDecaf448(msg, { DST: 'decaf448_XOF:SHAKE256_D448MAP_RO_' });\n```\n\nSame RFC7748 / RFC8032 / IRTF draft are followed.\n\n#### bls12-381\n\n```ts\nimport { bls12_381 as bls } from '@noble/curves/bls12-381';\n\n// G1 keys, G2 signatures\nconst privateKey = '67d53f170b908cabb9eb326c3c337762d59289a8fec79f7bc9254b584b73265c';\nconst message = '64726e3da8';\nconst publicKey = bls.getPublicKey(privateKey);\nconst signature = bls.sign(message, privateKey);\nconst isValid = bls.verify(signature, message, publicKey);\nconsole.log({ publicKey, signature, isValid });\n\n// G2 keys, G1 signatures\n// getPublicKeyForShortSignatures(privateKey)\n// signShortSignature(message, privateKey)\n// verifyShortSignature(signature, message, publicKey)\n// aggregateShortSignatures(signatures)\n\n// Custom DST\nconst htfEthereum = { DST: 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_POP_' };\nconst signatureEth = bls.sign(message, privateKey, htfEthereum);\nconst isValidEth = bls.verify(signature, message, publicKey, htfEthereum);\n\n// Aggregation\nconst aggregatedKey = bls.aggregatePublicKeys([bls.utils.randomPrivateKey(), bls.utils.randomPrivateKey()])\n// const aggregatedSig = bls.aggregateSignatures(sigs)\n\n// Pairings, with and without final exponentiation\n// bls.pairing(PointG1, PointG2);\n// bls.pairing(PointG1, PointG2, false);\n// bls.fields.Fp12.finalExponentiate(bls.fields.Fp12.mul(PointG1, PointG2));\n\n// Others\n// bls.G1.ProjectivePoint.BASE, bls.G2.ProjectivePoint.BASE;\n// bls.fields.Fp, bls.fields.Fp2, bls.fields.Fp12, bls.fields.Fr;\n```\n\nSee [abstract/bls](#bls-barreto-lynn-scott-curves).\nFor example usage, check out [the implementation of BLS EVM precompiles](https://github.com/ethereumjs/ethereumjs-monorepo/blob/361f4edbc239e795a411ac2da7e5567298b9e7e5/packages/evm/src/precompiles/bls12_381/noble.ts).\n\n#### bn254 aka alt_bn128\n\n```ts\nimport { bn254 } from '@noble/curves/bn254';\n\nconsole.log(\n  bn254.G1,\n  bn254.G2,\n  bn254.pairing\n)\n```\n\nThe API mirrors [BLS](#bls12-381). The curve was previously called alt_bn128.\nThe implementation is compatible with [EIP-196](https://eips.ethereum.org/EIPS/eip-196) and\n[EIP-197](https://eips.ethereum.org/EIPS/eip-197).\n\nKeep in mind that we don't implement Point methods toHex / toRawBytes. It's because\ndifferent implementations of bn254 do it differently - there is no standard. Points of divergence:\n\n- Endianness: LE vs BE (byte-swapped)\n- Flags as first hex bits (similar to BLS) vs no-flags\n- Imaginary part last in G2 vs first (c0, c1 vs c1, c0)\n\nFor example usage, check out [the implementation of bn254 EVM precompiles](https://github.com/paulmillr/noble-curves/blob/3ed792f8ad9932765b84d1064afea8663a255457/test/bn254.test.js#L697).\n\n#### Multi-scalar-multiplication\n\n```ts\nimport { secp256k1 } from '@noble/curves/secp256k1';\nconst p = secp256k1.ProjectivePoint;\nconst points = [p.BASE, p.BASE.multiply(2n), p.BASE.multiply(4n), p.BASE.multiply(8n)];\np.msm(points, [3n, 5n, 7n, 11n]).equals(p.BASE.multiply(129n)); // 129*G\n```\n\nPippenger algorithm is used underneath.\nMulti-scalar-multiplication (MSM) is basically `(Pa + Qb + Rc + ...)`.\nIt's 10-30x faster vs naive addition for large amount of points.\n\n#### Accessing a curve's variables\n\n```ts\nimport { secp256k1 } from '@noble/curves/secp256k1';\n// Every curve has `CURVE` object that contains its parameters, field, and others\nconsole.log(secp256k1.CURVE.p); // field modulus\nconsole.log(secp256k1.CURVE.n); // curve order\nconsole.log(secp256k1.CURVE.a, secp256k1.CURVE.b); // equation params\nconsole.log(secp256k1.CURVE.Gx, secp256k1.CURVE.Gy); // base point coordinates\n```\n\n\n#### All available imports\n\n```typescript\nimport { secp256k1, schnorr } from '@noble/curves/secp256k1';\nimport { ed25519, ed25519ph, ed25519ctx, x25519, RistrettoPoint } from '@noble/curves/ed25519';\nimport { ed448, ed448ph, ed448ctx, x448 } from '@noble/curves/ed448';\nimport { p256 } from '@noble/curves/p256';\nimport { p384 } from '@noble/curves/p384';\nimport { p521 } from '@noble/curves/p521';\nimport { pallas, vesta } from '@noble/curves/pasta';\nimport { bls12_381 } from '@noble/curves/bls12-381';\nimport { bn254 } from '@noble/curves/bn254'; // also known as alt_bn128\nimport { jubjub } from '@noble/curves/jubjub';\nimport { bytesToHex, hexToBytes, concatBytes, utf8ToBytes } from '@noble/curves/abstract/utils';\n```\n\n## Abstract API\n\nAbstract API allows to define custom curves. All arithmetics is done with JS\nbigints over finite fields, which is defined from `modular` sub-module. For\nscalar multiplication, we use\n[precomputed tables with w-ary non-adjacent form (wNAF)](https://paulmillr.com/posts/noble-secp256k1-fast-ecc/).\nPrecomputes are enabled for weierstrass and edwards BASE points of a curve. You\ncould precompute any other point (e.g. for ECDH) using `utils.precompute()`\nmethod: check out examples.\n\n### weierstrass: Short Weierstrass curve\n\n```ts\nimport { weierstrass } from '@noble/curves/abstract/weierstrass';\nimport { Field } from '@noble/curves/abstract/modular'; // finite field for mod arithmetics\nimport { sha256 } from '@noble/hashes/sha256'; // 3rd-party sha256() of type utils.CHash\nimport { hmac } from '@noble/hashes/hmac'; // 3rd-party hmac() that will accept sha256()\nimport { concatBytes, randomBytes } from '@noble/hashes/utils'; // 3rd-party utilities\n\nconst hmacSha256 = (key: Uint8Array, ...msgs: Uint8Array[]) => hmac(sha256, key, concatBytes(...msgs));\n\n// secq256k1: cycle of secp256k1 with Fp/N flipped.\n// https://personaelabs.org/posts/spartan-ecdsa\n// https://zcash.github.io/halo2/background/curves.html#cycles-of-curves\nconst secq256k1 = weierstrass({\n  // Curve equation params a, b\n  a: 0n,\n  b: 7n,\n  // Field over which we'll do calculations\n  Fp: Field(2n ** 256n - 432420386565659656852420866394968145599n),\n  // Curve order, total count of valid points in the field.\n  n: 2n ** 256n - 2n ** 32n - 2n ** 9n - 2n ** 8n - 2n ** 7n - 2n ** 6n - 2n ** 4n - 1n,\n  // Base point (x, y) aka generator point\n  Gx: 55066263022277343669578718895168534326250603453777594175500187360389116729240n,\n  Gy: 32670510020758816978083085130507043184471273380659243275938904335757337482424n,\n\n  hash: sha256,\n  hmac: hmacSha256,\n  randomBytes,\n});\n\n// NIST secp192r1 aka p192 https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/secg/secp192r1\nconst secp192r1 = weierstrass({\n  a: BigInt('0xfffffffffffffffffffffffffffffffefffffffffffffffc'),\n  b: BigInt('0x64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1'),\n  Fp: Field(BigInt('0xfffffffffffffffffffffffffffffffeffffffffffffffff')),\n  n: BigInt('0xffffffffffffffffffffffff99def836146bc9b1b4d22831'),\n  Gx: BigInt('0x188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012'),\n  Gy: BigInt('0x07192b95ffc8da78631011ed6b24cdd573f977a11e794811'),\n  h: BigInt(1),\n  hash: sha256,\n  hmac: hmacSha256,\n  randomBytes,\n});\n\n\n// Replace weierstrass() with weierstrassPoints() if you don't need ECDSA, hash, hmac, randomBytes\n```\n\nShort Weierstrass curve's formula is `y² = x³ + ax + b`. `weierstrass`\nexpects arguments `a`, `b`, field `Fp`, curve order `n`, cofactor `h`\nand coordinates `Gx`, `Gy` of generator point.\n\n**`k` generation** is done deterministically, following\n[RFC6979](https://www.rfc-editor.org/rfc/rfc6979). It is suggested to use `extraEntropy`\noption, which incorporates randomness into signatures to increase their security.\n\nFor k generation, specifying `hmac` & `hash` is required,\nwhich in our implementations is done by noble-hashes. If\nyou're using different hashing library, make sure to wrap it in the following interface:\n\n```ts\ntype CHash = {\n  (message: Uint8Array): Uint8Array;\n  blockLen: number;\n  outputLen: number;\n  create(): any;\n};\n\n// example\nfunction sha256(message: Uint8Array) {\n  return _internal_lowlvl(message);\n}\nsha256.outputLen = 32; // 32 bytes of output for sha2-256\n```\n\n**Message hash** is expected instead of message itself:\n\n- `sign(msgHash, privKey)` is default behavior, assuming you pre-hash msg with sha2, or other hash\n- `sign(msg, privKey, {prehash: true})` option can be used if you want to pass the message itself\n\n**Weierstrass points:**\n\n1. Exported as `ProjectivePoint`\n2. Represented in projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z)\n3. Use complete exception-free formulas for addition and doubling\n4. Can be decoded/encoded from/to Uint8Array / hex strings using\n   `ProjectivePoint.fromHex` and `ProjectivePoint#toRawBytes()`\n5. Have `assertValidity()` which checks for being on-curve\n6. Have `toAffine()` and `x` / `y` getters which convert to 2d xy affine coordinates\n\n```ts\n// `weierstrassPoints()` returns `CURVE` and `ProjectivePoint`\n// `weierstrass()` returns `CurveFn`\ntype SignOpts = { lowS?: boolean; prehash?: boolean; extraEntropy: boolean | Uint8Array };\ntype CurveFn = {\n  CURVE: ReturnType<typeof validateOpts>;\n  getPublicKey: (privateKey: PrivKey, isCompressed?: boolean) => Uint8Array;\n  getSharedSecret: (privateA: PrivKey, publicB: Hex, isCompressed?: boolean) => Uint8Array;\n  sign: (msgHash: Hex, privKey: PrivKey, opts?: SignOpts) => SignatureType;\n  verify: (\n    signature: Hex | SignatureType,\n    msgHash: Hex,\n    publicKey: Hex,\n    opts?: { lowS?: boolean; prehash?: boolean; format?: 'compact' | 'der' }\n  ) => boolean;\n  ProjectivePoint: ProjectivePointConstructor;\n  Signature: SignatureConstructor;\n  utils: {\n    normPrivateKeyToScalar: (key: PrivKey) => bigint;\n    isValidPrivateKey(key: PrivKey): boolean;\n    randomPrivateKey: () => Uint8Array;\n    precompute: (windowSize?: number, point?: ProjPointType<bigint>) => ProjPointType<bigint>;\n  };\n};\n\n// T is usually bigint, but can be something else like complex numbers in BLS curves\ninterface ProjPointType<T> extends Group<ProjPointType<T>> {\n  readonly px: T;\n  readonly py: T;\n  readonly pz: T;\n  get x(): bigint;\n  get y(): bigint;\n  multiply(scalar: bigint): ProjPointType<T>;\n  multiplyUnsafe(scalar: bigint): ProjPointType<T>;\n  multiplyAndAddUnsafe(Q: ProjPointType<T>, a: bigint, b: bigint): ProjPointType<T> | undefined;\n  toAffine(iz?: T): AffinePoint<T>;\n  isTorsionFree(): boolean;\n  clearCofactor(): ProjPointType<T>;\n  assertValidity(): void;\n  hasEvenY(): boolean;\n  toRawBytes(isCompressed?: boolean): Uint8Array;\n  toHex(isCompressed?: boolean): string;\n}\n// Static methods for 3d XYZ points\ninterface ProjConstructor<T> extends GroupConstructor<ProjPointType<T>> {\n  new (x: T, y: T, z: T): ProjPointType<T>;\n  fromAffine(p: AffinePoint<T>): ProjPointType<T>;\n  fromHex(hex: Hex): ProjPointType<T>;\n  fromPrivateKey(privateKey: PrivKey): ProjPointType<T>;\n  msm(points: ProjPointType[], scalars: bigint[]): ProjPointType<T>;\n}\n```\n\n**ECDSA signatures** are represented by `Signature` instances and can be\ndescribed by the interface:\n\n```ts\ninterface SignatureType {\n  readonly r: bigint;\n  readonly s: bigint;\n  readonly recovery?: number;\n  assertValidity(): void;\n  addRecoveryBit(recovery: number): SignatureType;\n  hasHighS(): boolean;\n  normalizeS(): SignatureType;\n  recoverPublicKey(msgHash: Hex): ProjPointType<bigint>;\n  toCompactRawBytes(): Uint8Array;\n  toCompactHex(): string;\n  // DER-encoded\n  toDERRawBytes(): Uint8Array;\n  toDERHex(): string;\n}\ntype SignatureConstructor = {\n  new (r: bigint, s: bigint): SignatureType;\n  fromCompact(hex: Hex): SignatureType;\n  fromDER(hex: Hex): SignatureType;\n};\n```\n\nMore examples:\n\n```typescript\n// All curves expose same generic interface.\nconst priv = secq256k1.utils.randomPrivateKey();\nsecq256k1.getPublicKey(priv); // Convert private key to public.\nconst sig = secq256k1.sign(msg, priv); // Sign msg with private key.\nconst sig2 = secq256k1.sign(msg, priv, { prehash: true }); // hash(msg)\nsecq256k1.verify(sig, msg, priv); // Verify if sig is correct.\n\n// Default behavior is \"try DER, then try compact if fails\". Can be explicit:\nsecq256k1.verify(sig.toCompactHex(), msg, priv, { format: 'compact' });\n\nconst Point = secq256k1.ProjectivePoint;\nconst point = Point.BASE; // Elliptic curve Point class and BASE point static var.\npoint.add(point).equals(point.double()); // add(), equals(), double() methods\npoint.subtract(point).equals(Point.ZERO); // subtract() method, ZERO static var\npoint.negate(); // Flips point over x/y coordinate.\npoint.multiply(31415n); // Multiplication of Point by scalar.\n\npoint.assertValidity(); // Checks for being on-curve\npoint.toAffine(); // Converts to 2d affine xy coordinates\n\nsecq256k1.CURVE.n;\nsecq256k1.CURVE.p;\nsecq256k1.CURVE.Fp.mod();\nsecq256k1.CURVE.hash();\n\n// precomputes\nconst fast = secq256k1.utils.precompute(8, Point.fromHex(someonesPubKey));\nfast.multiply(privKey); // much faster ECDH now\n```\n\n### edwards: Twisted Edwards curve\n\n```ts\nimport { twistedEdwards } from '@noble/curves/abstract/edwards';\nimport { Field } from '@noble/curves/abstract/modular';\nimport { sha512 } from '@noble/hashes/sha512';\nimport { randomBytes } from '@noble/hashes/utils';\n\nconst Fp = Field(2n ** 255n - 19n);\nconst ed25519 = twistedEdwards({\n  a: Fp.create(-1n),\n  d: Fp.div(-121665n, 121666n), // -121665n/121666n mod p\n  Fp: Fp,\n  n: 2n ** 252n + 27742317777372353535851937790883648493n,\n  h: 8n,\n  Gx: 15112221349535400772501151409588531511454012693041857206046113283949847762202n,\n  Gy: 46316835694926478169428394003475163141307993866256225615783033603165251855960n,\n  hash: sha512,\n  randomBytes,\n  adjustScalarBytes(bytes) {\n    // optional; but mandatory in ed25519\n    bytes[0] &= 248;\n    bytes[31] &= 127;\n    bytes[31] |= 64;\n    return bytes;\n  },\n} as const);\n```\n\nTwisted Edwards curve's formula is `ax² + y² = 1 + dx²y²`. You must specify `a`, `d`, field `Fp`, order `n`, cofactor `h`\nand coordinates `Gx`, `Gy` of generator point.\n\nFor EdDSA signatures, `hash` param required. `adjustScalarBytes` which instructs how to change private scalars could be specified.\n\nWe support [non-repudiation](https://eprint.iacr.org/2020/1244), which help in following scenarios:\n\n- Contract Signing: if A signed an agreement with B using key that allows repudiation, it can later claim that it signed a different contract\n- E-voting: malicious voters may pick keys that allow repudiation in order to deny results\n- Blockchains: transaction of amount X might also be valid for a different amount Y\n\n**Edwards points:**\n\n1. Exported as `ExtendedPoint`\n2. Represented in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z)\n3. Use complete exception-free formulas for addition and doubling\n4. Can be decoded/encoded from/to Uint8Array / hex strings using `ExtendedPoint.fromHex` and `ExtendedPoint#toRawBytes()`\n5. Have `assertValidity()` which checks for being on-curve\n6. Have `toAffine()` and `x` / `y` getters which convert to 2d xy affine coordinates\n7. Have `isTorsionFree()`, `clearCofactor()` and `isSmallOrder()` utilities to handle torsions\n\n```ts\n// `twistedEdwards()` returns `CurveFn` of following type:\ntype CurveFn = {\n  CURVE: ReturnType<typeof validateOpts>;\n  getPublicKey: (privateKey: Hex) => Uint8Array;\n  sign: (message: Hex, privateKey: Hex, context?: Hex) => Uint8Array;\n  verify: (sig: SigType, message: Hex, publicKey: Hex, context?: Hex) => boolean;\n  ExtendedPoint: ExtPointConstructor;\n  utils: {\n    randomPrivateKey: () => Uint8Array;\n    getExtendedPublicKey: (key: PrivKey) => {\n      head: Uint8Array;\n      prefix: Uint8Array;\n      scalar: bigint;\n      point: PointType;\n      pointBytes: Uint8Array;\n    };\n  };\n};\n\ninterface ExtPointType extends Group<ExtPointType> {\n  readonly ex: bigint;\n  readonly ey: bigint;\n  readonly ez: bigint;\n  readonly et: bigint;\n  get x(): bigint;\n  get y(): bigint;\n  assertValidity(): void;\n  multiply(scalar: bigint): ExtPointType;\n  multiplyUnsafe(scalar: bigint): ExtPointType;\n  isSmallOrder(): boolean;\n  isTorsionFree(): boolean;\n  clearCofactor(): ExtPointType;\n  toAffine(iz?: bigint): AffinePoint<bigint>;\n  toRawBytes(isCompressed?: boolean): Uint8Array;\n  toHex(isCompressed?: boolean): string;\n}\n// Static methods of Extended Point with coordinates in X, Y, Z, T\ninterface ExtPointConstructor extends GroupConstructor<ExtPointType> {\n  new (x: bigint, y: bigint, z: bigint, t: bigint): ExtPointType;\n  fromAffine(p: AffinePoint<bigint>): ExtPointType;\n  fromHex(hex: Hex): ExtPointType;\n  fromPrivateKey(privateKey: Hex): ExtPointType;\n  msm(points: ExtPointType[], scalars: bigint[]): ExtPointType;\n}\n```\n\n### montgomery: Montgomery curve\n\n```typescript\nimport { montgomery } from '@noble/curves/abstract/montgomery';\nimport { Field } from '@noble/curves/abstract/modular';\n\nconst x25519 = montgomery({\n  a: 486662n,\n  Gu: 9n,\n  P: 2n ** 255n - 19n,\n  montgomeryBits: 255,\n  nByteLength: 32,\n  // Optional param\n  adjustScalarBytes(bytes) {\n    bytes[0] &= 248;\n    bytes[31] &= 127;\n    bytes[31] |= 64;\n    return bytes;\n  },\n});\n```\n\nThe module contains methods for x-only ECDH on Curve25519 / Curve448 from RFC7748.\nProper Elliptic Curve Points are not implemented yet.\n\nYou must specify curve params `Fp`, `a`, `Gu` coordinate of u, `montgomeryBits` and `nByteLength`.\n\n### bls: Barreto-Lynn-Scott curves\n\nThe module abstracts BLS (Barreto-Lynn-Scott) pairing-friendly elliptic curve construction.\nThey allow to construct [zk-SNARKs](https://z.cash/technology/zksnarks/) and\nuse aggregated, batch-verifiable\n[threshold signatures](https://medium.com/snigirev.stepan/bls-signatures-better-than-schnorr-5a7fe30ea716),\nusing Boneh-Lynn-Shacham signature scheme.\n\nThe module doesn't expose `CURVE` property: use `G1.CURVE`, `G2.CURVE` instead.\nOnly BLS12-381 is currently implemented.\nDefining BLS12-377 and BLS24 should be straightforward.\n\nThe default BLS uses short public keys (with public keys in G1 and signatures in G2).\nShort signatures (public keys in G2 and signatures in G1) are also supported.\n\n### hash-to-curve: Hashing strings to curve points\n\nThe module allows to hash arbitrary strings to elliptic curve points. Implements [RFC 9380](https://www.rfc-editor.org/rfc/rfc9380).\n\nEvery curve has exported `hashToCurve` and `encodeToCurve` methods. You should always prefer `hashToCurve` for security:\n\n```ts\nimport { hashToCurve, encodeToCurve } from '@noble/curves/secp256k1';\nimport { randomBytes } from '@noble/hashes/utils';\nhashToCurve('0102abcd');\nconsole.log(hashToCurve(randomBytes()));\nconsole.log(encodeToCurve(randomBytes()));\n\nimport { bls12_381 } from '@noble/curves/bls12-381';\nbls12_381.G1.hashToCurve(randomBytes(), { DST: 'another' });\nbls12_381.G2.hashToCurve(randomBytes(), { DST: 'custom' });\n```\n\nLow-level methods from the spec:\n\n```ts\n// produces a uniformly random byte string using a cryptographic hash function H that outputs b bits.\nfunction expand_message_xmd(\n  msg: Uint8Array,\n  DST: Uint8Array,\n  lenInBytes: number,\n  H: CHash // For CHash see abstract/weierstrass docs section\n): Uint8Array;\n// produces a uniformly random byte string using an extendable-output function (XOF) H.\nfunction expand_message_xof(\n  msg: Uint8Array,\n  DST: Uint8Array,\n  lenInBytes: number,\n  k: number,\n  H: CHash\n): Uint8Array;\n// Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F\nfunction hash_to_field(msg: Uint8Array, count: number, options: Opts): bigint[][];\n\n/**\n * * `DST` is a domain separation tag, defined in section 2.2.5\n * * `p` characteristic of F, where F is a finite field of characteristic p and order q = p^m\n * * `m` is extension degree (1 for prime fields)\n * * `k` is the target security target in bits (e.g. 128), from section 5.1\n * * `expand` is `xmd` (SHA2, SHA3, BLAKE) or `xof` (SHAKE, BLAKE-XOF)\n * * `hash` conforming to `utils.CHash` interface, with `outputLen` / `blockLen` props\n */\ntype UnicodeOrBytes = string | Uint8Array;\ntype Opts = {\n  DST: UnicodeOrBytes;\n  p: bigint;\n  m: number;\n  k: number;\n  expand?: 'xmd' | 'xof';\n  hash: CHash;\n};\n```\n\n### poseidon: Poseidon hash\n\nImplements [Poseidon](https://www.poseidon-hash.info) ZK-friendly hash.\n\nThere are many poseidon variants with different constants.\nWe don't provide them: you should construct them manually.\nCheck out [micro-starknet](https://github.com/paulmillr/micro-starknet) package for a proper example.\n\n```ts\nimport { poseidon } from '@noble/curves/abstract/poseidon';\n\ntype PoseidonOpts = {\n  Fp: Field<bigint>;\n  t: number;\n  roundsFull: number;\n  roundsPartial: number;\n  sboxPower?: number;\n  reversePartialPowIdx?: boolean;\n  mds: bigint[][];\n  roundConstants: bigint[][];\n};\nconst instance = poseidon(opts: PoseidonOpts);\n```\n\n### modular: Modular arithmetics utilities\n\n```ts\nimport * as mod from '@noble/curves/abstract/modular';\n\n// Finite Field utils\nconst fp = mod.Field(2n ** 255n - 19n); // Finite field over 2^255-19\nfp.mul(591n, 932n); // multiplication\nfp.pow(481n, 11024858120n); // exponentiation\nfp.div(5n, 17n); // division: 5/17 mod 2^255-19 == 5 * invert(17)\nfp.inv(5n); // modular inverse\nfp.sqrt(21n); // square root\n\n// Non-Field generic utils are also available\nmod.mod(21n, 10n); // 21 mod 10 == 1n; fixed version of 21 % 10\nmod.invert(17n, 10n); // invert(17) mod 10; modular multiplicative inverse\nmod.invertBatch([1n, 2n, 4n], 21n); // => [1n, 11n, 16n] in one inversion\n```\n\nField operations are not constant-time: they are using JS bigints, see [security](#security).\nThe fact is mostly irrelevant, but the important method to keep in mind is `pow`,\nwhich may leak exponent bits, when used naïvely.\n\n`mod.Field` is always **field over prime number**. Non-prime fields aren't supported for now.\nWe don't test for prime-ness for speed and because algorithms are probabilistic anyway.\nInitializing a non-prime field could make your app suspectible to\nDoS (infilite loop) on Tonelli-Shanks square root calculation.\n\nUnlike `mod.inv`, `mod.invertBatch` won't throw on `0`: make sure to throw an error yourself.\n\n#### Creating private keys from hashes\n\nYou can't simply make a 32-byte private key from a 32-byte hash.\nDoing so will make the key [biased](https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/).\n\nTo make the bias negligible, we follow [FIPS 186-5 A.2](https://csrc.nist.gov/publications/detail/fips/186/5/final)\nand [RFC 9380](https://www.rfc-editor.org/rfc/rfc9380#section-5.2).\nThis means, for 32-byte key, we would need 48-byte hash to get 2^-128 bias, which matches curve security level.\n\n`hashToPrivateScalar()` that hashes to **private key** was created for this purpose.\nUse [abstract/hash-to-curve](#hash-to-curve-hashing-strings-to-curve-points)\nif you need to hash to **public key**.\n\n```ts\nimport { p256 } from '@noble/curves/p256';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { hkdf } from '@noble/hashes/hkdf';\nimport * as mod from '@noble/curves/abstract/modular';\nconst someKey = new Uint8Array(32).fill(2); // Needs to actually be random, not .fill(2)\nconst derived = hkdf(sha256, someKey, undefined, 'application', 48); // 48 bytes for 32-byte priv\nconst validPrivateKey = mod.hashToPrivateScalar(derived, p256.CURVE.n);\n```\n\n### utils: Useful utilities\n\n```ts\nimport * as utils from '@noble/curves/abstract/utils';\n\nutils.bytesToHex(Uint8Array.from([0xde, 0xad, 0xbe, 0xef]));\nutils.hexToBytes('deadbeef');\nutils.numberToHexUnpadded(123n);\nutils.hexToNumber();\n\nutils.bytesToNumberBE(Uint8Array.from([0xde, 0xad, 0xbe, 0xef]));\nutils.bytesToNumberLE(Uint8Array.from([0xde, 0xad, 0xbe, 0xef]));\nutils.numberToBytesBE(123n, 32);\nutils.numberToBytesLE(123n, 64);\n\nutils.concatBytes(Uint8Array.from([0xde, 0xad]), Uint8Array.from([0xbe, 0xef]));\nutils.nLength(255n);\nutils.equalBytes(Uint8Array.from([0xde]), Uint8Array.from([0xde]));\n```\n\n## Security\n\nThe library has been independently audited:\n\n- at version 1.6.0, in Sep 2024, by [Cure53](https://cure53.de)\n  - PDFs: [website](https://cure53.de/audit-report_noble-crypto-libs.pdf), [in-repo](./audit/2024-09-cure53-audit-nbl4.pdf)\n  - [Changes since audit](https://github.com/paulmillr/noble-curves/compare/1.6.0..main)\n  - Scope: ed25519, ed448, their add-ons, bls12-381, bn254,\n    hash-to-curve, low-level primitives bls, tower, edwards, montgomery.\n  - The audit has been funded by [OpenSats](https://opensats.org)\n- at version 1.2.0, in Sep 2023, by [Kudelski Security](https://kudelskisecurity.com)\n  - PDFs: [in-repo](./audit/2023-09-kudelski-audit-starknet.pdf)\n  - [Changes since audit](https://github.com/paulmillr/noble-curves/compare/1.2.0..main)\n  - Scope: [scure-starknet](https://github.com/paulmillr/scure-starknet) and its related\n    abstract modules of noble-curves: `curve`, `modular`, `poseidon`, `weierstrass`\n  - The audit has been funded by [Starkware](https://starkware.co)\n- at version 0.7.3, in Feb 2023, by [Trail of Bits](https://www.trailofbits.com)\n  - PDFs: [website](https://github.com/trailofbits/publications/blob/master/reviews/2023-01-ryanshea-noblecurveslibrary-securityreview.pdf),\n    [in-repo](./audit/2023-01-trailofbits-audit-curves.pdf)\n  - [Changes since audit](https://github.com/paulmillr/noble-curves/compare/0.7.3..main)\n  - Scope: abstract modules `curve`, `hash-to-curve`, `modular`, `poseidon`, `utils`, `weierstrass` and\n    top-level modules `_shortw_utils` and `secp256k1`\n  - The audit has been funded by [Ryan Shea](https://www.shea.io)\n\nIt is tested against property-based, cross-library and Wycheproof vectors,\nand has fuzzing by [Guido Vranken's cryptofuzz](https://github.com/guidovranken/cryptofuzz).\n\nIf you see anything unusual: investigate and report.\n\n### Constant-timeness\n\n_JIT-compiler_ and _Garbage Collector_ make \"constant time\" extremely hard to\nachieve [timing attack](https://en.wikipedia.org/wiki/Timing_attack) resistance\nin a scripting language. Which means _any other JS library can't have\nconstant-timeness_. Even statically typed Rust, a language without GC,\n[makes it harder to achieve constant-time](https://www.chosenplaintext.ca/open-source/rust-timing-shield/security)\nfor some cases. If your goal is absolute security, don't use any JS lib — including bindings to native ones.\nUse low-level libraries & languages. Nonetheless we're targetting algorithmic constant time.\n\n### Supply chain security\n\n- **Commits** are signed with PGP keys, to prevent forgery. Make sure to verify commit signatures.\n- **Releases** are transparent and built on GitHub CI. Make sure to verify [provenance](https://docs.npmjs.com/generating-provenance-statements) logs\n- **Rare releasing** is followed to ensure less re-audit need for end-users\n- **Dependencies** are minimized and locked-down:\n  - If your app has 500 dependencies, any dep could get hacked and you'll be downloading\n    malware with every install. We make sure to use as few dependencies as possible\n  - We prevent automatic dependency updates by locking-down version ranges. Every update is checked with `npm-diff`\n  - One dependency [noble-hashes](https://github.com/paulmillr/noble-hashes) is used, by the same author, to provide hashing functionality\n- **Dev Dependencies** are only used if you want to contribute to the repo. They are disabled for end-users:\n  - scure-base, scure-bip32, scure-bip39, micro-bmark and micro-should are developed by the same author and follow identical security practices\n  - prettier (linter), fast-check (property-based testing) and typescript are used for code quality, vector generation and ts compilation. The packages are big, which makes it hard to audit their source code thoroughly and fully\n\n### Randomness\n\nWe're deferring to built-in\n[crypto.getRandomValues](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues)\nwhich is considered cryptographically secure (CSPRNG).\n\nIn the past, browsers had bugs that made it weak: it may happen again.\nImplementing a userspace CSPRNG to get resilient to the weakness\nis even worse: there is no reliable userspace source of quality entropy.\n\n### Quantum computers\n\nCryptographically relevant quantum computer, if built, will allow to\nbreak elliptic curve cryptography (both ECDSA / EdDSA & ECDH) using Shor's algorithm.\n\nConsider switching to newer / hybrid algorithms, such as SPHINCS+. They are available in\n[noble-post-quantum](https://github.com/paulmillr/noble-post-quantum).\n\nNIST prohibits classical cryptography (RSA, DSA, ECDSA, ECDH) [after 2035](https://nvlpubs.nist.gov/nistpubs/ir/2024/NIST.IR.8547.ipd.pdf). Australian ASD prohibits it [after 2030](https://www.cyber.gov.au/resources-business-and-government/essential-cyber-security/ism/cyber-security-guidelines/guidelines-cryptography).\n\n## Speed\n\nBenchmark results on Apple M2 with node v22:\n\n```\nsecp256k1\ninit x 68 ops/sec @ 14ms/op\ngetPublicKey x 6,839 ops/sec @ 146μs/op\nsign x 5,226 ops/sec @ 191μs/op\nverify x 893 ops/sec @ 1ms/op\ngetSharedSecret x 538 ops/sec @ 1ms/op\nrecoverPublicKey x 923 ops/sec @ 1ms/op\nschnorr.sign x 700 ops/sec @ 1ms/op\nschnorr.verify x 919 ops/sec @ 1ms/op\n\ned25519\ninit x 51 ops/sec @ 19ms/op\ngetPublicKey x 9,809 ops/sec @ 101μs/op\nsign x 4,976 ops/sec @ 200μs/op\nverify x 1,018 ops/sec @ 981μs/op\n\ned448\ninit x 19 ops/sec @ 50ms/op\ngetPublicKey x 3,723 ops/sec @ 268μs/op\nsign x 1,759 ops/sec @ 568μs/op\nverify x 344 ops/sec @ 2ms/op\n\np256\ninit x 39 ops/sec @ 25ms/op\ngetPublicKey x 6,518 ops/sec @ 153μs/op\nsign x 5,148 ops/sec @ 194μs/op\nverify x 609 ops/sec @ 1ms/op\n\np384\ninit x 17 ops/sec @ 57ms/op\ngetPublicKey x 2,933 ops/sec @ 340μs/op\nsign x 2,327 ops/sec @ 429μs/op\nverify x 244 ops/sec @ 4ms/op\n\np521\ninit x 8 ops/sec @ 112ms/op\ngetPublicKey x 1,484 ops/sec @ 673μs/op\nsign x 1,264 ops/sec @ 790μs/op\nverify x 124 ops/sec @ 8ms/op\n\nristretto255\nadd x 680,735 ops/sec @ 1μs/op\nmultiply x 10,766 ops/sec @ 92μs/op\nencode x 15,835 ops/sec @ 63μs/op\ndecode x 15,972 ops/sec @ 62μs/op\n\ndecaf448\nadd x 345,303 ops/sec @ 2μs/op\nmultiply x 300 ops/sec @ 3ms/op\nencode x 5,987 ops/sec @ 167μs/op\ndecode x 5,892 ops/sec @ 169μs/op\n\necdh\n├─x25519 x 1,477 ops/sec @ 676μs/op\n├─secp256k1 x 537 ops/sec @ 1ms/op\n├─p256 x 512 ops/sec @ 1ms/op\n├─p384 x 198 ops/sec @ 5ms/op\n├─p521 x 99 ops/sec @ 10ms/op\n└─x448 x 504 ops/sec @ 1ms/op\n\nbls12-381\ninit x 36 ops/sec @ 27ms/op\ngetPublicKey x 960 ops/sec @ 1ms/op\nsign x 60 ops/sec @ 16ms/op\nverify x 47 ops/sec @ 21ms/op\npairing x 125 ops/sec @ 7ms/op\npairing10 x 40 ops/sec @ 24ms/op ± 23.27% (min: 21ms, max: 48ms)\nMSM 4096 scalars x points x 0 ops/sec @ 4655ms/op\naggregatePublicKeys/8 x 129 ops/sec @ 7ms/op\naggregatePublicKeys/32 x 34 ops/sec @ 28ms/op\naggregatePublicKeys/128 x 8 ops/sec @ 113ms/op\naggregatePublicKeys/512 x 2 ops/sec @ 449ms/op\naggregatePublicKeys/2048 x 0 ops/sec @ 1792ms/op\naggregateSignatures/8 x 62 ops/sec @ 15ms/op\naggregateSignatures/32 x 16 ops/sec @ 60ms/op\naggregateSignatures/128 x 4 ops/sec @ 238ms/op\naggregateSignatures/512 x 1 ops/sec @ 946ms/op\naggregateSignatures/2048 x 0 ops/sec @ 3774ms/op\n\nhash-to-curve\nhash_to_field x 91,600 ops/sec @ 10μs/op\nsecp256k1 x 2,373 ops/sec @ 421μs/op\np256 x 4,310 ops/sec @ 231μs/op\np384 x 1,664 ops/sec @ 600μs/op\np521 x 807 ops/sec @ 1ms/op\ned25519 x 3,088 ops/sec @ 323μs/op\ned448 x 1,247 ops/sec @ 801μs/op\n```\n\n## Upgrading\n\nPreviously, the library was split into single-feature packages\n[noble-secp256k1](https://github.com/paulmillr/noble-secp256k1),\n[noble-ed25519](https://github.com/paulmillr/noble-ed25519) and\n[noble-bls12-381](https://github.com/paulmillr/noble-bls12-381).\n\nCurves continue their original work. The single-feature packages changed their\ndirection towards providing minimal 4kb implementations of cryptography,\nwhich means they have less features.\n\nUpgrading from noble-secp256k1 2.0 or noble-ed25519 2.0: no changes, libraries are compatible.\n\nUpgrading from noble-secp256k1 1.7:\n\n- `getPublicKey`\n  - now produce 33-byte compressed signatures by default\n  - to use old behavior, which produced 65-byte uncompressed keys, set\n    argument `isCompressed` to `false`: `getPublicKey(priv, false)`\n- `sign`\n  - is now sync\n  - now returns `Signature` instance with `{ r, s, recovery }` properties\n  - `canonical` option was renamed to `lowS`\n  - `recovered` option has been removed because recovery bit is always returned now\n  - `der` option has been removed. There are 2 options:\n    1. Use compact encoding: `fromCompact`, `toCompactRawBytes`, `toCompactHex`.\n       Compact encoding is simply a concatenation of 32-byte r and 32-byte s.\n    2. If you must use DER encoding, switch to noble-curves (see above).\n- `verify`\n  - is now sync\n  - `strict` option was renamed to `lowS`\n- `getSharedSecret`\n  - now produce 33-byte compressed signatures by default\n  - to use old behavior, which produced 65-byte uncompressed keys, set\n    argument `isCompressed` to `false`: `getSharedSecret(a, b, false)`\n- `recoverPublicKey(msg, sig, rec)` was changed to `sig.recoverPublicKey(msg)`\n- `number` type for private keys have been removed: use `bigint` instead\n- `Point` (2d xy) has been changed to `ProjectivePoint` (3d xyz)\n- `utils` were split into `utils` (same api as in noble-curves) and\n  `etc` (`hmacSha256Sync` and others)\n\nUpgrading from [@noble/ed25519](https://github.com/paulmillr/noble-ed25519) 1.7:\n\n- Methods are now sync by default\n- `bigint` is no longer allowed in `getPublicKey`, `sign`, `verify`. Reason: ed25519 is LE, can lead to bugs\n- `Point` (2d xy) has been changed to `ExtendedPoint` (xyzt)\n- `Signature` was removed: just use raw bytes or hex now\n- `utils` were split into `utils` (same api as in noble-curves) and\n  `etc` (`sha512Sync` and others)\n- `getSharedSecret` was moved to `x25519` module\n- `toX25519` has been moved to `edwardsToMontgomeryPub` and `edwardsToMontgomeryPriv` methods\n\nUpgrading from [@noble/bls12-381](https://github.com/paulmillr/noble-bls12-381):\n\n- Methods and classes were renamed:\n  - PointG1 -> G1.Point, PointG2 -> G2.Point\n  - PointG2.fromSignature -> Signature.decode, PointG2.toSignature -> Signature.encode\n- Fp2 ORDER was corrected\n\n## Contributing & testing\n\n* `npm install && npm run build && npm test` will build the code and run tests.\n* `npm run lint` / `npm run format` will run linter / fix linter issues.\n* `npm run bench` will run benchmarks, which may need their deps first (`npm run bench:install`)\n* `cd build && npm install && npm run build:release` will build single file\n\nCheck out [github.com/paulmillr/guidelines](https://github.com/paulmillr/guidelines)\nfor general coding practices and rules.\n\nSee [paulmillr.com/noble](https://paulmillr.com/noble/)\nfor useful resources, articles, documentation and demos\nrelated to the library.\n\n## License\n\nThe MIT License (MIT)\n\nCopyright (c) 2022 Paul Miller [(https://paulmillr.com)](https://paulmillr.com)\n\nSee LICENSE file.\n","publish_time":1737191826791,"maintainers":[{"name":"paulmillr","email":"paul@paulmillr.com"}],"_cnpm_publish_time":1737191826791,"dist-tags":{"latest":"2.4.0"}}