• Stars
    star
    419
  • Rank 103,397 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 5 years ago
  • Updated 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Fastest 4KB JS implementation of ed25519 signatures

noble-ed25519

Fastest 4KB JS implementation of ed25519 EDDSA signatures compliant with RFC8032, FIPS 186-5 & ZIP215.

If you're looking for additional features, check out noble-curves: a drop-in replacement with common.js, ristretto255, X25519 / curve25519, ed25519ph and ed25519ctx.

Has SUF-CMA (strong unforgeability under chosen message attacks) and, unlike many other libraries, non-repudiation (SBS / Strongly Binding Signatures aka exclusive ownership). See verify docs for details.

Check out Upgrading section for v1 to v2 transition instructions and the online demo.

This library belongs to noble crypto

noble-crypto — high-security, easily auditable set of contained cryptographic libraries and tools.

  • No dependencies, protection against supply chain attacks
  • Auditable TypeScript / JS code
  • Supported on all major platforms
  • Releases are signed with PGP keys and built transparently with NPM provenance
  • Check out homepage & all libraries: ciphers, curves, hashes, 4kb secp256k1 / ed25519

Usage

npm install @noble/ed25519

We support all major platforms and runtimes. For node.js <= 18 and React Native, additional polyfills are needed: see below.

import * as ed from '@noble/ed25519';
// import * as ed from "https://deno.land/x/ed25519/mod.ts"; // Deno
// import * as ed from "https://unpkg.com/@noble/ed25519"; // Unpkg
(async () => {
  // keys, messages & other inputs can be Uint8Arrays or hex strings
  // Uint8Array.from([0xde, 0xad, 0xbe, 0xef]) === 'deadbeef'
  const privKey = ed.utils.randomPrivateKey(); // Secure random private key
  const message = Uint8Array.from([0xab, 0xbc, 0xcd, 0xde]);
  const pubKey = await ed.getPublicKeyAsync(privKey); // Sync methods below
  const signature = await ed.signAsync(message, privKey);
  const isValid = await ed.verifyAsync(signature, message, pubKey);
})();

Additional polyfills for some environments:

// 1. Enable synchronous methods.
// Only async methods are available by default, to keep the library dependency-free.
import { sha512 } from '@noble/hashes/sha512';
ed.etc.sha512Sync = (...m) => sha512(ed.etc.concatBytes(...m));
// Sync methods can be used now:
// ed.getPublicKey(privKey); ed.sign(msg, privKey); ed.verify(signature, msg, pubKey);

// 2. node.js 18 and earlier, 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 { sha512 } from '@noble/hashes/sha512';
ed.etc.sha512Sync = (...m) => sha512(ed.etc.concatBytes(...m));
ed.etc.sha512Async = (...m) => Promise.resolve(ed.etc.sha512Sync(...m));

API

There are 3 main methods: getPublicKey(privateKey), sign(message, privateKey) and verify(signature, message, publicKey). We accept Hex type everywhere:

type Hex = Uint8Array | string

getPublicKey

function getPublicKey(privateKey: Hex): Uint8Array;
function getPublicKeyAsync(privateKey: Hex): Promise<Uint8Array>;

Generates 32-byte public key from 32-byte private key.

  • Some libraries have 64-byte private keys. Don't worry, those are just priv+pub concatenated. Slice it: priv64b.slice(0, 32)
  • Use Point.fromPrivateKey(privateKey) if you want Point instance instead
  • Use Point.fromHex(publicKey) if you want to convert hex / bytes into Point. It will use decompression algorithm 5.1.3 of RFC 8032.
  • Use utils.getExtendedPublicKey if you need full SHA512 hash of seed

sign

function sign(
  message: Hex, // message which would be signed
  privateKey: Hex // 32-byte private key
): Uint8Array;
function signAsync(message: Hex, privateKey: Hex): Promise<Uint8Array>;

Generates EdDSA signature. Always deterministic.

Assumes unhashed message: it would be hashed by ed25519 internally. For prehashed ed25519ph, switch to noble-curves.

verify

function verify(
  signature: Hex, // returned by the `sign` function
  message: Hex, // message that needs to be verified
  publicKey: Hex // public (not private) key,
  options = { zip215: true } // ZIP215 or RFC8032 verification type
): boolean;
function verifyAsync(signature: Hex, message: Hex, publicKey: Hex): Promise<boolean>;

Verifies EdDSA signature. Has SUF-CMA (strong unforgeability under chosen message attacks). By default, follows ZIP215 1 and can be used in consensus-critical apps 2. zip215: false option switches verification criteria to strict RFC8032 / FIPS 186-5 and provides non-repudiation with SBS (Strongly Binding Signatures) 3.

utils

A bunch of useful utilities are also exposed:

const etc: {
  bytesToHex: (b: Bytes) => string;
  hexToBytes: (hex: string) => Bytes;
  concatBytes: (...arrs: Bytes[]) => Uint8Array;
  mod: (a: bigint, b?: bigint) => bigint;
  invert: (num: bigint, md?: bigint) => bigint;
  randomBytes: (len: number) => Bytes;
  sha512Async: (...messages: Bytes[]) => Promise<Bytes>;
  sha512Sync: Sha512FnSync;
};
const utils: {
  getExtendedPublicKeyAsync: (priv: Hex) => Promise<ExtK>;
  getExtendedPublicKey: (priv: Hex) => ExtK;
  precompute(p: Point, w?: number): Point;
  randomPrivateKey: () => Bytes; // Uses CSPRNG https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues
};

class ExtendedPoint { // Elliptic curve point in Extended (x, y, z, t) coordinates.
  constructor(ex: bigint, ey: bigint, ez: bigint, et: bigint);
  static readonly BASE: Point;
  static readonly ZERO: Point;
  static fromAffine(point: AffinePoint): ExtendedPoint;
  static fromHex(hash: string);
  get x(): bigint;
  get y(): bigint;
  // Note: It does not check whether the `other` point is valid point on curve.
  add(other: ExtendedPoint): ExtendedPoint;
  equals(other: ExtendedPoint): boolean;
  isTorsionFree(): boolean; // Multiplies the point by curve order
  multiply(scalar: bigint): ExtendedPoint;
  subtract(other: ExtendedPoint): ExtendedPoint;
  toAffine(): Point;
  toRawBytes(): Uint8Array;
  toHex(): string; // Compact representation of a Point
}
// Curve params
ed25519.CURVE.p // 2 ** 255 - 19
ed25519.CURVE.n // 2 ** 252 + 27742317777372353535851937790883648493
ed25519.ExtendedPoint.BASE // new ed25519.Point(Gx, Gy) where
// Gx=15112221349535400772501151409588531511454012693041857206046113283949847762202n
// Gy=46316835694926478169428394003475163141307993866256225615783033603165251855960n;

Security

The module is production-ready. It is cross-tested against noble-curves, and has similar security.

  1. The current version is rewrite of v1, which has been audited by cure53: PDF.
  2. 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

Benchmarks done with Apple M2 on macOS 13 with Node.js 20.

getPublicKey(utils.randomPrivateKey()) x 9,173 ops/sec @ 109μs/op
sign x 4,567 ops/sec @ 218μs/op
verify x 994 ops/sec @ 1ms/op
Point.fromHex decompression x 16,164 ops/sec @ 61μs/op

Compare to alternative implementations:

[email protected] getPublicKey x 1,808 ops/sec @ 552μs/op ± 1.64%
[email protected] sign x 651 ops/sec @ 1ms/op
[email protected] getPublicKey x 640 ops/sec @ 1ms/op ± 1.59%
sodium-native#sign x 83,654 ops/sec @ 11μs/op

Contributing

  1. Clone the repository
  2. npm install to install build dependencies like TypeScript
  3. npm run build to compile TypeScript code
  4. npm run test to run tests

Upgrading

noble-ed25519 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 300 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:

  • x25519 / curve25519 / getSharedSecret
  • ristretto255 / RistrettoPoint
  • 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/ed25519 1.7 to 2.0:

  • Methods are now sync by default; use getPublicKeyAsync, signAsync, verifyAsync for async versions
  • bigint is no longer allowed in getPublicKey, sign, verify. Reason: ed25519 is LE, can lead to bugs
  • Point (2d xy) has been changed to ExtendedPoint (xyzt)
  • Signature was removed: just use raw bytes or hex now
  • utils were split into utils (same api as in noble-curves) and etc (sha512Sync and others)

License

MIT (c) 2019 Paul Miller (https://paulmillr.com), see LICENSE file.

More Repositories

1

chokidar

Minimal and efficient cross-platform file watching library
JavaScript
10,957
star
2

encrypted-dns

DNS over HTTPS config profiles for iOS & macOS
3,316
star
3

es6-shim

ECMAScript 6 compatibility shims for legacy JS engines
JavaScript
3,114
star
4

dotfiles

Colourful & robust configuration files and utilities for Mac, Linux & BSD
Shell
1,199
star
5

exoskeleton

Faster and leaner Backbone for your HTML5 apps
JavaScript
880
star
6

noble-secp256k1

Fastest 4KB JS implementation of secp256k1 signatures and ECDH
JavaScript
757
star
7

noble-curves

Audited & minimal JS implementation of elliptic curve cryptography.
JavaScript
675
star
8

noble-hashes

Audited & minimal JS implementation of hash functions, MACs and KDFs.
JavaScript
573
star
9

console-polyfill

Browser console methods polyfill.
JavaScript
436
star
10

readdirp

Recursive version of fs.readdir with streaming api.
JavaScript
382
star
11

top-github-users

GitHub top-1000 generation script
CoffeeScript
259
star
12

ostio

Your open-source talks place.
JavaScript
247
star
13

noble-bls12-381

DEPRECATED: use noble-curves instead. Fastest JS implementation of BLS12-381.
TypeScript
202
star
14

noble-ciphers

Auditable & minimal JS implementation of Salsa20, ChaCha and AES
TypeScript
188
star
15

micro-eth-signer

Minimal library for Ethereum transactions, addresses and smart contracts.
JavaScript
187
star
16

code-style-guides

Idiomatic, widely-used code style guides for various programming languages.
164
star
17

scure-btc-signer

Audited & minimal library for creating, signing & decoding Bitcoin transactions.
JavaScript
151
star
18

qr

Minimal node.js & browser QR Code Pattern reader and generator
JavaScript
137
star
19

scaffolt

Dead-simple JSON-based scaffolder.
JavaScript
125
star
20

scure-bip39

Secure, audited & minimal implementation of BIP39 mnemonic phrases
TypeScript
119
star
21

scure-base

Secure, audited & 0-deps implementation of bech32, base64, base32, base16 & base58
JavaScript
114
star
22

async-each

No-bullshit, ultra-simple, 40-lines-of-code async parallel forEach / map function for JavaScript.
JavaScript
105
star
23

noble-post-quantum

Auditable & minimal JS implementation of public-key post-quantum cryptography
TypeScript
82
star
24

scure-starknet

Audited & minimal JS implementation of Starknet cryptography.
JavaScript
69
star
25

ostio-api

Your open-source talks place. Rails backend.
Ruby
69
star
26

tx-tor-broadcaster

CLI utility that broadcasts BTC, ETH, SOL, ZEC & XMR transactions through TOR using public block explorers
JavaScript
68
star
27

micro-sol-signer

Create, sign & decode Solana transactions with minimum deps
JavaScript
61
star
28

scure-bip32

Secure, audited & minimal implementation of BIP32 hierarchical deterministic (HD) wallets.
TypeScript
61
star
29

micro-web3

Typesafe Web3 with minimum deps: call eth contracts directly from JS. Batteries included
TypeScript
59
star
30

native-notifier

Use native system notifications in node.js without third-party libraries
JavaScript
56
star
31

chieftain

New generation imageboard. Built with Python / Django.
Python
49
star
32

micro-ordinals

Minimal JS library for ordinals and inscriptions on top of scure-btc-signer
JavaScript
43
star
33

micro-key-producer

Produces secure keys and passwords. Supports SSH, PGP, BLS, OTP and many other formats
TypeScript
43
star
34

loggy

Colorful stdstream dead-simple logger for node.js.
JavaScript
42
star
35

micro-ftch

Wrappers for built-in fetch() enabling killswitch, logging, concurrency limit and other features.
JavaScript
40
star
36

Array.prototype.find

Simple ES6 Array.prototype.find polyfill for older environments.
JavaScript
38
star
37

micro-packed

Define complex binary structures using composable primitives
TypeScript
38
star
38

micro-otp

One Time Password generation via RFC 6238
JavaScript
35
star
39

micro-bmark

Benchmark your node.js projects with nanosecond resolution.
JavaScript
34
star
40

pushserve

Dead-simple pushState-enabled command-line http server.
JavaScript
32
star
41

LiveScript.tmbundle

A TextMate, Chocolat and Sublime Text bundle for LiveScript
Python
31
star
42

jage

age-encryption.org tool implementation in JavaScript
TypeScript
29
star
43

read-components

Read bower and component(1) components
JavaScript
28
star
44

Array.prototype.findIndex

Simple ES6 Array.prototype.findIndex polyfill for older environments.
JavaScript
28
star
45

mnp

My new passport
JavaScript
28
star
46

nip44

NIP44 spec and implementations of encrypted messages for nostr
C
26
star
47

github-pull-req-stats

Stats from GitHub repos about accepted / closed pull requests.
JavaScript
25
star
48

micro-aes-gcm

0-dep wrapper around webcrypto AES-GCM. Has optional RFC 8452 SIV implementation.
JavaScript
25
star
49

steg

Simple and secure steganography
TypeScript
23
star
50

micro-password-generator

Utilities for password generation and estimation with support for iOS keychain
TypeScript
18
star
51

tag-shell

Use ES6 template tags for your node.js shell commands.
JavaScript
17
star
52

papers

Papers i've read and / or wanted to save
17
star
53

micro-should

Simplest zero-dependency testing framework, a drop-in replacement for Mocha.
JavaScript
17
star
54

noble-ripemd160

Noble RIPEMD160. High-security, easily auditable, 0-dep, 1-file hash function
TypeScript
17
star
55

bls12-381-keygen

BLS12-381 Key Generation compatible with EIP-2333.
TypeScript
16
star
56

micro-promisify

Convert callback-based JS function into promise. Simple, 10LOC, no deps.
JavaScript
16
star
57

micro-base58

Fast and beautiful base58 encoder without dependencies.
TypeScript
15
star
58

micro-rsa-dsa-dh

Minimal JS implementation of older cryptography algorithms: RSA, DSA, DH.
TypeScript
15
star
59

lastfm-tools

Last.FM data reclaimer (backuper, helper and analyzer).
Ruby
14
star
60

fetch-streaming

Simple XMLHTTPRequest-based `fetch` implementation for streaming content.
JavaScript
14
star
61

micro-ed25519-hdkey

Minimal implementation of SLIP-0010 hierarchical deterministic (HD) wallets
JavaScript
14
star
62

unicode-categories

ECMAscript unicode categories. Useful for lexing.
12
star
63

noble.py

Noble cryptographic libraries in Python. High-security, easily auditable, 0-dep pubkey, scalarmult & EDDSA.
Python
11
star
64

argumentum

No-bullshit option parser for node.js.
JavaScript
8
star
65

trusted-setups

Easily access trusted setups in JS. Includes KZG / ETH
JavaScript
7
star
66

micro-es7-shim

No-bullshit super-simple es7 collections shim for Array#includes, Object.values, Object.entries
JavaScript
7
star
67

jsbt

Build tools for js projects. Includes tsconfigs, templates and CI workflows
JavaScript
7
star
68

eth-vectors

Comprehensive official vectors for ETH
JavaScript
7
star
69

micro-ff1

Format-preserving encryption algorithm (FPE-FF1) specified in NIST Special Publication 800-38G.
TypeScript
6
star
70

backup

Backup of all my projects in a single signed file
JavaScript
6
star
71

quickly-copy-file

Quickly copy file from one path to another. No bullshit, ultra-simple, async and just one dep.
JavaScript
6
star
72

microtemplates

John Resig's micro-templates aka underscore templates. No-bullshit and small
JavaScript
6
star
73

popular-user-agents

Regularly updated list of popular user agents aka browser versions
JavaScript
6
star
74

paulmillr.github.io

JavaScript
5
star
75

roy.tmbundle

Roy TextMate, Chocolat & Sublime Text 2 bundle
5
star
76

qr-code-vectors

QR Code test vectors
Python
4
star
77

paulmillr

4
star
78

aesscr

Use AES-256-GCM + Scrypt to encrypt files.
JavaScript
3
star
79

universal-path

Cross-platform universal node.js `path` module replacement that works better with Windows
JavaScript
2
star
80

fcache

fs.readFile cache for node.js build systems & watchers
JavaScript
2
star
81

rn-bigint

Java
1
star
82

packed

https://github.com/paulmillr/micro-packed
1
star
83

unused-test-repo

JavaScript
1
star