• This repository has been archived on 12/Oct/2024
  • Stars
    star
    202
  • Rank 193,691 (Top 4 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 5 years ago
  • Updated about 1 month ago

Reviews

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

Repository Details

DEPRECATED: use noble-curves instead. Fastest JS implementation of BLS12-381.

noble-bls12-381

The repo has been merged into noble-curves. It is now deprecated. Please switch to:

npm install @noble/curves
// Import in js
import { bls12_381 } from '@noble/curves/bls12-381';

Fastest JS implementation of BLS12-381. Auditable, secure, 0-dependency aggregated signatures & pairings.

The pairing-friendly Barreto-Lynn-Scott elliptic curve construction allows to:

  • Construct zk-SNARKs at the 128-bit security
  • Use threshold signatures, which allows a user to sign lots of messages with one signature and verify them swiftly in a batch, using Boneh-Lynn-Shacham signature scheme.

Compatible with Algorand, Chia, Dfinity, Ethereum, FIL, Zcash. Matches specs pairing-curves-10, bls-sigs-04, hash-to-curve-12. To learn more about internals, navigate to utilities section.

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 in all major browsers and stable node.js versions
  • All releases are signed with PGP keys
  • Check out homepage & all libraries: curves (4kb versions secp256k1, ed25519), hashes

Usage

Use NPM in node.js / browser, or include single file from GitHub's releases page:

npm install @noble/bls12-381

const bls = require('@noble/bls12-381');
// If you're using single file, use global variable instead: `window.nobleBls12381`

(async () => {
  // keys, messages & other inputs can be Uint8Arrays or hex strings
  const privateKey = '67d53f170b908cabb9eb326c3c337762d59289a8fec79f7bc9254b584b73265c';
  const message = '64726e3da8';
  const publicKey = bls.getPublicKey(privateKey);
  const signature = await bls.sign(message, privateKey);
  const isValid = await bls.verify(signature, message, publicKey);
  console.log({ publicKey, signature, isValid });

  // Sign 1 msg with 3 keys
  const privateKeys = [
    '18f020b98eb798752a50ed0563b079c125b0db5dd0b1060d1c1b47d4a193e1e4',
    'ed69a8c50cf8c9836be3b67c7eeff416612d45ba39a5c099d48fa668bf558c9c',
    '16ae669f3be7a2121e17d0c68c05a8f3d6bef21ec0f2315f1d7aec12484e4cf5'
  ];
  const messages = ['d2', '0d98', '05caf3'];
  const publicKeys = privateKeys.map(bls.getPublicKey);
  const signatures2 = await Promise.all(privateKeys.map(p => bls.sign(message, p)));
  const aggPubKey2 = bls.aggregatePublicKeys(publicKeys);
  const aggSignature2 = bls.aggregateSignatures(signatures2);
  const isValid2 = await bls.verify(aggSignature2, message, aggPubKey2);
  console.log({ signatures2, aggSignature2, isValid2 });

  // Sign 3 msgs with 3 keys
  const signatures3 = await Promise.all(privateKeys.map((p, i) => bls.sign(messages[i], p)));
  const aggSignature3 = bls.aggregateSignatures(signatures3);
  const isValid3 = await bls.verifyBatch(aggSignature3, messages, publicKeys);
  console.log({ publicKeys, signatures3, aggSignature3, isValid3 });
})();

To use the module with Deno, you will need import map:

  • deno run --import-map=imports.json app.ts
  • app.ts: import * as bls from "https://deno.land/x/bls12_381/mod.ts";
  • imports.json: {"imports": {"crypto": "https://deno.land/[email protected]/node/crypto.ts"}}

API

getPublicKey(privateKey)
function getPublicKey(privateKey: Uint8Array | string | bigint): Uint8Array;
  • privateKey: Uint8Array | string | bigint will be used to generate public key. Public key is generated by executing scalar multiplication of a base Point(x, y) by a fixed integer. The result is another Point(x, y) which we will by default encode to hex Uint8Array.
  • Returns Uint8Array: encoded publicKey for signature verification

Note: if you need EIP2333-compliant KeyGen (eth2/fil), use paulmillr/bls12-381-keygen.

sign(message, privateKey)
function sign(message: Uint8Array | string, privateKey: Uint8Array | string): Promise<Uint8Array>;
function sign(message: PointG2, privateKey: Uint8Array | string | bigint): Promise<PointG2>;
  • message: Uint8Array | string - message which would be hashed & signed
  • privateKey: Uint8Array | string | bigint - private key which will sign the hash
  • Returns Uint8Array | string | PointG2: encoded signature

Check out Utilities section on instructions about domain separation tag (DST).

verify(signature, message, publicKey)
function verify(
  signature: Uint8Array | string | PointG2,
  message: Uint8Array | string | PointG2,
  publicKey: Uint8Array | string | PointG1
): Promise<boolean>
  • signature: Uint8Array | string - object returned by the sign or aggregateSignatures function
  • message: Uint8Array | string - message hash that needs to be verified
  • publicKey: Uint8Array | string - e.g. that was generated from privateKey by getPublicKey
  • Returns Promise<boolean>: true / false whether the signature matches hash
aggregatePublicKeys(publicKeys)
function aggregatePublicKeys(publicKeys: (Uint8Array | string)[]): Uint8Array;
function aggregatePublicKeys(publicKeys: PointG1[]): PointG1;
  • publicKeys: (Uint8Array | string | PointG1)[] - e.g. that have been generated from privateKey by getPublicKey
  • Returns Uint8Array | PointG1: one aggregated public key which calculated from public keys
aggregateSignatures(signatures)
function aggregateSignatures(signatures: (Uint8Array | string)[]): Uint8Array;
function aggregateSignatures(signatures: PointG2[]): PointG2;
  • signatures: (Uint8Array | string | PointG2)[] - e.g. that have been generated by sign
  • Returns Uint8Array | PointG2: one aggregated signature which calculated from signatures
verifyBatch(signature, messages, publicKeys)
function verifyBatch(
  signature: Uint8Array | string | PointG2,
  messages: (Uint8Array | string | PointG2)[],
  publicKeys: (Uint8Array | string | PointG1)[]
): Promise<boolean>
  • signature: Uint8Array | string | PointG2 - object returned by the aggregateSignatures function
  • messages: (Uint8Array | string | PointG2)[] - messages hashes that needs to be verified
  • publicKeys: (Uint8Array | string | PointG1)[] - e.g. that were generated from privateKeys by getPublicKey
  • Returns Promise<boolean>: true / false whether the signature matches hashes
pairing(pointG1, pointG2)
function pairing(
  pointG1: PointG1,
  pointG2: PointG2,
  withFinalExponent: boolean = true
): Fp12
  • pointG1: PointG1 - simple point, x, y are bigints
  • pointG2: PointG2 - point over curve with complex numbers ((x₁, x₂+i), (y₁, y₂+i)) - pairs of bigints
  • withFinalExponent: boolean - should the result be powered by curve order; very slow
  • Returns Fp12: paired point over 12-degree extension field.

Utilities

Resources that help to understand bls12-381:

The library uses G1 for public keys and G2 for signatures. Adding support for G1 signatures is planned.

  • BLS Relies on Bilinear Pairing (expensive)
  • Private Keys: 32 bytes
  • Public Keys: 48 bytes: 381 bit affine x coordinate, encoded into 48 big-endian bytes.
  • Signatures: 96 bytes: two 381 bit integers (affine x coordinate), encoded into two 48 big-endian byte arrays.
    • The signature is a point on the G2 subgroup, which is defined over a finite field with elements twice as big as the G1 curve (G2 is over Fp2 rather than Fp. Fp2 is analogous to the complex numbers).
  • The 12 stands for the Embedding degree.

Formulas:

  • P = pk x G - public keys
  • S = pk x H(m) - signing
  • e(P, H(m)) == e(G, S) - verification using pairings
  • e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si)) - signature aggregation

The BLS parameters for the library are:

  • PK_IN G1
  • HASH_OR_ENCODE true
  • DST BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_ - use bls.utils.getDSTLabel() & bls.utils.setDSTLabel("...") to read/change the Domain Separation Tag label
  • RAND_BITS 64

Filecoin uses little endian byte arrays for private keys - so ensure to reverse byte order if you'll use it with FIL.

// Exports `CURVE`, `utils`, `PointG1`, `PointG2`, `Fp`, `Fp2`, `Fp12` helpers

const utils: {
  hashToField(msg: Uint8Array, count: number, options = {}): Promise<bigint[][]>;
  bytesToHex: (bytes: Uint8Array): string;
  randomBytes: (bytesLength?: number) => Uint8Array;
  randomPrivateKey: () => Uint8Array;
  sha256: (message: Uint8Array) => Promise<Uint8Array>;
  mod: (a: bigint, b = CURVE.P): bigint;
  getDSTLabel(): string;
  setDSTLabel(newLabel: string): void;
};

// characteristic; z + (z⁴ - z² + 1)(z - 1)²/3
CURVE.P // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab
CURVE.r // curve order; z⁴ − z² + 1, 0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001
curve.h // cofactor; (z - 1)²/3, 0x396c8c005555e1568c00aaab0000aaab
CURVE.Gx, CURVE.Gy   // G1 base point coordinates (x, y)
CURVE.G2x, CURVE.G2y // G2 base point coordinates (x₁, x₂+i), (y₁, y₂+i)

// Classes
bls.Fp   // field over Fp
bls.Fp2  // field over Fp₂
bls.Fp12 // finite extension field over irreducible polynominal

// for hashToCurve static method
declare const htfDefaults: {
  DST: string;
  p: bigint;
  m: number;
  k: number;
  expand: boolean;
  hash: Hash;
};

// projective point (xyz) at G1
class PointG1 extends ProjectivePoint<Fp> {
  constructor(x: Fp, y: Fp, z?: Fp);
  static BASE: PointG1;
  static ZERO: PointG1;
  static fromHex(bytes: Bytes): PointG1;
  static fromPrivateKey(privateKey: PrivateKey): PointG1;
  static hashToCurve(msg: Hex, options?: Partial<typeof htfDefaults>): Promise<PointG1>;
  toRawBytes(isCompressed?: boolean): Uint8Array;
  toHex(isCompressed?: boolean): string;
  assertValidity(): this;
  millerLoop(P: PointG2): Fp12;
  clearCofactor(): PointG1;
}
// projective point (xyz) at G2
class PointG2 extends ProjectivePoint<Fp2> {
  constructor(x: Fp2, y: Fp2, z?: Fp2);
  static BASE: PointG2;
  static ZERO: PointG2;
  static hashToCurve(msg: Hex, options?: Partial<typeof htfDefaults>): Promise<PointG2>;
  static fromSignature(hex: Bytes): PointG2;
  static fromHex(bytes: Bytes): PointG2;
  static fromPrivateKey(privateKey: PrivateKey): PointG2;
  toSignature(): Uint8Array;
  toRawBytes(isCompressed?: boolean): Uint8Array;
  toHex(isCompressed?: boolean): string;
  assertValidity(): this;
  clearCofactor(): PointG2;
}

Speed

To achieve the best speed out of all JS / Python implementations, the library employs different optimizations:

  • cyclotomic exponentation
  • endomorphism for clearing cofactor
  • pairing precomputation

Benchmarks measured with Apple M2 on macOS 12.5 with node.js 18.8:

getPublicKey x 818 ops/sec @ 1ms/op
sign x 44 ops/sec @ 22ms/op
verify x 34 ops/sec @ 29ms/op
pairing x 84 ops/sec @ 11ms/op
aggregatePublicKeys/8 x 117 ops/sec @ 8ms/op
aggregateSignatures/8 x 45 ops/sec @ 21ms/op

with compression / decompression disabled:
sign/nc x 60 ops/sec @ 16ms/op
verify/nc x 57 ops/sec @ 17ms/op ± 1.05% (min: 17ms, max: 19ms)
aggregatePublicKeys/32 x 1,163 ops/sec @ 859μs/op
aggregatePublicKeys/128 x 758 ops/sec @ 1ms/op
aggregatePublicKeys/512 x 318 ops/sec @ 3ms/op
aggregatePublicKeys/2048 x 96 ops/sec @ 10ms/op
aggregateSignatures/32 x 516 ops/sec @ 1ms/op
aggregateSignatures/128 x 269 ops/sec @ 3ms/op
aggregateSignatures/512 x 93 ops/sec @ 10ms/op
aggregateSignatures/2048 x 25 ops/sec @ 38ms/op

Security

Noble is production-ready.

  1. No public audits have been done yet. Our goal is to crowdfund the audit.
  2. It was developed in a similar fashion to noble-secp256k1, which was audited by a third-party firm.
  3. It was fuzzed by Guido Vranken's cryptofuzz, no serious issues have been found. You can run the fuzzer by yourself to check it.

We're using built-in JS BigInt, which is potentially vulnerable to timing attacks as per official spec. 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 however 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.

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 jest on test/index.ts

Special thanks to Roman Koblov, who have helped to improve pairing speed.

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

noble-ed25519

Fastest 4KB JS implementation of ed25519 signatures
JavaScript
419
star
11

readdirp

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

top-github-users

GitHub top-1000 generation script
CoffeeScript
259
star
13

ostio

Your open-source talks place.
JavaScript
247
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