Compare commits
60 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6cf3255d56 | ||
|
|
57863fddcd | ||
|
|
7d500495a7 | ||
|
|
7da3b7047c | ||
|
|
360a4d83db | ||
|
|
9400508f3e | ||
|
|
7edee38ea1 | ||
|
|
1a17bef1ac | ||
|
|
04405da933 | ||
|
|
ee0077063d | ||
|
|
b09bf0d839 | ||
|
|
d04844cce8 | ||
|
|
b03b848909 | ||
|
|
9b746838c3 | ||
|
|
978e5029f3 | ||
|
|
011e4c303c | ||
|
|
fa019fe9a1 | ||
|
|
0f31e1c301 | ||
|
|
c9a20e63b5 | ||
|
|
79e38b8f79 | ||
|
|
7cfd43b91b | ||
|
|
777ab312a5 | ||
|
|
2763dd9d6a | ||
|
|
a20b28cd21 | ||
|
|
456f0e1f2e | ||
|
|
4abb4bf33c | ||
|
|
7dcfc7c3e3 | ||
|
|
07f5f39f35 | ||
|
|
10ddda633c | ||
|
|
c55a5ebfd8 | ||
|
|
b6e945f8de | ||
|
|
3ec585273f | ||
|
|
0e8229e13e | ||
|
|
230bd70e07 | ||
|
|
c36cb4a0fe | ||
|
|
d6b167a50b | ||
|
|
27f4cd6857 | ||
|
|
28c8109f8a | ||
|
|
00e93b2b2f | ||
|
|
2334f742cf | ||
|
|
8c456ec522 | ||
|
|
e734f33542 | ||
|
|
6ad2d37a23 | ||
|
|
28ce7bce1b | ||
|
|
894a163111 | ||
|
|
efe9d977cd | ||
|
|
bff0bca411 | ||
|
|
fee3ffc764 | ||
|
|
d49a3e800f | ||
|
|
9d9d0f88f5 | ||
|
|
b11161862a | ||
|
|
fe35b2dfa1 | ||
|
|
ae67e65969 | ||
|
|
19344942b0 | ||
|
|
c758333269 | ||
|
|
3ed0c35611 | ||
|
|
d9503c1532 | ||
|
|
fa0859dcdd | ||
|
|
0c340316ae | ||
|
|
313a55992f |
3
.gitignore
vendored
3
.gitignore
vendored
@@ -1,3 +1,6 @@
|
||||
# GPT-2 model files (271MB, too large for git — uploaded directly to server)
|
||||
www/models/
|
||||
|
||||
hamburger_morphing/
|
||||
client/
|
||||
ndk/
|
||||
|
||||
36
build-pq-bundle.js
Normal file
36
build-pq-bundle.js
Normal file
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* Build script for the post-quantum crypto bundle.
|
||||
* Bundles pq-crypto.mjs and all its dependencies into a single
|
||||
* ESM file that can be loaded directly in the browser.
|
||||
*
|
||||
* Usage: node build-pq-bundle.js
|
||||
*/
|
||||
|
||||
const esbuild = require('esbuild');
|
||||
const path = require('path');
|
||||
|
||||
async function build() {
|
||||
console.log('🔧 Building PQ crypto bundle...');
|
||||
|
||||
await esbuild.build({
|
||||
entryPoints: ['www/js/pq-crypto.mjs'],
|
||||
bundle: true,
|
||||
format: 'esm',
|
||||
target: ['es2020'],
|
||||
outfile: 'www/pq-crypto.bundle.js',
|
||||
sourcemap: true,
|
||||
minify: false, // keep readable for demo
|
||||
logLevel: 'info',
|
||||
// Pure JS — no WASM files to handle
|
||||
define: {
|
||||
'process.env.NODE_ENV': '"production"'
|
||||
}
|
||||
});
|
||||
|
||||
console.log('✅ PQ crypto bundle built: www/pq-crypto.bundle.js');
|
||||
}
|
||||
|
||||
build().catch(err => {
|
||||
console.error('❌ Build failed:', err);
|
||||
process.exit(1);
|
||||
});
|
||||
494
node_modules/.package-lock.json
generated
vendored
494
node_modules/.package-lock.json
generated
vendored
@@ -1,296 +1,8 @@
|
||||
{
|
||||
"name": "client-ndk",
|
||||
"name": "client",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"node_modules/@esbuild/aix-ppc64": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.2.tgz",
|
||||
"integrity": "sha512-GZMB+a0mOMZs4MpDbj8RJp4cw+w1WV5NYD6xzgvzUJ5Ek2jerwfO2eADyI6ExDSUED+1X8aMbegahsJi+8mgpw==",
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
],
|
||||
"dev": true,
|
||||
"ideallyInert": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"aix"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/android-arm": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.2.tgz",
|
||||
"integrity": "sha512-DVNI8jlPa7Ujbr1yjU2PfUSRtAUZPG9I1RwW4F4xFB1Imiu2on0ADiI/c3td+KmDtVKNbi+nffGDQMfcIMkwIA==",
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"ideallyInert": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"android"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/android-arm64": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.2.tgz",
|
||||
"integrity": "sha512-pvz8ZZ7ot/RBphf8fv60ljmaoydPU12VuXHImtAs0XhLLw+EXBi2BLe3OYSBslR4rryHvweW5gmkKFwTiFy6KA==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"ideallyInert": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"android"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/android-x64": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.2.tgz",
|
||||
"integrity": "sha512-z8Ank4Byh4TJJOh4wpz8g2vDy75zFL0TlZlkUkEwYXuPSgX8yzep596n6mT7905kA9uHZsf/o2OJZubl2l3M7A==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"ideallyInert": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"android"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/darwin-arm64": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.2.tgz",
|
||||
"integrity": "sha512-davCD2Zc80nzDVRwXTcQP/28fiJbcOwvdolL0sOiOsbwBa72kegmVU0Wrh1MYrbuCL98Omp5dVhQFWRKR2ZAlg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"ideallyInert": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/darwin-x64": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.2.tgz",
|
||||
"integrity": "sha512-ZxtijOmlQCBWGwbVmwOF/UCzuGIbUkqB1faQRf5akQmxRJ1ujusWsb3CVfk/9iZKr2L5SMU5wPBi1UWbvL+VQA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"ideallyInert": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/freebsd-arm64": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.2.tgz",
|
||||
"integrity": "sha512-lS/9CN+rgqQ9czogxlMcBMGd+l8Q3Nj1MFQwBZJyoEKI50XGxwuzznYdwcav6lpOGv5BqaZXqvBSiB/kJ5op+g==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"ideallyInert": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"freebsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/freebsd-x64": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.2.tgz",
|
||||
"integrity": "sha512-tAfqtNYb4YgPnJlEFu4c212HYjQWSO/w/h/lQaBK7RbwGIkBOuNKQI9tqWzx7Wtp7bTPaGC6MJvWI608P3wXYA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"ideallyInert": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"freebsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-arm": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.2.tgz",
|
||||
"integrity": "sha512-vWfq4GaIMP9AIe4yj1ZUW18RDhx6EPQKjwe7n8BbIecFtCQG4CfHGaHuh7fdfq+y3LIA2vGS/o9ZBGVxIDi9hw==",
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"ideallyInert": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-arm64": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.2.tgz",
|
||||
"integrity": "sha512-hYxN8pr66NsCCiRFkHUAsxylNOcAQaxSSkHMMjcpx0si13t1LHFphxJZUiGwojB1a/Hd5OiPIqDdXONia6bhTw==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"ideallyInert": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-ia32": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.2.tgz",
|
||||
"integrity": "sha512-MJt5BRRSScPDwG2hLelYhAAKh9imjHK5+NE/tvnRLbIqUWa+0E9N4WNMjmp/kXXPHZGqPLxggwVhz7QP8CTR8w==",
|
||||
"cpu": [
|
||||
"ia32"
|
||||
],
|
||||
"dev": true,
|
||||
"ideallyInert": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-loong64": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.2.tgz",
|
||||
"integrity": "sha512-lugyF1atnAT463aO6KPshVCJK5NgRnU4yb3FUumyVz+cGvZbontBgzeGFO1nF+dPueHD367a2ZXe1NtUkAjOtg==",
|
||||
"cpu": [
|
||||
"loong64"
|
||||
],
|
||||
"dev": true,
|
||||
"ideallyInert": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-mips64el": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.2.tgz",
|
||||
"integrity": "sha512-nlP2I6ArEBewvJ2gjrrkESEZkB5mIoaTswuqNFRv/WYd+ATtUpe9Y09RnJvgvdag7he0OWgEZWhviS1OTOKixw==",
|
||||
"cpu": [
|
||||
"mips64el"
|
||||
],
|
||||
"dev": true,
|
||||
"ideallyInert": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-ppc64": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.2.tgz",
|
||||
"integrity": "sha512-C92gnpey7tUQONqg1n6dKVbx3vphKtTHJaNG2Ok9lGwbZil6DrfyecMsp9CrmXGQJmZ7iiVXvvZH6Ml5hL6XdQ==",
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
],
|
||||
"dev": true,
|
||||
"ideallyInert": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-riscv64": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.2.tgz",
|
||||
"integrity": "sha512-B5BOmojNtUyN8AXlK0QJyvjEZkWwy/FKvakkTDCziX95AowLZKR6aCDhG7LeF7uMCXEJqwa8Bejz5LTPYm8AvA==",
|
||||
"cpu": [
|
||||
"riscv64"
|
||||
],
|
||||
"dev": true,
|
||||
"ideallyInert": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-s390x": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.2.tgz",
|
||||
"integrity": "sha512-p4bm9+wsPwup5Z8f4EpfN63qNagQ47Ua2znaqGH6bqLlmJ4bx97Y9JdqxgGZ6Y8xVTixUnEkoKSHcpRlDnNr5w==",
|
||||
"cpu": [
|
||||
"s390x"
|
||||
],
|
||||
"dev": true,
|
||||
"ideallyInert": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-x64": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.2.tgz",
|
||||
@@ -308,166 +20,96 @@
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/netbsd-arm64": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.2.tgz",
|
||||
"integrity": "sha512-Kj6DiBlwXrPsCRDeRvGAUb/LNrBASrfqAIok+xB0LxK8CHqxZ037viF13ugfsIpePH93mX7xfJp97cyDuTZ3cw==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"ideallyInert": true,
|
||||
"node_modules/@noble/ciphers": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-2.2.0.tgz",
|
||||
"integrity": "sha512-Z6pjIZ/8IJcCGzb2S/0Px5J81yij85xASuk1teLNeg75bfT07MV3a/O2Mtn1I2se43k3lkVEcFaR10N4cgQcZA==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"netbsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
"node": ">= 20.19.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://paulmillr.com/funding/"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/netbsd-x64": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.2.tgz",
|
||||
"integrity": "sha512-HwGDZ0VLVBY3Y+Nw0JexZy9o/nUAWq9MlV7cahpaXKW6TOzfVno3y3/M8Ga8u8Yr7GldLOov27xiCnqRZf0tCA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"ideallyInert": true,
|
||||
"node_modules/@noble/curves": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@noble/curves/-/curves-2.2.0.tgz",
|
||||
"integrity": "sha512-T/BoHgFXirb0ENSPBquzX0rcjXeM6Lo892a2jlYJkqk83LqZx0l1Of7DzlKJ6jkpvMrkHSnAcgb5JegL8SeIkQ==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"netbsd"
|
||||
],
|
||||
"dependencies": {
|
||||
"@noble/hashes": "2.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
"node": ">= 20.19.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://paulmillr.com/funding/"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/openbsd-arm64": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.2.tgz",
|
||||
"integrity": "sha512-DNIHH2BPQ5551A7oSHD0CKbwIA/Ox7+78/AWkbS5QoRzaqlev2uFayfSxq68EkonB+IKjiuxBFoV8ESJy8bOHA==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"ideallyInert": true,
|
||||
"node_modules/@noble/hashes": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.2.0.tgz",
|
||||
"integrity": "sha512-IYqDGiTXab6FniAgnSdZwgWbomxpy9FtYvLKs7wCUs2a8RkITG+DFGO1DM9cr+E3/RgADRpFjrKVaJ1z6sjtEg==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"openbsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
"node": ">= 20.19.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://paulmillr.com/funding/"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/openbsd-x64": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.2.tgz",
|
||||
"integrity": "sha512-/it7w9Nb7+0KFIzjalNJVR5bOzA9Vay+yIPLVHfIQYG/j+j9VTH84aNB8ExGKPU4AzfaEvN9/V4HV+F+vo8OEg==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"ideallyInert": true,
|
||||
"node_modules/@noble/post-quantum": {
|
||||
"version": "0.6.1",
|
||||
"resolved": "https://registry.npmjs.org/@noble/post-quantum/-/post-quantum-0.6.1.tgz",
|
||||
"integrity": "sha512-+pormrDZwjRw05U8ADK4JpHejo87+gBd+muRBB/ozztH5yhDLMDF4jHQWN3NQQAsu1zBNPWTG0ZwVI0CR29H0A==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"openbsd"
|
||||
],
|
||||
"dependencies": {
|
||||
"@noble/ciphers": "~2.2.0",
|
||||
"@noble/curves": "~2.2.0",
|
||||
"@noble/hashes": "~2.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
"node": ">= 20.19.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://paulmillr.com/funding/"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/openharmony-arm64": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.2.tgz",
|
||||
"integrity": "sha512-LRBbCmiU51IXfeXk59csuX/aSaToeG7w48nMwA6049Y4J4+VbWALAuXcs+qcD04rHDuSCSRKdmY63sruDS5qag==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"ideallyInert": true,
|
||||
"node_modules/@scure/base": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@scure/base/-/base-2.2.0.tgz",
|
||||
"integrity": "sha512-b8XEupJibegiXV+tDUseI8oLQc8ei3d/4Jkb2RpbHh3MfE054ov3uIz2dhFkB3FI8iwYkEh0gGCApkrYggkPNg==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"openharmony"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
"funding": {
|
||||
"url": "https://paulmillr.com/funding/"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/sunos-x64": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.2.tgz",
|
||||
"integrity": "sha512-kMtx1yqJHTmqaqHPAzKCAkDaKsffmXkPHThSfRwZGyuqyIeBvf08KSsYXl+abf5HDAPMJIPnbBfXvP2ZC2TfHg==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"ideallyInert": true,
|
||||
"node_modules/@scure/bip32": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@scure/bip32/-/bip32-2.2.0.tgz",
|
||||
"integrity": "sha512-zFr7t2F+a9+5tB7QbarF2HQNYrgjCNaoLAupZdKkrFMYMozJf5zqH2WJCQibMzm1qQ0QogrxVGO3qXfQDYMaQg==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"sunos"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
"dependencies": {
|
||||
"@noble/curves": "2.2.0",
|
||||
"@noble/hashes": "2.2.0",
|
||||
"@scure/base": "2.2.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://paulmillr.com/funding/"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/win32-arm64": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.2.tgz",
|
||||
"integrity": "sha512-Yaf78O/B3Kkh+nKABUF++bvJv5Ijoy9AN1ww904rOXZFLWVc5OLOfL56W+C8F9xn5JQZa3UX6m+IktJnIb1Jjg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"ideallyInert": true,
|
||||
"node_modules/@scure/bip39": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@scure/bip39/-/bip39-2.2.0.tgz",
|
||||
"integrity": "sha512-T/Bj/YvYMNkIPq6EENO6/rcs2e7qTNuyoUXf0KBFDmp0ZDu0H2X4Lq6yC3i0c8PcWkov5EbW+yQZZbdMmk154A==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/win32-ia32": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.2.tgz",
|
||||
"integrity": "sha512-Iuws0kxo4yusk7sw70Xa2E2imZU5HoixzxfGCdxwBdhiDgt9vX9VUCBhqcwY7/uh//78A1hMkkROMJq9l27oLQ==",
|
||||
"cpu": [
|
||||
"ia32"
|
||||
],
|
||||
"dev": true,
|
||||
"ideallyInert": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/win32-x64": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.2.tgz",
|
||||
"integrity": "sha512-sRdU18mcKf7F+YgheI/zGf5alZatMUTKj/jNS6l744f9u3WFu4v7twcUI9vu4mknF4Y9aDlblIie0IM+5xxaqQ==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"ideallyInert": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
"dependencies": {
|
||||
"@noble/hashes": "2.2.0",
|
||||
"@scure/base": "2.2.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://paulmillr.com/funding/"
|
||||
}
|
||||
},
|
||||
"node_modules/esbuild": {
|
||||
|
||||
22
node_modules/@noble/ciphers/LICENSE
generated
vendored
Normal file
22
node_modules/@noble/ciphers/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,22 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2022 Paul Miller (https://paulmillr.com)
|
||||
Copyright (c) 2016 Thomas Pornin <pornin@bolet.org>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the “Software”), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
607
node_modules/@noble/ciphers/README.md
generated
vendored
Normal file
607
node_modules/@noble/ciphers/README.md
generated
vendored
Normal file
@@ -0,0 +1,607 @@
|
||||
# noble-ciphers
|
||||
|
||||
Audited & minimal JS implementation of Salsa20, ChaCha and AES.
|
||||
|
||||
- 🔒 [**Audited**](#security) by an independent security firm
|
||||
- 🔻 Tree-shakeable: unused code is excluded from your builds
|
||||
- 🏎 Fast: hand-optimized for caveats of JS engines
|
||||
- 🔍 Reliable: property-based / cross-library / wycheproof tests ensure correctness
|
||||
- 💼 AES: ECB, CBC, CTR, CFB, GCM, SIV (nonce misuse-resistant), AESKW, AESKWP
|
||||
- 💃 Salsa20, ChaCha, XSalsa20, XChaCha, ChaCha8, ChaCha12, Poly1305
|
||||
- 🥈 Two AES implementations: pure JS or friendly WebCrypto wrapper
|
||||
- 🪶 11KB (gzipped) for everything, 3KB for ChaCha-only build
|
||||
|
||||
Use [awasm-noble](https://github.com/paulmillr/awasm-noble) if you need an even faster (WASM) alternative. Check out [Upgrading](#upgrading) for information about upgrading from previous versions.
|
||||
Take a glance at [GitHub Discussions](https://github.com/paulmillr/noble-ciphers/discussions) for questions and support.
|
||||
|
||||
### This library belongs to _noble_ cryptography
|
||||
|
||||
> **noble cryptography** — high-security, easily auditable set of contained cryptographic libraries and tools.
|
||||
|
||||
- Zero or minimal dependencies
|
||||
- Highly readable TypeScript / JS code
|
||||
- PGP-signed releases and transparent NPM builds
|
||||
- All libraries:
|
||||
[ciphers](https://github.com/paulmillr/noble-ciphers),
|
||||
[curves](https://github.com/paulmillr/noble-curves),
|
||||
[hashes](https://github.com/paulmillr/noble-hashes),
|
||||
[post-quantum](https://github.com/paulmillr/noble-post-quantum),
|
||||
5kb [secp256k1](https://github.com/paulmillr/noble-secp256k1) /
|
||||
[ed25519](https://github.com/paulmillr/noble-ed25519)
|
||||
- [Check out the homepage](https://paulmillr.com/noble/)
|
||||
for reading resources, documentation, and apps built with noble
|
||||
|
||||
## Usage
|
||||
|
||||
> `npm install @noble/ciphers`
|
||||
|
||||
> `deno add jsr:@noble/ciphers`
|
||||
|
||||
We support all major platforms and runtimes.
|
||||
For React Native, you may need a
|
||||
[polyfill for getRandomValues](https://github.com/LinusU/react-native-get-random-values).
|
||||
A standalone file
|
||||
[noble-ciphers.js](https://github.com/paulmillr/noble-ciphers/releases) is also available.
|
||||
|
||||
```ts
|
||||
// import * from '@noble/ciphers'; // Error: use sub-imports, to ensure small app size
|
||||
import { gcm, gcmsiv } from '@noble/ciphers/aes.js';
|
||||
import { chacha20poly1305, xchacha20poly1305 } from '@noble/ciphers/chacha.js';
|
||||
import { xsalsa20poly1305 } from '@noble/ciphers/salsa.js';
|
||||
|
||||
// Unauthenticated encryption: make sure to use HMAC or similar
|
||||
import { ctr, cfb, cbc, ecb } from '@noble/ciphers/aes.js';
|
||||
import { salsa20, xsalsa20 } from '@noble/ciphers/salsa.js';
|
||||
import { chacha20, xchacha20, chacha8, chacha12 } from '@noble/ciphers/chacha.js';
|
||||
import { aeskw, aeskwp } from '@noble/ciphers/aes.js'; // KW
|
||||
import { bytesToHex, hexToBytes, managedNonce, randomBytes } from '@noble/ciphers/utils.js';
|
||||
```
|
||||
|
||||
- [Examples](#examples)
|
||||
- [XChaCha20-Poly1305 encryption](#xchacha20-poly1305-encryption)
|
||||
- [AES-256-GCM encryption](#aes-256-gcm-encryption)
|
||||
- [managedNonce: automatic nonce handling](#managednonce-automatic-nonce-handling)
|
||||
- [AES: gcm, siv, ctr, cfb, cbc, ecb, aeskw](#aes-gcm-siv-ctr-cfb-cbc-ecb-aeskw)
|
||||
- [AES: friendly WebCrypto wrapper](#aes-friendly-webcrypto-wrapper)
|
||||
- [Reuse array for input and output](#reuse-array-for-input-and-output)
|
||||
- [Use password for encryption](#use-password-for-encryption)
|
||||
- [Internals](#internals)
|
||||
- [Picking a cipher](#picking-a-cipher)
|
||||
- [How to encrypt properly](#how-to-encrypt-properly)
|
||||
- [Nonces](#nonces)
|
||||
- [Encryption limits](#encryption-limits)
|
||||
- [AES block modes](#aes-block-modes)
|
||||
- [Implemented primitives](#implemented-primitives)
|
||||
- [Security](#security)
|
||||
- [Speed](#speed)
|
||||
- [Upgrading](#upgrading)
|
||||
- [Contributing & testing](#contributing--testing)
|
||||
- [License](#license)
|
||||
|
||||
## Examples
|
||||
|
||||
> [!NOTE]
|
||||
> Use different nonce every time `encrypt()` is done.
|
||||
|
||||
#### XChaCha20-Poly1305 encryption
|
||||
|
||||
```js
|
||||
import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';
|
||||
import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
const key = randomBytes(32); // random key
|
||||
// const key = new Uint8Array([ // existing key
|
||||
// 169, 88, 160, 139, 168, 29, 147, 196, 14, 88, 237, 76, 243, 177, 109, 140,
|
||||
// 195, 140, 80, 10, 216, 134, 215, 71, 191, 48, 20, 104, 189, 37, 38, 55,
|
||||
// ]);
|
||||
// import { hexToBytes } from '@noble/ciphers/utils.js'; // hex key
|
||||
// const key = hexToBytes('4b7f89bac90a1086fef73f5da2cbe93b2fae9dfbf7678ae1f3e75fd118ddf999');
|
||||
const nonce = randomBytes(24);
|
||||
const chacha = xchacha20poly1305(key, nonce);
|
||||
const data = new TextEncoder().encode('hello noble');
|
||||
const ciphertext = chacha.encrypt(data);
|
||||
const data_ = chacha.decrypt(ciphertext); // new TextDecoder().decode(data_) === data
|
||||
```
|
||||
|
||||
#### AES-256-GCM encryption
|
||||
|
||||
```js
|
||||
import { gcm } from '@noble/ciphers/aes.js';
|
||||
import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
const key = randomBytes(32);
|
||||
const nonce = randomBytes(24);
|
||||
const data = new TextEncoder().encode('hello noble');
|
||||
const aes = gcm(key, nonce);
|
||||
const ciphertext = aes.encrypt(data);
|
||||
const data_ = aes.decrypt(ciphertext); // new TextDecoder().decode(data_) === data
|
||||
```
|
||||
|
||||
#### managedNonce: automatic nonce handling
|
||||
|
||||
We provide API that manages nonce internally instead of exposing them to library's user.
|
||||
|
||||
For `encrypt`: a `nonceBytes`-length buffer is fetched from CSPRNG and prenended to encrypted ciphertext.
|
||||
|
||||
For `decrypt`: first `nonceBytes` of ciphertext are treated as nonce.
|
||||
|
||||
> [!NOTE]
|
||||
> AES-GCM & ChaCha (NOT XChaCha) [limit amount of messages](#encryption-limits)
|
||||
> encryptable under the same key.
|
||||
|
||||
```js
|
||||
import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';
|
||||
import { hexToBytes, managedNonce } from '@noble/ciphers/utils.js';
|
||||
const key = hexToBytes('fa686bfdffd3758f6377abbc23bf3d9bdc1a0dda4a6e7f8dbdd579fa1ff6d7e1');
|
||||
const chacha = managedNonce(xchacha20poly1305)(key); // manages nonces for you
|
||||
const data = new TextEncoder().encode('hello noble');
|
||||
const ciphertext = chacha.encrypt(data);
|
||||
const data_ = chacha.decrypt(ciphertext);
|
||||
```
|
||||
|
||||
#### AES: gcm, siv, ctr, cfb, cbc, ecb, aeskw
|
||||
|
||||
```js
|
||||
import { gcm, gcmsiv, aessiv, ctr, cfb, cbc, ecb } from '@noble/ciphers/aes.js';
|
||||
import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
const plaintext = new Uint8Array(32).fill(16);
|
||||
for (let cipher of [gcm, gcmsiv, aessiv]) {
|
||||
const key = randomBytes(32); // 24 for AES-192, 16 for AES-128
|
||||
const nonce = randomBytes(12);
|
||||
const ciphertext_ = cipher(key, nonce).encrypt(plaintext);
|
||||
const plaintext_ = cipher(key, nonce).decrypt(ciphertext_);
|
||||
}
|
||||
for (const cipher of [ctr, cbc, cfb]) {
|
||||
const key = randomBytes(32); // 24 for AES-192, 16 for AES-128
|
||||
const nonce = randomBytes(16);
|
||||
const ciphertext_ = cipher(key, nonce).encrypt(plaintext);
|
||||
const plaintext_ = cipher(key, nonce).decrypt(ciphertext_);
|
||||
}
|
||||
for (const cipher of [ecb]) {
|
||||
const key = randomBytes(32); // 24 for AES-192, 16 for AES-128
|
||||
const ciphertext_ = cipher(key).encrypt(plaintext);
|
||||
const plaintext_ = cipher(key).decrypt(ciphertext_);
|
||||
}
|
||||
|
||||
// AESKW, AESKWP
|
||||
import { aeskw, aeskwp } from '@noble/ciphers/aes.js';
|
||||
import { hexToBytes } from '@noble/ciphers/utils.js';
|
||||
|
||||
const kek = hexToBytes('000102030405060708090A0B0C0D0E0F');
|
||||
const keyData = hexToBytes('00112233445566778899AABBCCDDEEFF');
|
||||
const ciphertext = aeskw(kek).encrypt(keyData);
|
||||
```
|
||||
|
||||
#### AES: friendly WebCrypto wrapper
|
||||
|
||||
Noble implements AES. Sometimes people want to use built-in `crypto.subtle` instead. However, it has terrible API. We simplify access to built-ins.
|
||||
|
||||
> [!NOTE]
|
||||
> Webcrypto methods are always async.
|
||||
|
||||
```js
|
||||
import { gcm, ctr, cbc } from '@noble/ciphers/webcrypto.js';
|
||||
import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
const plaintext = new Uint8Array(32).fill(16);
|
||||
const key = randomBytes(32);
|
||||
for (const cipher of [gcm]) {
|
||||
const nonce = randomBytes(12);
|
||||
const ciphertext_ = await cipher(key, nonce).encrypt(plaintext);
|
||||
const plaintext_ = await cipher(key, nonce).decrypt(ciphertext_);
|
||||
}
|
||||
for (const cipher of [ctr, cbc]) {
|
||||
const nonce = randomBytes(16);
|
||||
const ciphertext_ = await cipher(key, nonce).encrypt(plaintext);
|
||||
const plaintext_ = await cipher(key, nonce).decrypt(ciphertext_);
|
||||
}
|
||||
```
|
||||
|
||||
#### Reuse array for input and output
|
||||
|
||||
To avoid additional allocations, Uint8Array can be reused
|
||||
between encryption and decryption calls.
|
||||
|
||||
> [!NOTE]
|
||||
> Some ciphers don't support unaligned (`byteOffset % 4 !== 0`) Uint8Array as
|
||||
> destination. It can decrease performance, making the optimization pointless.
|
||||
|
||||
```js
|
||||
import { chacha20poly1305 } from '@noble/ciphers/chacha.js';
|
||||
import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
|
||||
const key = randomBytes(32);
|
||||
const nonce = randomBytes(12);
|
||||
const chacha = chacha20poly1305(key, nonce);
|
||||
|
||||
const input = new TextEncoder().encode('hello noble'); // length == 12
|
||||
const inputLength = input.length;
|
||||
const tagLength = 16;
|
||||
|
||||
const buf = new Uint8Array(inputLength + tagLength);
|
||||
const start = buf.subarray(0, inputLength);
|
||||
start.set(input); // copy input to buf
|
||||
|
||||
chacha.encrypt(start, buf); // encrypt into `buf`
|
||||
chacha.decrypt(buf, start); // decrypt into `start`
|
||||
```
|
||||
|
||||
xsalsa20poly1305 also supports this, but requires 32 additional bytes for encryption / decryption,
|
||||
due to its inner workings.
|
||||
|
||||
#### Randomness generation
|
||||
|
||||
We provide userspace CSPRNG (cryptographically secure pseudorandom number generator).
|
||||
It's best to limit their usage to non-production, non-critical cases: for example, test-only usage.
|
||||
ChaCha-based CSPRNG does not have a specification as per 2025, which makes it less secure.
|
||||
|
||||
```js
|
||||
import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
import { rngAesCtrDrbg256 } from '@noble/ciphers/aes.js';
|
||||
import { rngChacha8, rngChacha20 } from '@noble/ciphers/chacha.js';
|
||||
|
||||
// 1. Best: WebCrypto
|
||||
const rnd1 = randomBytes(32);
|
||||
// 2. AES-CTR DRBG
|
||||
const seed2 = randomBytes(48);
|
||||
const rnd2 = rngAesCtrDrbg256(seed2).randomBytes(1024);
|
||||
// 3. ChaCha8 CSPRNG
|
||||
const seed3 = randomBytes(32);
|
||||
const rnd3 = rngChacha8(seed3).randomBytes(1024);
|
||||
```
|
||||
|
||||
#### Use password for encryption
|
||||
|
||||
It is not safe to convert password into Uint8Array.
|
||||
Instead, KDF stretching function like PBKDF2 / Scrypt / Argon2id
|
||||
should be applied to convert password to AES key.
|
||||
Make sure to use salt (app-specific secret) in addition to password.
|
||||
|
||||
> `npm install @noble/hashes`
|
||||
|
||||
```js
|
||||
import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';
|
||||
import { managedNonce } from '@noble/ciphers/utils.js';
|
||||
import { scrypt } from '@noble/hashes/scrypt.js';
|
||||
|
||||
// Convert password into 32-byte key using scrypt
|
||||
const PASSWORD = 'correct-horse-battery-staple';
|
||||
const APP_SPECIFIC_SECRET = 'salt-12345678-secret';
|
||||
const SECURITY_LEVEL = 2 ** 20; // requires 1GB of RAM to calculate
|
||||
// sync, but scryptAsync is also available
|
||||
const key = scrypt(PASSWORD, APP_SPECIFIC_SECRET, { N: SECURITY_LEVEL, r: 8, p: 1, dkLen: 32 });
|
||||
|
||||
// Use random, managed nonce
|
||||
const chacha = managedNonce(xchacha20poly1305)(key);
|
||||
|
||||
const data = new TextEncoder().encode('hello noble');
|
||||
const ciphertext = chacha.encrypt(data);
|
||||
const data_ = chacha.decrypt(ciphertext);
|
||||
```
|
||||
|
||||
## Internals
|
||||
|
||||
### Picking a cipher
|
||||
|
||||
We suggest to use **XChaCha20-Poly1305** because it's very fast and allows random keys.
|
||||
**AES-GCM-SIV** is also a good idea, because it provides resistance against nonce reuse.
|
||||
**AES-GCM** is a good option when those two are not available.
|
||||
|
||||
### How to encrypt properly
|
||||
|
||||
- Use unpredictable key with enough entropy
|
||||
- Random key must be using cryptographically secure random number generator (CSPRNG), not `Math.random` etc.
|
||||
- Non-random key generated from KDF is fine
|
||||
- Re-using key is fine, but be aware of rules for cryptographic key wear-out and [encryption limits](#encryption-limits)
|
||||
- Use new nonce every time and [don't repeat it](#nonces)
|
||||
- chacha and salsa20 are fine for sequential counters that _never_ repeat: `01, 02...`
|
||||
- xchacha and xsalsa20 can use random nonces instead
|
||||
- AES-GCM should use 12-byte nonces: smaller nonces are security risk
|
||||
- Prefer authenticated encryption (AEAD)
|
||||
- Good: chacha20poly1305, GCM, GCM-SIV, ChaCha+HMAC, CTR+HMAC, CBC+HMAC
|
||||
- Bad: chacha20, raw CTR, raw CBC
|
||||
- Flipping bits or ciphertext substitution won't be detected in unauthenticated ciphers
|
||||
- Polynomial MACs are not perfect for every situation:
|
||||
they lack Random Key Robustness: the MAC can be forged, and can't
|
||||
be used in PAKE schemes. See
|
||||
[invisible salamanders attack](https://keymaterial.net/2020/09/07/invisible-salamanders-in-aes-gcm-siv/).
|
||||
To combat salamanders, `hash(key)` can be included in ciphertext,
|
||||
however, this would violate ciphertext indistinguishability:
|
||||
an attacker would know which key was used - so `HKDF(key, i)`
|
||||
could be used instead.
|
||||
- Don't re-use keys between different protocols
|
||||
- For example, using ECDH key in AES can be bad
|
||||
- Use hkdf or, at least, a hash function to create sub-key instead
|
||||
|
||||
### Nonces
|
||||
|
||||
Most ciphers need a key and a nonce (aka initialization vector / IV) to encrypt a data.
|
||||
Repeating (key, nonce) pair with different plaintexts would allow an attacker to decrypt it.
|
||||
|
||||
ciphertext_a = encrypt(plaintext_a, key, nonce)
|
||||
ciphertext_b = encrypt(plaintext_b, key, nonce)
|
||||
stream_diff = xor(ciphertext_a, ciphertext_b) # Break encryption
|
||||
|
||||
One way of not repeating nonces is using counters:
|
||||
|
||||
for i in 0..:
|
||||
ciphertext[i] = encrypt(plaintexts[i], key, i)
|
||||
|
||||
Another is generating random nonce every time:
|
||||
|
||||
for i in 0..:
|
||||
rand_nonces[i] = random()
|
||||
ciphertext[i] = encrypt(plaintexts[i], key, rand_nonces[i])
|
||||
|
||||
- Counters are OK, but it's not always possible to store current counter value:
|
||||
e.g. in decentralized, unsyncable systems.
|
||||
- Randomness is OK, but there's a catch:
|
||||
ChaCha20 and AES-GCM use 96-bit / 12-byte nonces, which implies higher chance of collision.
|
||||
In the example above, `random()` can collide and produce repeating nonce.
|
||||
Chance is even higher for 64-bit nonces, which GCM allows - don't use them.
|
||||
- To safely use random nonces, utilize XSalsa20 or XChaCha:
|
||||
they increased nonce length to 192-bit, minimizing a chance of collision.
|
||||
AES-SIV is also fine. In situations where you can't use eXtended-nonce
|
||||
algorithms, key rotation is advised. hkdf would work great for this case.
|
||||
|
||||
### Encryption limits
|
||||
|
||||
A "protected message" would mean a probability of `2**-50` that a passive attacker
|
||||
successfully distinguishes the ciphertext outputs of the AEAD scheme from the outputs
|
||||
of a random function.
|
||||
|
||||
- Max message size:
|
||||
- AES-GCM: ~68GB, `2**36-256`
|
||||
- Salsa, ChaCha, XSalsa, XChaCha: ~256GB, `2**38-64`
|
||||
- Max amount of protected messages, under same key:
|
||||
- AES-GCM: `2**32.5`
|
||||
- Salsa, ChaCha: `2**46`, but only integrity (MAC) is affected, not confidentiality (encryption)
|
||||
- XSalsa, XChaCha: `2**72`
|
||||
- Max amount of protected messages, across all keys:
|
||||
- AES-GCM: `2**69/B` where B is max blocks encrypted by a key. Meaning
|
||||
`2**59` for 1KB, `2**49` for 1MB, `2**39` for 1GB
|
||||
- Salsa, ChaCha, XSalsa, XChaCha: `2**100`
|
||||
- Max amount of protected messages, under same key, using **random nonce**:
|
||||
- Relevant for 12-byte nonces with `managedNonce`: AES-GCM, ChaCha
|
||||
- `2**23` (8M) messages for `2**-50` chance, `2**32.5` (4B) for `2**-32.5` chance
|
||||
|
||||
Check out [draft-irtf-cfrg-aead-limits](https://datatracker.ietf.org/doc/draft-irtf-cfrg-aead-limits/) for details.
|
||||
|
||||
### Implemented primitives
|
||||
|
||||
- Salsa20 stream cipher, released in 2005.
|
||||
Salsa's goal was to implement AES replacement that does not rely on S-Boxes,
|
||||
which are hard to implement in a constant-time manner.
|
||||
Salsa20 is usually faster than AES, a big deal on slow, budget mobile phones.
|
||||
- [XSalsa20](https://cr.yp.to/snuffle/xsalsa-20110204.pdf), extended-nonce
|
||||
variant was released in 2008. It switched nonces from 96-bit to 192-bit,
|
||||
and became safe to be picked at random.
|
||||
- Nacl / Libsodium popularized term "secretbox", - which is just xsalsa20poly1305.
|
||||
We provide the alias and corresponding seal / open methods.
|
||||
"crypto_box" and "sealedbox" are available in package [noble-sodium](https://github.com/serenity-kit/noble-sodium).
|
||||
- Check out [PDF](https://cr.yp.to/snuffle/salsafamily-20071225.pdf)
|
||||
and [website](https://cr.yp.to/snuffle.html).
|
||||
- ChaCha20 stream cipher, released in 2008. Developed after Salsa20,
|
||||
ChaCha aims to increase diffusion per round.
|
||||
- [XChaCha20](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha)
|
||||
extended-nonce variant is also provided. Similar to XSalsa, it's safe to use with
|
||||
randomly-generated nonces.
|
||||
- Check out
|
||||
[RFC 8439](https://www.rfc-editor.org/rfc/rfc8439),
|
||||
[PDF](http://cr.yp.to/chacha/chacha-20080128.pdf) and
|
||||
[website](https://cr.yp.to/chacha.html).
|
||||
- AES is a variant of Rijndael block cipher, standardized by NIST in 2001.
|
||||
We provide the fastest available pure JS implementation.
|
||||
- We support AES-128, AES-192 and AES-256: the mode is selected dynamically,
|
||||
based on key length (16, 24, 32).
|
||||
- AES-GCM-SIV nonce-misuse-resistant mode is also provided. Our implementation of SIV
|
||||
has the same speed as GCM: there is no performance hit.
|
||||
The mode is described in [RFC 8452](https://www.rfc-editor.org/rfc/rfc8452).
|
||||
- There is a separate AES-SIV mode, described in [RFC 5297](https://www.rfc-editor.org/rfc/rfc5297)
|
||||
- We also have AESKW and AESKWP from
|
||||
[RFC 3394](https://www.rfc-editor.org/rfc/rfc3394) & [RFC 5649](https://www.rfc-editor.org/rfc/rfc5649)
|
||||
- Format-preserving encryption algorithm (FPE-FF1) specified in
|
||||
[NIST SP 800-38G](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf).
|
||||
- Check out [AES block modes](#aes-block-modes),
|
||||
[FIPS 197](https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf) and
|
||||
[original proposal](https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf).
|
||||
- Polynomial-evaluation MACs are available: Poly1305, AES-GCM's GHash and AES-SIV's Polyval.
|
||||
- Poly1305 ([PDF](https://cr.yp.to/mac/poly1305-20050329.pdf),
|
||||
[website](https://cr.yp.to/mac.html))
|
||||
is a fast and parallel secret-key message-authentication code suitable for
|
||||
a wide variety of applications. It was standardized in
|
||||
[RFC 8439](https://www.rfc-editor.org/rfc/rfc8439) and is now used in TLS 1.3.
|
||||
- Ghash is used in AES-GCM: see NIST SP 800-38G
|
||||
- Polyval is used in AES-GCM-SIV: see [RFC 8452](https://www.rfc-editor.org/rfc/rfc8452)
|
||||
|
||||
##### AES block modes
|
||||
|
||||
For non-deterministic (not ECB) schemes, initialization vector (IV) is mixed to block/key;
|
||||
and each new round either depends on previous block's key, or on some counter.
|
||||
|
||||
- **ECB** (Electronic Codebook): Deterministic encryption; identical plaintext blocks yield identical ciphertexts. Not secure due to pattern leakage. due to pattern leakage.
|
||||
See [AES Penguin](https://words.filippo.io/the-ecb-penguin/)
|
||||
- **CBC** (Cipher Block Chaining): Each plaintext block is XORed with the previous block of ciphertext
|
||||
before encryption. Hard to use: requires proper padding and an IV. Unauthenticated: needs MAC.
|
||||
- **CTR** (Counter Mode): Turns a block cipher into a stream cipher using a counter and IV (nonce).
|
||||
Efficient and parallelizable. Requires a unique nonce per encryption. Unauthenticated: needs MAC.
|
||||
- **GCM** (Galois/Counter Mode): Combines CTR mode with polynomial MAC. Efficient and widely used. Not perfect:
|
||||
a) conservative key wear-out is `2**32` (4B) msgs.
|
||||
b) key wear-out under random nonces is even smaller: `2**23` (8M) messages for `2**-50` chance.
|
||||
c) MAC can be forged: see Poly1305 documentation.
|
||||
- **SIV** (Synthetic IV): GCM with nonce-misuse resistance; repeating nonces reveal only the fact plaintexts
|
||||
are identical. Also suffers from GCM issues: key wear-out limits & MAC forging.
|
||||
- **XTS**: Designed for disk encryption.
|
||||
Similar to ECB (deterministic), but has `[i][j]` tweak arguments corresponding to
|
||||
sector i and 16-byte block (part of sector) j. Lacks MAC.
|
||||
|
||||
## Security
|
||||
|
||||
The library has been audited:
|
||||
|
||||
- at version 2.2.0, in Apr 2026, by ourselves (self-audited)
|
||||
- Scope: everything
|
||||
- [Changes since audit](https://github.com/paulmillr/noble-ciphers/compare/2.2.0..main)
|
||||
- at version 1.0.0, in Sep 2024, independently, by [cure53](https://cure53.de)
|
||||
- PDFs: [website](https://cure53.de/audit-report_noble-crypto-libs.pdf), [in-repo](./audit/2024-09-cure53-audit-nbl4.pdf)
|
||||
- [Changes since audit](https://github.com/paulmillr/noble-ciphers/compare/1.0.0..main)
|
||||
- Scope: everything
|
||||
- The audit has been funded by [OpenSats](https://opensats.org)
|
||||
|
||||
It is tested against property-based, cross-library and Wycheproof vectors,
|
||||
and is being fuzzed in [the separate repo](https://github.com/paulmillr/fuzzing).
|
||||
|
||||
If you see anything unusual: investigate and report.
|
||||
|
||||
### Constant-timeness
|
||||
|
||||
We're targetting algorithmic constant time. _JIT-compiler_ and _Garbage Collector_ make "constant time"
|
||||
extremely hard to achieve [timing attack](https://en.wikipedia.org/wiki/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](https://www.chosenplaintext.ca/open-source/rust-timing-shield/security)
|
||||
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.
|
||||
|
||||
The library uses T-tables for AES, which
|
||||
[leak access timings](https://cr.yp.to/antiforgery/cachetiming-20050414.pdf).
|
||||
This is also done in [OpenSSL](https://github.com/openssl/openssl/blob/2f33265039cdbd0e4589c80970e02e208f3f94d2/crypto/aes/aes_core.c#L706) and
|
||||
[Go stdlib](https://cs.opensource.google/go/go/+/refs/tags/go1.22.6:src/crypto/aes/const.go;l=90) for performance reasons.
|
||||
The analysis was mentioned in [hal-04652991](https://hal.science/hal-04652991/document).
|
||||
|
||||
### Supply chain security
|
||||
|
||||
- **Commits** are signed with PGP keys to prevent forgery. Be sure to verify the commit signatures
|
||||
- **Releases** are made transparently through token-less GitHub CI and Trusted Publishing. Be sure to verify the [provenance logs](https://docs.npmjs.com/generating-provenance-statements) for authenticity.
|
||||
- **Rare releasing** is practiced to minimize the need for re-audits by end-users.
|
||||
- **Dependencies** are minimized and strictly pinned to reduce supply-chain risk.
|
||||
- We use as few dependencies as possible.
|
||||
- Version ranges are locked, and changes are checked with npm-diff.
|
||||
- **Dev dependencies** are excluded from end-user installs; they’re only used for development and build steps.
|
||||
|
||||
For this package, there are 0 dependencies; and a few dev dependencies:
|
||||
|
||||
- jsbt is used for benchmarking / testing / build tooling and developed by the same author
|
||||
- prettier, fast-check and typescript are used for code quality / test generation / ts compilation
|
||||
|
||||
### Randomness
|
||||
|
||||
We rely on the built-in
|
||||
[`crypto.getRandomValues`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues),
|
||||
which is considered a cryptographically secure PRNG.
|
||||
|
||||
Browsers have had weaknesses in the past - and could again - but implementing a userspace CSPRNG is even worse, as there’s no reliable userspace source of high-quality entropy.
|
||||
|
||||
### Quantum computers
|
||||
|
||||
Cryptographically relevant quantum computer, if built, will allow to
|
||||
utilize Grover's algorithm to break ciphers in 2^n/2 operations, instead of 2^n.
|
||||
|
||||
This means AES128 should be replaced with AES256. Salsa and ChaCha are already safe.
|
||||
|
||||
Australian ASD prohibits AES128 [after 2030](https://www.cyber.gov.au/resources-business-and-government/essential-cyber-security/ism/cyber-security-guidelines/guidelines-cryptography).
|
||||
|
||||
## Speed
|
||||
|
||||
```sh
|
||||
npm run bench
|
||||
```
|
||||
|
||||
Benchmarks measured on Apple M4.
|
||||
If you need truly exemplar performance, switch to [awasm-noble](https://github.com/paulmillr/awasm-noble).
|
||||
|
||||
```
|
||||
64B
|
||||
xsalsa20poly1305 x 735,835 ops/sec @ 1μs/op
|
||||
chacha20poly1305 x 581,395 ops/sec @ 1μs/op
|
||||
xchacha20poly1305 x 468,384 ops/sec @ 2μs/op
|
||||
aes-256-gcm x 201,126 ops/sec @ 4μs/op
|
||||
aes-256-gcm-siv x 162,284 ops/sec @ 6μs/op
|
||||
# Unauthenticated encryption
|
||||
salsa20 x 1,655,629 ops/sec @ 604ns/op
|
||||
xsalsa20 x 1,400,560 ops/sec @ 714ns/op
|
||||
chacha20 x 1,996,007 ops/sec @ 501ns/op
|
||||
xchacha20 x 1,404,494 ops/sec @ 712ns/op
|
||||
chacha8 x 2,145,922 ops/sec @ 466ns/op
|
||||
chacha12 x 2,036,659 ops/sec @ 491ns/op
|
||||
aes-ecb-256 x 1,019,367 ops/sec @ 981ns/op
|
||||
aes-cbc-256 x 931,966 ops/sec @ 1μs/op
|
||||
aes-ctr-256 x 954,198 ops/sec @ 1μs/op
|
||||
|
||||
1MB
|
||||
xsalsa20poly1305 x 334 ops/sec @ 2ms/op
|
||||
chacha20poly1305 x 333 ops/sec @ 2ms/op
|
||||
xchacha20poly1305 x 334 ops/sec @ 2ms/op
|
||||
aes-256-gcm x 94 ops/sec @ 10ms/op
|
||||
aes-256-gcm-siv x 90 ops/sec @ 11ms/op
|
||||
# Unauthenticated encryption
|
||||
salsa20 x 831 ops/sec @ 1ms/op
|
||||
xsalsa20 x 830 ops/sec @ 1ms/op
|
||||
chacha20 x 804 ops/sec @ 1ms/op
|
||||
xchacha20 x 797 ops/sec @ 1ms/op
|
||||
chacha8 x 1,495 ops/sec @ 668μs/op
|
||||
chacha12 x 1,148 ops/sec @ 871μs/op
|
||||
aes-ecb-256 x 289 ops/sec @ 3ms/op
|
||||
aes-cbc-256 x 114 ops/sec @ 8ms/op
|
||||
aes-ctr-256 x 127 ops/sec @ 7ms/op
|
||||
# Wrapper over built-in webcrypto
|
||||
webcrypto ctr-256 x 6,508 ops/sec @ 153μs/op
|
||||
webcrypto cbc-256 x 1,820 ops/sec @ 549μs/op
|
||||
webcrypto gcm-256 x 5,106 ops/sec @ 195μs/op
|
||||
```
|
||||
|
||||
Compare to other implementations:
|
||||
|
||||
```
|
||||
xsalsa20poly1305 (encrypt, 1MB)
|
||||
├─tweetnacl x 196 mb/sec
|
||||
├─awasm-noble_threads x 2,318 mb/sec
|
||||
├─awasm-noble_no_threads x 1,196 mb/sec
|
||||
└─noble x 305 mb/sec
|
||||
|
||||
aes-ctr-256 (encrypt, 1MB)
|
||||
├─stablelib x 123 mb/sec
|
||||
├─aesjs x 42 mb/sec
|
||||
├─awasm-noble_thread x 2,105 mb/sec
|
||||
├─awasm-noble_no_threads x 272 mb/sec
|
||||
├─noble_webcrypto x 5,965 mb/sec
|
||||
└─noble x 124 mb/sec
|
||||
```
|
||||
|
||||
## Upgrading
|
||||
|
||||
Supported node.js versions:
|
||||
|
||||
- v2: v20.19+ (ESM-only)
|
||||
- v1: v14.21+ (ESM & CJS)
|
||||
|
||||
Changelog of v2, when upgrading from ciphers v1:
|
||||
|
||||
- The package is now ESM-only. ESM can finally be loaded from common.js on node v20.19+
|
||||
- `.js` extension must be used for all modules
|
||||
- Old: `@noble/ciphers/aes`
|
||||
- New: `@noble/ciphers/aes.js`
|
||||
- This simplifies working in browsers natively without transpilers
|
||||
- webcrypto: move `randomBytes` and `managedNonce` to `utils.js`
|
||||
- ghash, poly1305, polyval: only allow Uint8Array as hash inputs, prohibit `string`
|
||||
- utils: new abytes; remove ahash, toBytes
|
||||
- Remove modules `_assert` (use `utils`), `_micro` and `crypto` (use `webcrypto`)
|
||||
- Bump TS compilation target from es2020 to es2022
|
||||
- Massively improve error messages, make them more descriptive
|
||||
|
||||
## Contributing & testing
|
||||
|
||||
- `npm install && npm run build && npm test` will build the code and run tests.
|
||||
- `npm run lint` / `npm run format` will run linter / fix linter issues.
|
||||
- `npm run bench` will run benchmarks
|
||||
- `npm run build:release` will build single file
|
||||
|
||||
See [paulmillr.com/noble](https://paulmillr.com/noble/)
|
||||
for useful resources, articles, documentation and demos
|
||||
related to the library.
|
||||
|
||||
## License
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2023 Paul Miller [(https://paulmillr.com)](https://paulmillr.com)
|
||||
Copyright (c) 2016 Thomas Pornin <pornin@bolet.org>
|
||||
|
||||
See LICENSE file.
|
||||
145
node_modules/@noble/ciphers/_arx.d.ts
generated
vendored
Normal file
145
node_modules/@noble/ciphers/_arx.d.ts
generated
vendored
Normal file
@@ -0,0 +1,145 @@
|
||||
/**
|
||||
* Basic utils for ARX (add-rotate-xor) salsa and chacha ciphers.
|
||||
|
||||
RFC8439 requires multi-step cipher stream, where
|
||||
authKey starts with counter: 0, actual msg with counter: 1.
|
||||
|
||||
For this, we need a way to re-use nonce / counter:
|
||||
|
||||
const counter = new Uint8Array(4);
|
||||
chacha(..., counter, ...); // counter is now 1
|
||||
chacha(..., counter, ...); // counter is now 2
|
||||
|
||||
This is complicated:
|
||||
|
||||
- 32-bit counters are enough, no need for 64-bit: max ArrayBuffer size in JS is 4GB
|
||||
- Original papers don't allow mutating counters
|
||||
- Counter overflow is undefined [^1]
|
||||
- Idea A: allow providing (nonce | counter) instead of just nonce, re-use it
|
||||
- Caveat: Cannot be re-used through all cases:
|
||||
- * chacha has (counter | nonce)
|
||||
- * xchacha has (nonce16 | counter | nonce16)
|
||||
- Idea B: separate nonce / counter and provide separate API for counter re-use
|
||||
- Caveat: there are different counter sizes depending on an algorithm.
|
||||
- salsa & chacha also differ in structures of key & sigma:
|
||||
salsa20: s[0] | k(4) | s[1] | nonce(2) | cnt(2) | s[2] | k(4) | s[3]
|
||||
chacha: s(4) | k(8) | cnt(1) | nonce(3)
|
||||
chacha20orig: s(4) | k(8) | cnt(2) | nonce(2)
|
||||
- Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)`
|
||||
- Caveat: we can't re-use counter array
|
||||
|
||||
xchacha uses the subkey and remaining 8 byte nonce with ChaCha20 as normal
|
||||
(prefixed by 4 NUL bytes, since RFC8439 specifies a 12-byte nonce).
|
||||
Counter overflow is undefined; see {@link https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/ | the CFRG thread}.
|
||||
Current noble policy is strict non-wrap for the shared 32-bit counter path:
|
||||
exported ARX ciphers reject initial `0xffffffff` and stop before any implicit
|
||||
wrap back to zero.
|
||||
See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2 | the XChaCha appendix} for the extended-nonce construction.
|
||||
|
||||
* @module
|
||||
*/
|
||||
import { type PRG, type TArg, type TRet, type XorStream } from './utils.ts';
|
||||
/**
|
||||
* Rotates a 32-bit word left.
|
||||
* @param a - Input word.
|
||||
* @param b - Rotation count in bits.
|
||||
* @returns Rotated 32-bit word.
|
||||
* @example
|
||||
* Moves the top byte of `0x12345678` into the low byte position.
|
||||
* ```ts
|
||||
* rotl(0x12345678, 8);
|
||||
* ```
|
||||
*/
|
||||
export declare function rotl(a: number, b: number): number;
|
||||
/**
|
||||
* ARX core function operating on 32-bit words. Ciphers must use u32 for efficiency.
|
||||
* @param sigma - Sigma constants for the selected cipher layout.
|
||||
* @param key - Expanded key words.
|
||||
* @param nonce - Nonce and counter words prepared for the round function.
|
||||
* @param output - Output block written in place.
|
||||
* @param counter - Block counter value.
|
||||
* @param rounds - Optional round count override.
|
||||
*/
|
||||
export type CipherCoreFn = (sigma: TArg<Uint32Array>, key: TArg<Uint32Array>, nonce: TArg<Uint32Array>, output: TArg<Uint32Array>, counter: number, rounds?: number) => void;
|
||||
/**
|
||||
* Nonce-extension function used by XChaCha and XSalsa.
|
||||
* @param sigma - Sigma constants for the selected cipher layout.
|
||||
* @param key - Expanded key words.
|
||||
* @param input - Input nonce words used for subkey derivation.
|
||||
* @param output - Output buffer written with the derived nonce words.
|
||||
*/
|
||||
export type ExtendNonceFn = (sigma: TArg<Uint32Array>, key: TArg<Uint32Array>, input: TArg<Uint32Array>, output: TArg<Uint32Array>) => void;
|
||||
/** ARX cipher options.
|
||||
* * `allowShortKeys` for 16-byte keys
|
||||
* * `counterLength` in bytes
|
||||
* * `counterRight`: right: `nonce|counter`; left: `counter|nonce`
|
||||
* */
|
||||
export type CipherOpts = {
|
||||
/** Whether 16-byte keys are accepted for legacy Salsa and ChaCha variants. */
|
||||
allowShortKeys?: boolean;
|
||||
/** Optional nonce-expansion hook used by extended-nonce variants. */
|
||||
extendNonceFn?: ExtendNonceFn;
|
||||
/** Counter length in bytes inside the nonce/counter layout. */
|
||||
counterLength?: number;
|
||||
/** Whether the layout is `nonce|counter` instead of `counter|nonce`. */
|
||||
counterRight?: boolean;
|
||||
/** Number of core rounds to execute. */
|
||||
rounds?: number;
|
||||
};
|
||||
/**
|
||||
* Creates an ARX stream cipher from a 32-bit core permutation.
|
||||
* Used internally to build the exported Salsa and ChaCha stream ciphers.
|
||||
* @param core - Core function that fills one keystream block.
|
||||
* @param opts - Cipher layout and nonce-extension options. See {@link CipherOpts}.
|
||||
* @returns Stream cipher function over byte arrays.
|
||||
* @throws If the core callback, key size, counter, or output sizing is invalid. {@link Error}
|
||||
*/
|
||||
export declare function createCipher(core: TArg<CipherCoreFn>, opts: TArg<CipherOpts>): TRet<XorStream>;
|
||||
/** Internal class which wraps chacha20 or chacha8 to create CSPRNG. */
|
||||
export declare class _XorStreamPRG implements PRG {
|
||||
readonly blockLen: number;
|
||||
readonly keyLen: number;
|
||||
readonly nonceLen: number;
|
||||
private state;
|
||||
private buf;
|
||||
private key;
|
||||
private nonce;
|
||||
private pos;
|
||||
private ctr;
|
||||
private cipher;
|
||||
constructor(cipher: TArg<XorStream>, blockLen: number, keyLen: number, nonceLen: number, seed: TArg<Uint8Array>);
|
||||
private reseed;
|
||||
addEntropy(seed: TArg<Uint8Array>): void;
|
||||
randomBytes(len: number): TRet<Uint8Array>;
|
||||
clone(): _XorStreamPRG;
|
||||
clean(): void;
|
||||
}
|
||||
/**
|
||||
* PRG constructor backed by an ARX stream cipher.
|
||||
* @param seed - Optional seed bytes mixed into the initial state. When omitted, exactly 32
|
||||
* random bytes are mixed in by default: larger states keep a zero tail, while smaller states
|
||||
* wrap those bytes through `reseed()`'s XOR schedule.
|
||||
* @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`.
|
||||
*/
|
||||
export type XorPRG = (seed?: TArg<Uint8Array>) => TRet<_XorStreamPRG>;
|
||||
/**
|
||||
* Creates a PRG constructor from a stream cipher.
|
||||
* @param cipher - Stream cipher used to fill output blocks.
|
||||
* @param blockLen - Keystream block length in bytes.
|
||||
* @param keyLen - Internal key length in bytes.
|
||||
* @param nonceLen - Internal nonce length in bytes.
|
||||
* @returns PRG factory for seeded concrete `_XorStreamPRG` instances.
|
||||
* @example
|
||||
* Builds a PRG from XChaCha20 and reads bytes from a randomly seeded instance.
|
||||
* ```ts
|
||||
* import { xchacha20 } from '@noble/ciphers/chacha.js';
|
||||
* import { createPRG } from '@noble/ciphers/_arx.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const seed = randomBytes(32);
|
||||
* const init = createPRG(xchacha20, 64, 32, 24);
|
||||
* const prg = init(seed);
|
||||
* prg.randomBytes(8);
|
||||
* ```
|
||||
*/
|
||||
export declare const createPRG: (cipher: TArg<XorStream>, blockLen: number, keyLen: number, nonceLen: number) => TRet<XorPRG>;
|
||||
//# sourceMappingURL=_arx.d.ts.map
|
||||
1
node_modules/@noble/ciphers/_arx.d.ts.map
generated
vendored
Normal file
1
node_modules/@noble/ciphers/_arx.d.ts.map
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"_arx.d.ts","sourceRoot":"","sources":["src/_arx.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AACH,OAAO,EACL,KAAK,GAAG,EACR,KAAK,IAAI,EACT,KAAK,IAAI,EACT,KAAK,SAAS,EAaf,MAAM,YAAY,CAAC;AAcpB;;;;;;;;;;GAUG;AACH,wBAAgB,IAAI,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CAEjD;AAED;;;;;;;;GAQG;AACH,MAAM,MAAM,YAAY,GAAG,CACzB,KAAK,EAAE,IAAI,CAAC,WAAW,CAAC,EACxB,GAAG,EAAE,IAAI,CAAC,WAAW,CAAC,EACtB,KAAK,EAAE,IAAI,CAAC,WAAW,CAAC,EACxB,MAAM,EAAE,IAAI,CAAC,WAAW,CAAC,EACzB,OAAO,EAAE,MAAM,EACf,MAAM,CAAC,EAAE,MAAM,KACZ,IAAI,CAAC;AAEV;;;;;;GAMG;AACH,MAAM,MAAM,aAAa,GAAG,CAC1B,KAAK,EAAE,IAAI,CAAC,WAAW,CAAC,EACxB,GAAG,EAAE,IAAI,CAAC,WAAW,CAAC,EACtB,KAAK,EAAE,IAAI,CAAC,WAAW,CAAC,EACxB,MAAM,EAAE,IAAI,CAAC,WAAW,CAAC,KACtB,IAAI,CAAC;AAEV;;;;KAIK;AACL,MAAM,MAAM,UAAU,GAAG;IACvB,8EAA8E;IAC9E,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,qEAAqE;IACrE,aAAa,CAAC,EAAE,aAAa,CAAC;IAC9B,+DAA+D;IAC/D,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,wEAAwE;IACxE,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,wCAAwC;IACxC,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,CAAC;AA8FF;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,IAAI,CAAC,YAAY,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,CAoG9F;AAED,uEAAuE;AACvE,qBAAa,aAAc,YAAW,GAAG;IACvC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,OAAO,CAAC,KAAK,CAAmB;IAChC,OAAO,CAAC,GAAG,CAAmB;IAC9B,OAAO,CAAC,GAAG,CAAmB;IAC9B,OAAO,CAAC,KAAK,CAAmB;IAChC,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,MAAM,CAAkB;gBAE9B,MAAM,EAAE,IAAI,CAAC,SAAS,CAAC,EACvB,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,MAAM,EAChB,IAAI,EAAE,IAAI,CAAC,UAAU,CAAC;IAgBxB,OAAO,CAAC,MAAM;IASd,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI;IASxC,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC,UAAU,CAAC;IA+C1C,KAAK,IAAI,aAAa;IAYtB,KAAK,IAAI,IAAI;CAMd;AAED;;;;;;GAMG;AACH,MAAM,MAAM,MAAM,GAAG,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,UAAU,CAAC,KAAK,IAAI,CAAC,aAAa,CAAC,CAAC;AAEtE;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,SAAS,GACpB,QAAQ,IAAI,CAAC,SAAS,CAAC,EACvB,UAAU,MAAM,EAChB,QAAQ,MAAM,EACd,UAAU,MAAM,KACf,IAAI,CAAC,MAAM,CASb,CAAC"}
|
||||
369
node_modules/@noble/ciphers/_arx.js
generated
vendored
Normal file
369
node_modules/@noble/ciphers/_arx.js
generated
vendored
Normal file
@@ -0,0 +1,369 @@
|
||||
/**
|
||||
* Basic utils for ARX (add-rotate-xor) salsa and chacha ciphers.
|
||||
|
||||
RFC8439 requires multi-step cipher stream, where
|
||||
authKey starts with counter: 0, actual msg with counter: 1.
|
||||
|
||||
For this, we need a way to re-use nonce / counter:
|
||||
|
||||
const counter = new Uint8Array(4);
|
||||
chacha(..., counter, ...); // counter is now 1
|
||||
chacha(..., counter, ...); // counter is now 2
|
||||
|
||||
This is complicated:
|
||||
|
||||
- 32-bit counters are enough, no need for 64-bit: max ArrayBuffer size in JS is 4GB
|
||||
- Original papers don't allow mutating counters
|
||||
- Counter overflow is undefined [^1]
|
||||
- Idea A: allow providing (nonce | counter) instead of just nonce, re-use it
|
||||
- Caveat: Cannot be re-used through all cases:
|
||||
- * chacha has (counter | nonce)
|
||||
- * xchacha has (nonce16 | counter | nonce16)
|
||||
- Idea B: separate nonce / counter and provide separate API for counter re-use
|
||||
- Caveat: there are different counter sizes depending on an algorithm.
|
||||
- salsa & chacha also differ in structures of key & sigma:
|
||||
salsa20: s[0] | k(4) | s[1] | nonce(2) | cnt(2) | s[2] | k(4) | s[3]
|
||||
chacha: s(4) | k(8) | cnt(1) | nonce(3)
|
||||
chacha20orig: s(4) | k(8) | cnt(2) | nonce(2)
|
||||
- Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)`
|
||||
- Caveat: we can't re-use counter array
|
||||
|
||||
xchacha uses the subkey and remaining 8 byte nonce with ChaCha20 as normal
|
||||
(prefixed by 4 NUL bytes, since RFC8439 specifies a 12-byte nonce).
|
||||
Counter overflow is undefined; see {@link https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/ | the CFRG thread}.
|
||||
Current noble policy is strict non-wrap for the shared 32-bit counter path:
|
||||
exported ARX ciphers reject initial `0xffffffff` and stop before any implicit
|
||||
wrap back to zero.
|
||||
See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2 | the XChaCha appendix} for the extended-nonce construction.
|
||||
|
||||
* @module
|
||||
*/
|
||||
import { abool, abytes, anumber, checkOpts, clean, copyBytes, getOutput, isAligned32, isLE, randomBytes, swap32IfBE, u32, } from "./utils.js";
|
||||
// Replaces `TextEncoder` for ASCII literals, which is enough for sigma constants.
|
||||
// Non-ASCII input would not match UTF-8 `TextEncoder` output.
|
||||
const encodeStr = (str) => Uint8Array.from(str.split(''), (c) => c.charCodeAt(0));
|
||||
// Raw `createCipher(...)` exports consume these native-endian `u32(...)` views directly.
|
||||
// Public `wrapCipher(...)` APIs reject non-little-endian platforms before reaching this path.
|
||||
// RFC 8439 §2.3 / RFC 7539 §2.3 only define the 256-bit-key constants; this 16-byte sigma is
|
||||
// kept for legacy allowShortKeys Salsa/ChaCha variants.
|
||||
const sigma16_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr('expand 16-byte k'))))();
|
||||
// RFC 8439 §2.3 / RFC 7539 §2.3 define words 0-3 as
|
||||
// `0x61707865 0x3320646e 0x79622d32 0x6b206574`, i.e. `expand 32-byte k`.
|
||||
const sigma32_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr('expand 32-byte k'))))();
|
||||
/**
|
||||
* Rotates a 32-bit word left.
|
||||
* @param a - Input word.
|
||||
* @param b - Rotation count in bits.
|
||||
* @returns Rotated 32-bit word.
|
||||
* @example
|
||||
* Moves the top byte of `0x12345678` into the low byte position.
|
||||
* ```ts
|
||||
* rotl(0x12345678, 8);
|
||||
* ```
|
||||
*/
|
||||
export function rotl(a, b) {
|
||||
return (a << b) | (a >>> (32 - b));
|
||||
}
|
||||
// Salsa and Chacha block length is always 512-bit
|
||||
const BLOCK_LEN = 64;
|
||||
// RFC 8439 §2.2 / RFC 7539 §2.2: the ChaCha state has 16 32-bit words.
|
||||
const BLOCK_LEN32 = 16;
|
||||
// Counter policy for the shared public `counter` argument:
|
||||
// - RFC/IETF ChaCha20 uses a 32-bit counter.
|
||||
// - OpenSSL/Node `chacha20` instead treat the full 16-byte IV as a 128-bit
|
||||
// counter state and carry into the next word.
|
||||
// - Raw `chacha20orig`, `salsa20`, `xsalsa20`, and `xchacha20` use 64-bit counters in libsodium
|
||||
// and libtomcrypt, while some libs (for example libtomcrypt's RFC/IETF path) reject the max
|
||||
// boundary instead of carrying.
|
||||
// - AEAD wrappers diverge too: libsodium `xchacha20poly1305` uses the IETF payload counter from
|
||||
// block 1, while `secretstream_xchacha20poly1305` is a different protocol with rekey/reset.
|
||||
// Noble intentionally throws instead of silently picking one wrap model for users. In the default
|
||||
// path, even a 32-bit boundary would take 2^32 blocks * 64 bytes = 256 GiB, which is practically
|
||||
// unreachable for normal JS callers; advanced users who pass `counter` explicitly can implement
|
||||
// whatever wider carry / wrap policy they need on top.
|
||||
const MAX_COUNTER = /* @__PURE__ */ (() => 2 ** 32 - 1)();
|
||||
const U32_EMPTY = /* @__PURE__ */ Uint32Array.of();
|
||||
function runCipher(core, sigma, key, nonce, data, output, counter, rounds) {
|
||||
const len = data.length;
|
||||
const block = new Uint8Array(BLOCK_LEN);
|
||||
const b32 = u32(block);
|
||||
// Make sure that buffers aligned to 4 bytes
|
||||
const isAligned = isLE && isAligned32(data) && isAligned32(output);
|
||||
const d32 = isAligned ? u32(data) : U32_EMPTY;
|
||||
const o32 = isAligned ? u32(output) : U32_EMPTY;
|
||||
// RFC 8439 §2.4.1 / RFC 7539 §2.4.1 allow XORing one keystream block at a time and
|
||||
// truncating the final partial block instead of materializing the whole keystream.
|
||||
if (!isLE) {
|
||||
for (let pos = 0; pos < len; counter++) {
|
||||
core(sigma, key, nonce, b32, counter, rounds);
|
||||
// RFC 8439 §2.4 / RFC 7539 §2.4 serialize keystream words in little-endian order.
|
||||
swap32IfBE(b32);
|
||||
if (counter >= MAX_COUNTER)
|
||||
throw new Error('arx: counter overflow');
|
||||
const take = Math.min(BLOCK_LEN, len - pos);
|
||||
for (let j = 0, posj; j < take; j++) {
|
||||
posj = pos + j;
|
||||
output[posj] = data[posj] ^ block[j];
|
||||
}
|
||||
pos += take;
|
||||
}
|
||||
return;
|
||||
}
|
||||
for (let pos = 0; pos < len; counter++) {
|
||||
core(sigma, key, nonce, b32, counter, rounds);
|
||||
// See MAX_COUNTER policy note above: never silently wrap the shared public counter.
|
||||
if (counter >= MAX_COUNTER)
|
||||
throw new Error('arx: counter overflow');
|
||||
const take = Math.min(BLOCK_LEN, len - pos);
|
||||
// aligned to 4 bytes
|
||||
if (isAligned && take === BLOCK_LEN) {
|
||||
const pos32 = pos / 4;
|
||||
if (pos % 4 !== 0)
|
||||
throw new Error('arx: invalid block position');
|
||||
for (let j = 0, posj; j < BLOCK_LEN32; j++) {
|
||||
posj = pos32 + j;
|
||||
o32[posj] = d32[posj] ^ b32[j];
|
||||
}
|
||||
pos += BLOCK_LEN;
|
||||
continue;
|
||||
}
|
||||
for (let j = 0, posj; j < take; j++) {
|
||||
posj = pos + j;
|
||||
output[posj] = data[posj] ^ block[j];
|
||||
}
|
||||
pos += take;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Creates an ARX stream cipher from a 32-bit core permutation.
|
||||
* Used internally to build the exported Salsa and ChaCha stream ciphers.
|
||||
* @param core - Core function that fills one keystream block.
|
||||
* @param opts - Cipher layout and nonce-extension options. See {@link CipherOpts}.
|
||||
* @returns Stream cipher function over byte arrays.
|
||||
* @throws If the core callback, key size, counter, or output sizing is invalid. {@link Error}
|
||||
*/
|
||||
export function createCipher(core, opts) {
|
||||
const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts({ allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 }, opts);
|
||||
if (typeof core !== 'function')
|
||||
throw new Error('core must be a function');
|
||||
anumber(counterLength);
|
||||
anumber(rounds);
|
||||
abool(counterRight);
|
||||
abool(allowShortKeys);
|
||||
return (key, nonce, data, output, counter = 0) => {
|
||||
abytes(key, undefined, 'key');
|
||||
abytes(nonce, undefined, 'nonce');
|
||||
abytes(data, undefined, 'data');
|
||||
const len = data.length;
|
||||
// Raw XorStream APIs return ciphertext/plaintext bytes directly, so caller-provided outputs
|
||||
// must match the logical result length exactly instead of returning an oversized workspace.
|
||||
output = getOutput(len, output, false);
|
||||
anumber(counter);
|
||||
// See MAX_COUNTER policy note above: reject advanced explicit-counter requests before any wrap.
|
||||
if (counter < 0 || counter >= MAX_COUNTER)
|
||||
throw new Error('arx: counter overflow');
|
||||
const toClean = [];
|
||||
// Key & sigma
|
||||
// key=16 -> sigma16, k=key|key
|
||||
// key=32 -> sigma32, k=key
|
||||
let l = key.length;
|
||||
let k;
|
||||
let sigma;
|
||||
if (l === 32) {
|
||||
// Copy caller keys too: big-endian normalization, extended-nonce subkey derivation, and
|
||||
// final clean(...) all mutate or wipe the temporary buffer in place.
|
||||
toClean.push((k = copyBytes(key)));
|
||||
sigma = sigma32_32;
|
||||
}
|
||||
else if (l === 16 && allowShortKeys) {
|
||||
k = new Uint8Array(32);
|
||||
k.set(key);
|
||||
k.set(key, 16);
|
||||
sigma = sigma16_32;
|
||||
toClean.push(k);
|
||||
}
|
||||
else {
|
||||
abytes(key, 32, 'arx key');
|
||||
throw new Error('invalid key size');
|
||||
// throw new Error(`"arx key" expected Uint8Array of length 32, got length=${l}`);
|
||||
}
|
||||
// Nonce
|
||||
// salsa20: 8 (8-byte counter)
|
||||
// chacha20orig: 8 (8-byte counter)
|
||||
// chacha20: 12 (4-byte counter)
|
||||
// xsalsa20: 24 (16 -> hsalsa, 8 -> old nonce)
|
||||
// xchacha20: 24 (16 -> hchacha, 8 -> old nonce)
|
||||
// Copy before taking u32(...) views on misaligned inputs, and on big-endian so later
|
||||
// swap32IfBE(...) never mutates caller nonce bytes in place.
|
||||
if (!isLE || !isAligned32(nonce))
|
||||
toClean.push((nonce = copyBytes(nonce)));
|
||||
let k32 = u32(k);
|
||||
// hsalsa & hchacha: handle extended nonce
|
||||
if (extendNonceFn) {
|
||||
if (nonce.length !== 24)
|
||||
throw new Error(`arx: extended nonce must be 24 bytes`);
|
||||
const n16 = nonce.subarray(0, 16);
|
||||
if (isLE)
|
||||
extendNonceFn(sigma, k32, u32(n16), k32);
|
||||
else {
|
||||
const sigmaRaw = swap32IfBE(Uint32Array.from(sigma));
|
||||
extendNonceFn(sigmaRaw, k32, u32(n16), k32);
|
||||
clean(sigmaRaw);
|
||||
swap32IfBE(k32);
|
||||
}
|
||||
nonce = nonce.subarray(16);
|
||||
}
|
||||
else if (!isLE)
|
||||
swap32IfBE(k32);
|
||||
// Handle nonce counter
|
||||
const nonceNcLen = 16 - counterLength;
|
||||
if (nonceNcLen !== nonce.length)
|
||||
throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);
|
||||
// Normalize 64-bit-nonce layouts to the 12-byte core input: ChaCha/XChaCha prefix 4 zero
|
||||
// counter bytes, while Salsa/XSalsa append them after the nonce words.
|
||||
if (nonceNcLen !== 12) {
|
||||
const nc = new Uint8Array(12);
|
||||
nc.set(nonce, counterRight ? 0 : 12 - nonce.length);
|
||||
nonce = nc;
|
||||
toClean.push(nonce);
|
||||
}
|
||||
const n32 = swap32IfBE(u32(nonce));
|
||||
// Ensure temporary key/nonce copies are wiped even if the remaining
|
||||
// runtime guard in runCipher(...) throws on counter overflow.
|
||||
try {
|
||||
runCipher(core, sigma, k32, n32, data, output, counter, rounds);
|
||||
return output;
|
||||
}
|
||||
finally {
|
||||
clean(...toClean);
|
||||
}
|
||||
};
|
||||
}
|
||||
/** Internal class which wraps chacha20 or chacha8 to create CSPRNG. */
|
||||
export class _XorStreamPRG {
|
||||
blockLen;
|
||||
keyLen;
|
||||
nonceLen;
|
||||
state;
|
||||
buf;
|
||||
key;
|
||||
nonce;
|
||||
pos;
|
||||
ctr;
|
||||
cipher;
|
||||
constructor(cipher, blockLen, keyLen, nonceLen, seed) {
|
||||
this.cipher = cipher;
|
||||
this.blockLen = blockLen;
|
||||
this.keyLen = keyLen;
|
||||
this.nonceLen = nonceLen;
|
||||
this.state = new Uint8Array(this.keyLen + this.nonceLen);
|
||||
this.reseed(seed);
|
||||
this.ctr = 0;
|
||||
this.pos = this.blockLen;
|
||||
this.buf = new Uint8Array(this.blockLen);
|
||||
// Keep a single key||nonce backing buffer so reseed/addEntropy/clean update the live cipher
|
||||
// inputs in place through these subarray views.
|
||||
this.key = this.state.subarray(0, this.keyLen);
|
||||
this.nonce = this.state.subarray(this.keyLen);
|
||||
}
|
||||
reseed(seed) {
|
||||
abytes(seed);
|
||||
if (!seed || seed.length === 0)
|
||||
throw new Error('entropy required');
|
||||
// Mix variable-length entropy cyclically across the whole key||nonce state, then restart the
|
||||
// keystream so buffered leftovers from the previous state are never reused.
|
||||
for (let i = 0; i < seed.length; i++)
|
||||
this.state[i % this.state.length] ^= seed[i];
|
||||
this.ctr = 0;
|
||||
this.pos = this.blockLen;
|
||||
}
|
||||
addEntropy(seed) {
|
||||
// Reject empty entropy before re-keying, otherwise a throwing call would still advance state.
|
||||
abytes(seed);
|
||||
if (seed.length === 0)
|
||||
throw new Error('entropy required');
|
||||
// Re-key from the current stream first, then mix external entropy into the fresh key||nonce
|
||||
// state through reseed() so stale buffered bytes are discarded.
|
||||
this.state.set(this.randomBytes(this.state.length));
|
||||
this.reseed(seed);
|
||||
}
|
||||
randomBytes(len) {
|
||||
anumber(len);
|
||||
if (len === 0)
|
||||
return new Uint8Array(0);
|
||||
const avail = this.pos < this.blockLen ? this.blockLen - this.pos : 0;
|
||||
const blocks = Math.ceil(Math.max(0, len - avail) / this.blockLen);
|
||||
// Preflight overflow so failed reads don't partially consume keystream
|
||||
// and leave the PRG repeating blocks.
|
||||
if (blocks > 0 && this.ctr > MAX_COUNTER - blocks)
|
||||
throw new Error('arx: counter overflow');
|
||||
const out = new Uint8Array(len);
|
||||
let outPos = 0;
|
||||
// `out` starts zero-filled, and `buf.fill(0)` below does the same for leftovers: XOR-stream
|
||||
// ciphers then emit raw keystream bytes directly into those buffers.
|
||||
// Serve buffered leftovers first so split reads stay identical to one larger read.
|
||||
if (this.pos < this.blockLen) {
|
||||
const take = Math.min(len, this.blockLen - this.pos);
|
||||
out.set(this.buf.subarray(this.pos, this.pos + take), 0);
|
||||
this.pos += take;
|
||||
outPos += take;
|
||||
if (outPos === len)
|
||||
return out; // fast path
|
||||
}
|
||||
// Full blocks directly to out
|
||||
const full = Math.floor((len - outPos) / this.blockLen);
|
||||
if (full > 0) {
|
||||
const blockBytes = full * this.blockLen;
|
||||
const b = out.subarray(outPos, outPos + blockBytes);
|
||||
this.cipher(this.key, this.nonce, b, b, this.ctr);
|
||||
this.ctr += full;
|
||||
outPos += blockBytes;
|
||||
}
|
||||
// Save leftovers
|
||||
const left = len - outPos;
|
||||
if (left > 0) {
|
||||
this.buf.fill(0);
|
||||
// NOTE: cipher will handle overflow
|
||||
this.cipher(this.key, this.nonce, this.buf, this.buf, this.ctr++);
|
||||
out.set(this.buf.subarray(0, left), outPos);
|
||||
this.pos = left;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
// Clone seeds the new instance from this stream, so the source PRG advances too.
|
||||
clone() {
|
||||
return new _XorStreamPRG(this.cipher, this.blockLen, this.keyLen, this.nonceLen, this.randomBytes(this.state.length));
|
||||
}
|
||||
// Zeroes the current state and leftover buffer, but does not make the instance unusable:
|
||||
// Later reads first drain zeros from the cleared buffer and then continue
|
||||
// from zero key||nonce state.
|
||||
clean() {
|
||||
this.pos = 0;
|
||||
this.ctr = 0;
|
||||
this.buf.fill(0);
|
||||
this.state.fill(0);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Creates a PRG constructor from a stream cipher.
|
||||
* @param cipher - Stream cipher used to fill output blocks.
|
||||
* @param blockLen - Keystream block length in bytes.
|
||||
* @param keyLen - Internal key length in bytes.
|
||||
* @param nonceLen - Internal nonce length in bytes.
|
||||
* @returns PRG factory for seeded concrete `_XorStreamPRG` instances.
|
||||
* @example
|
||||
* Builds a PRG from XChaCha20 and reads bytes from a randomly seeded instance.
|
||||
* ```ts
|
||||
* import { xchacha20 } from '@noble/ciphers/chacha.js';
|
||||
* import { createPRG } from '@noble/ciphers/_arx.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const seed = randomBytes(32);
|
||||
* const init = createPRG(xchacha20, 64, 32, 24);
|
||||
* const prg = init(seed);
|
||||
* prg.randomBytes(8);
|
||||
* ```
|
||||
*/
|
||||
export const createPRG = (cipher, blockLen, keyLen, nonceLen) => {
|
||||
return ((seed = randomBytes(32)) => new _XorStreamPRG(cipher, blockLen, keyLen, nonceLen, seed));
|
||||
};
|
||||
//# sourceMappingURL=_arx.js.map
|
||||
1
node_modules/@noble/ciphers/_arx.js.map
generated
vendored
Normal file
1
node_modules/@noble/ciphers/_arx.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
73
node_modules/@noble/ciphers/_poly1305.d.ts
generated
vendored
Normal file
73
node_modules/@noble/ciphers/_poly1305.d.ts
generated
vendored
Normal file
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* Poly1305 ({@link https://cr.yp.to/mac/poly1305-20050329.pdf | PDF},
|
||||
* {@link https://en.wikipedia.org/wiki/Poly1305 | wiki})
|
||||
* is a fast and parallel secret-key message-authentication code suitable for
|
||||
* a wide variety of applications. It was standardized in
|
||||
* {@link https://www.rfc-editor.org/rfc/rfc8439 | RFC 8439} and is now used in TLS 1.3.
|
||||
*
|
||||
* Polynomial MACs are not perfect for every situation:
|
||||
* they lack Random Key Robustness: the MAC can be forged, and can't be used in PAKE schemes.
|
||||
* See {@link https://keymaterial.net/2020/09/07/invisible-salamanders-in-aes-gcm-siv/ | the invisible salamanders attack writeup}.
|
||||
* To combat invisible salamanders, `hash(key)` can be included in ciphertext,
|
||||
* however, this would violate ciphertext indistinguishability:
|
||||
* an attacker would know which key was used - so `HKDF(key, i)`
|
||||
* could be used instead.
|
||||
*
|
||||
* Check out the {@link https://cr.yp.to/mac.html | original website}.
|
||||
* Based on public-domain {@link https://github.com/floodyberry/poly1305-donna | poly1305-donna}.
|
||||
* @module
|
||||
*/
|
||||
import { type CMac, type IHash2, type TArg, type TRet } from './utils.ts';
|
||||
/**
|
||||
* Incremental Poly1305 MAC state.
|
||||
* Prefer `poly1305()` for one-shot use.
|
||||
* @param key - 32-byte Poly1305 one-time key.
|
||||
* @example
|
||||
* Feeds one chunk into an incremental Poly1305 state with a fresh one-time key.
|
||||
*
|
||||
* ```ts
|
||||
* import { Poly1305 } from '@noble/ciphers/_poly1305.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const mac = new Poly1305(key);
|
||||
* mac.update(new Uint8Array([1, 2, 3]));
|
||||
* mac.digest();
|
||||
* ```
|
||||
*/
|
||||
export declare class Poly1305 implements IHash2 {
|
||||
readonly blockLen = 16;
|
||||
readonly outputLen = 16;
|
||||
private buffer;
|
||||
private r;
|
||||
private h;
|
||||
private pad;
|
||||
private pos;
|
||||
protected finished: boolean;
|
||||
protected destroyed: boolean;
|
||||
constructor(key: TArg<Uint8Array>);
|
||||
private process;
|
||||
private finalize;
|
||||
update(data: TArg<Uint8Array>): this;
|
||||
destroy(): void;
|
||||
digestInto(out: TArg<Uint8Array>): void;
|
||||
digest(): TRet<Uint8Array>;
|
||||
}
|
||||
/** One-shot keyed hash helper with `.create()`. */
|
||||
export type CHash = CMac<Poly1305>;
|
||||
/**
|
||||
* Poly1305 MAC from RFC 8439.
|
||||
* @param msg - Message bytes to authenticate.
|
||||
* @param key - 32-byte Poly1305 one-time key.
|
||||
* @returns 16-byte authentication tag.
|
||||
* @example
|
||||
* Authenticates one message with a one-shot Poly1305 call and a fresh key.
|
||||
*
|
||||
* ```ts
|
||||
* import { poly1305 } from '@noble/ciphers/_poly1305.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* poly1305(new Uint8Array(), key);
|
||||
* ```
|
||||
*/
|
||||
export declare const poly1305: TRet<CHash>;
|
||||
//# sourceMappingURL=_poly1305.d.ts.map
|
||||
1
node_modules/@noble/ciphers/_poly1305.d.ts.map
generated
vendored
Normal file
1
node_modules/@noble/ciphers/_poly1305.d.ts.map
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"_poly1305.d.ts","sourceRoot":"","sources":["src/_poly1305.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,EAGe,KAAK,IAAI,EAAE,KAAK,MAAM,EAAE,KAAK,IAAI,EAAE,KAAK,IAAI,EACjE,MAAM,YAAY,CAAC;AA2DpB;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,QAAS,YAAW,MAAM;IACrC,QAAQ,CAAC,QAAQ,MAAM;IACvB,QAAQ,CAAC,SAAS,MAAM;IACxB,OAAO,CAAC,MAAM,CAAsB;IACpC,OAAO,CAAC,CAAC,CAAuB;IAChC,OAAO,CAAC,CAAC,CAAuB;IAChC,OAAO,CAAC,GAAG,CAAsB;IACjC,OAAO,CAAC,GAAG,CAAK;IAChB,SAAS,CAAC,QAAQ,UAAS;IAC3B,SAAS,CAAC,SAAS,UAAS;gBAGhB,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC;IA4BjC,OAAO,CAAC,OAAO;IA+Hf,OAAO,CAAC,QAAQ;IAmDhB,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI;IAwBpC,OAAO,IAAI,IAAI;IAKf,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI;IAqBvC,MAAM,IAAI,IAAI,CAAC,UAAU,CAAC;CAQ3B;AAED,mDAAmD;AACnD,MAAM,MAAM,KAAK,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC;AAEnC;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,QAAQ,EAAE,IAAI,CAAC,KAAK,CAGhC,CAAC"}
|
||||
364
node_modules/@noble/ciphers/_poly1305.js
generated
vendored
Normal file
364
node_modules/@noble/ciphers/_poly1305.js
generated
vendored
Normal file
@@ -0,0 +1,364 @@
|
||||
/**
|
||||
* Poly1305 ({@link https://cr.yp.to/mac/poly1305-20050329.pdf | PDF},
|
||||
* {@link https://en.wikipedia.org/wiki/Poly1305 | wiki})
|
||||
* is a fast and parallel secret-key message-authentication code suitable for
|
||||
* a wide variety of applications. It was standardized in
|
||||
* {@link https://www.rfc-editor.org/rfc/rfc8439 | RFC 8439} and is now used in TLS 1.3.
|
||||
*
|
||||
* Polynomial MACs are not perfect for every situation:
|
||||
* they lack Random Key Robustness: the MAC can be forged, and can't be used in PAKE schemes.
|
||||
* See {@link https://keymaterial.net/2020/09/07/invisible-salamanders-in-aes-gcm-siv/ | the invisible salamanders attack writeup}.
|
||||
* To combat invisible salamanders, `hash(key)` can be included in ciphertext,
|
||||
* however, this would violate ciphertext indistinguishability:
|
||||
* an attacker would know which key was used - so `HKDF(key, i)`
|
||||
* could be used instead.
|
||||
*
|
||||
* Check out the {@link https://cr.yp.to/mac.html | original website}.
|
||||
* Based on public-domain {@link https://github.com/floodyberry/poly1305-donna | poly1305-donna}.
|
||||
* @module
|
||||
*/
|
||||
// prettier-ignore
|
||||
import { abytes, aexists, aoutput, bytesToHex, clean, concatBytes, copyBytes, hexToNumber, numberToBytesBE, wrapMacConstructor } from "./utils.js";
|
||||
// Little-endian 2-byte load used by the Poly1305 limb decomposition.
|
||||
function u8to16(a, i) {
|
||||
return (a[i++] & 0xff) | ((a[i++] & 0xff) << 8);
|
||||
}
|
||||
function bytesToNumberLE(bytes) {
|
||||
return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
|
||||
}
|
||||
/** Small version of `poly1305` without loop unrolling. Unused, provided for auditability. */
|
||||
function poly1305_small(msg, key) {
|
||||
abytes(msg);
|
||||
abytes(key, 32, 'key');
|
||||
const POW_2_130_5 = BigInt(2) ** BigInt(130) - BigInt(5); // 2^130-5
|
||||
const POW_2_128_1 = BigInt(2) ** BigInt(128) - BigInt(1); // 2^128-1
|
||||
const CLAMP_R = BigInt('0x0ffffffc0ffffffc0ffffffc0fffffff');
|
||||
const r = bytesToNumberLE(key.subarray(0, 16)) & CLAMP_R;
|
||||
const s = bytesToNumberLE(key.subarray(16));
|
||||
// Process by 16 byte chunks
|
||||
let acc = BigInt(0);
|
||||
for (let i = 0; i < msg.length; i += 16) {
|
||||
const m = msg.subarray(i, i + 16);
|
||||
// RFC 8439 §2.5.1 / RFC 7539 §2.5.1 append [0x01] to each chunk before multiplying by r.
|
||||
const n = bytesToNumberLE(m) | (BigInt(1) << BigInt(8 * m.length));
|
||||
acc = ((acc + n) * r) % POW_2_130_5;
|
||||
}
|
||||
const res = (acc + s) & POW_2_128_1;
|
||||
// RFC 8439 §2.5 / RFC 7539 §2.5 serialize the low 128 bits in little-endian order.
|
||||
return numberToBytesBE(res, 16).reverse(); // LE
|
||||
}
|
||||
// Can be used to replace `computeTag` in chacha.ts. Unused, provided for auditability.
|
||||
// @ts-expect-error
|
||||
function poly1305_computeTag_small(authKey,
|
||||
// AEAD trailer must already be the 16-byte length block:
|
||||
// 8-byte little-endian AAD length || 8-byte little-endian ciphertext length.
|
||||
lengths, ciphertext, AAD) {
|
||||
// RFC 8439 §2.8.1 / RFC 7539 §2.8.1 MAC input is
|
||||
// AAD || pad16(AAD) || ciphertext || pad16(ciphertext) || lengths.
|
||||
const res = [];
|
||||
const updatePadded2 = (msg) => {
|
||||
res.push(msg);
|
||||
const leftover = msg.length % 16;
|
||||
// RFC 8439 §2.8.1 / RFC 7539 §2.8.1: pad16(x) is empty for aligned
|
||||
// inputs, else 16-(len%16) zero bytes.
|
||||
if (leftover)
|
||||
res.push(new Uint8Array(16).slice(leftover));
|
||||
};
|
||||
if (AAD)
|
||||
updatePadded2(AAD);
|
||||
updatePadded2(ciphertext);
|
||||
res.push(lengths);
|
||||
return poly1305_small(concatBytes(...res), authKey);
|
||||
}
|
||||
/**
|
||||
* Incremental Poly1305 MAC state.
|
||||
* Prefer `poly1305()` for one-shot use.
|
||||
* @param key - 32-byte Poly1305 one-time key.
|
||||
* @example
|
||||
* Feeds one chunk into an incremental Poly1305 state with a fresh one-time key.
|
||||
*
|
||||
* ```ts
|
||||
* import { Poly1305 } from '@noble/ciphers/_poly1305.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const mac = new Poly1305(key);
|
||||
* mac.update(new Uint8Array([1, 2, 3]));
|
||||
* mac.digest();
|
||||
* ```
|
||||
*/
|
||||
export class Poly1305 {
|
||||
blockLen = 16;
|
||||
outputLen = 16;
|
||||
buffer = new Uint8Array(16);
|
||||
r = new Uint16Array(10); // Allocating 1 array with .subarray() here is slower than 3
|
||||
h = new Uint16Array(10);
|
||||
pad = new Uint16Array(8);
|
||||
pos = 0;
|
||||
finished = false;
|
||||
destroyed = false;
|
||||
// Can be speed-up using BigUint64Array, at the cost of complexity
|
||||
constructor(key) {
|
||||
key = copyBytes(abytes(key, 32, 'key'));
|
||||
const t0 = u8to16(key, 0);
|
||||
const t1 = u8to16(key, 2);
|
||||
const t2 = u8to16(key, 4);
|
||||
const t3 = u8to16(key, 6);
|
||||
const t4 = u8to16(key, 8);
|
||||
const t5 = u8to16(key, 10);
|
||||
const t6 = u8to16(key, 12);
|
||||
const t7 = u8to16(key, 14);
|
||||
// RFC 8439 §2.5.1 / RFC 7539 §2.5.1 clamp r before multiplication.
|
||||
// These masks unpack that clamped value into 13-bit limbs, while pad
|
||||
// keeps the raw s half for finalize().
|
||||
// {@link https://github.com/floodyberry/poly1305-donna/blob/e6ad6e091d30d7f4ec2d4f978be1fcfcbce72781/poly1305-donna-16.h#L47 | poly1305-donna reference}
|
||||
this.r[0] = t0 & 0x1fff;
|
||||
this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;
|
||||
this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;
|
||||
this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;
|
||||
this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;
|
||||
this.r[5] = (t4 >>> 1) & 0x1ffe;
|
||||
this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;
|
||||
this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;
|
||||
this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;
|
||||
this.r[9] = (t7 >>> 5) & 0x007f;
|
||||
for (let i = 0; i < 8; i++)
|
||||
this.pad[i] = u8to16(key, 16 + 2 * i);
|
||||
}
|
||||
process(data, offset, isLast = false) {
|
||||
// RFC 8439 §2.5 / §2.5.1 and RFC 7539 §2.5 / §2.5.1 add an extra high
|
||||
// bit to every full 16-byte block. The final partial block gets its
|
||||
// explicit `1` byte during digestInto(), so `hibit` stays zero there.
|
||||
const hibit = isLast ? 0 : 1 << 11;
|
||||
const { h, r } = this;
|
||||
const r0 = r[0];
|
||||
const r1 = r[1];
|
||||
const r2 = r[2];
|
||||
const r3 = r[3];
|
||||
const r4 = r[4];
|
||||
const r5 = r[5];
|
||||
const r6 = r[6];
|
||||
const r7 = r[7];
|
||||
const r8 = r[8];
|
||||
const r9 = r[9];
|
||||
const t0 = u8to16(data, offset + 0);
|
||||
const t1 = u8to16(data, offset + 2);
|
||||
const t2 = u8to16(data, offset + 4);
|
||||
const t3 = u8to16(data, offset + 6);
|
||||
const t4 = u8to16(data, offset + 8);
|
||||
const t5 = u8to16(data, offset + 10);
|
||||
const t6 = u8to16(data, offset + 12);
|
||||
const t7 = u8to16(data, offset + 14);
|
||||
let h0 = h[0] + (t0 & 0x1fff);
|
||||
let h1 = h[1] + (((t0 >>> 13) | (t1 << 3)) & 0x1fff);
|
||||
let h2 = h[2] + (((t1 >>> 10) | (t2 << 6)) & 0x1fff);
|
||||
let h3 = h[3] + (((t2 >>> 7) | (t3 << 9)) & 0x1fff);
|
||||
let h4 = h[4] + (((t3 >>> 4) | (t4 << 12)) & 0x1fff);
|
||||
let h5 = h[5] + ((t4 >>> 1) & 0x1fff);
|
||||
let h6 = h[6] + (((t4 >>> 14) | (t5 << 2)) & 0x1fff);
|
||||
let h7 = h[7] + (((t5 >>> 11) | (t6 << 5)) & 0x1fff);
|
||||
let h8 = h[8] + (((t6 >>> 8) | (t7 << 8)) & 0x1fff);
|
||||
let h9 = h[9] + ((t7 >>> 5) | hibit);
|
||||
let c = 0;
|
||||
let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) + h4 * (5 * r6);
|
||||
c = d0 >>> 13;
|
||||
d0 &= 0x1fff;
|
||||
d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) + h9 * (5 * r1);
|
||||
c += d0 >>> 13;
|
||||
d0 &= 0x1fff;
|
||||
let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) + h4 * (5 * r7);
|
||||
c = d1 >>> 13;
|
||||
d1 &= 0x1fff;
|
||||
d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) + h9 * (5 * r2);
|
||||
c += d1 >>> 13;
|
||||
d1 &= 0x1fff;
|
||||
let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8);
|
||||
c = d2 >>> 13;
|
||||
d2 &= 0x1fff;
|
||||
d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) + h9 * (5 * r3);
|
||||
c += d2 >>> 13;
|
||||
d2 &= 0x1fff;
|
||||
let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9);
|
||||
c = d3 >>> 13;
|
||||
d3 &= 0x1fff;
|
||||
d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) + h9 * (5 * r4);
|
||||
c += d3 >>> 13;
|
||||
d3 &= 0x1fff;
|
||||
let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0;
|
||||
c = d4 >>> 13;
|
||||
d4 &= 0x1fff;
|
||||
d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r5);
|
||||
c += d4 >>> 13;
|
||||
d4 &= 0x1fff;
|
||||
let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1;
|
||||
c = d5 >>> 13;
|
||||
d5 &= 0x1fff;
|
||||
d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6);
|
||||
c += d5 >>> 13;
|
||||
d5 &= 0x1fff;
|
||||
let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2;
|
||||
c = d6 >>> 13;
|
||||
d6 &= 0x1fff;
|
||||
d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7);
|
||||
c += d6 >>> 13;
|
||||
d6 &= 0x1fff;
|
||||
let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3;
|
||||
c = d7 >>> 13;
|
||||
d7 &= 0x1fff;
|
||||
d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8);
|
||||
c += d7 >>> 13;
|
||||
d7 &= 0x1fff;
|
||||
let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4;
|
||||
c = d8 >>> 13;
|
||||
d8 &= 0x1fff;
|
||||
d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9);
|
||||
c += d8 >>> 13;
|
||||
d8 &= 0x1fff;
|
||||
let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5;
|
||||
c = d9 >>> 13;
|
||||
d9 &= 0x1fff;
|
||||
d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0;
|
||||
c += d9 >>> 13;
|
||||
d9 &= 0x1fff;
|
||||
c = ((c << 2) + c) | 0;
|
||||
c = (c + d0) | 0;
|
||||
d0 = c & 0x1fff;
|
||||
c = c >>> 13;
|
||||
d1 += c;
|
||||
h[0] = d0;
|
||||
h[1] = d1;
|
||||
h[2] = d2;
|
||||
h[3] = d3;
|
||||
h[4] = d4;
|
||||
h[5] = d5;
|
||||
h[6] = d6;
|
||||
h[7] = d7;
|
||||
h[8] = d8;
|
||||
h[9] = d9;
|
||||
}
|
||||
finalize() {
|
||||
const { h, pad } = this;
|
||||
const g = new Uint16Array(10);
|
||||
let c = h[1] >>> 13;
|
||||
h[1] &= 0x1fff;
|
||||
for (let i = 2; i < 10; i++) {
|
||||
h[i] += c;
|
||||
c = h[i] >>> 13;
|
||||
h[i] &= 0x1fff;
|
||||
}
|
||||
h[0] += c * 5;
|
||||
c = h[0] >>> 13;
|
||||
h[0] &= 0x1fff;
|
||||
h[1] += c;
|
||||
c = h[1] >>> 13;
|
||||
h[1] &= 0x1fff;
|
||||
h[2] += c;
|
||||
// RFC 8439 §2.5 / RFC 7539 §2.5 reduce modulo 2^130-5 before repacking
|
||||
// to 16-bit words and adding the raw s half.
|
||||
g[0] = h[0] + 5;
|
||||
c = g[0] >>> 13;
|
||||
g[0] &= 0x1fff;
|
||||
for (let i = 1; i < 10; i++) {
|
||||
g[i] = h[i] + c;
|
||||
c = g[i] >>> 13;
|
||||
g[i] &= 0x1fff;
|
||||
}
|
||||
g[9] -= 1 << 13;
|
||||
let mask = (c ^ 1) - 1;
|
||||
for (let i = 0; i < 10; i++)
|
||||
g[i] &= mask;
|
||||
mask = ~mask;
|
||||
for (let i = 0; i < 10; i++)
|
||||
h[i] = (h[i] & mask) | g[i];
|
||||
h[0] = (h[0] | (h[1] << 13)) & 0xffff;
|
||||
h[1] = ((h[1] >>> 3) | (h[2] << 10)) & 0xffff;
|
||||
h[2] = ((h[2] >>> 6) | (h[3] << 7)) & 0xffff;
|
||||
h[3] = ((h[3] >>> 9) | (h[4] << 4)) & 0xffff;
|
||||
h[4] = ((h[4] >>> 12) | (h[5] << 1) | (h[6] << 14)) & 0xffff;
|
||||
h[5] = ((h[6] >>> 2) | (h[7] << 11)) & 0xffff;
|
||||
h[6] = ((h[7] >>> 5) | (h[8] << 8)) & 0xffff;
|
||||
h[7] = ((h[8] >>> 8) | (h[9] << 5)) & 0xffff;
|
||||
let f = h[0] + pad[0];
|
||||
h[0] = f & 0xffff;
|
||||
for (let i = 1; i < 8; i++) {
|
||||
f = (((h[i] + pad[i]) | 0) + (f >>> 16)) | 0;
|
||||
h[i] = f & 0xffff;
|
||||
}
|
||||
clean(g);
|
||||
}
|
||||
update(data) {
|
||||
aexists(this);
|
||||
abytes(data);
|
||||
data = copyBytes(data);
|
||||
const { buffer, blockLen } = this;
|
||||
const len = data.length;
|
||||
for (let pos = 0; pos < len;) {
|
||||
const take = Math.min(blockLen - this.pos, len - pos);
|
||||
// Fast path: we have at least one block in input
|
||||
if (take === blockLen) {
|
||||
for (; blockLen <= len - pos; pos += blockLen)
|
||||
this.process(data, pos);
|
||||
continue;
|
||||
}
|
||||
buffer.set(data.subarray(pos, pos + take), this.pos);
|
||||
this.pos += take;
|
||||
pos += take;
|
||||
if (this.pos === blockLen) {
|
||||
this.process(buffer, 0, false);
|
||||
this.pos = 0;
|
||||
}
|
||||
}
|
||||
return this;
|
||||
}
|
||||
destroy() {
|
||||
// `aexists(this)` guards update/digest paths, so destroy must mark the instance unusable too.
|
||||
this.destroyed = true;
|
||||
clean(this.h, this.r, this.buffer, this.pad);
|
||||
}
|
||||
digestInto(out) {
|
||||
aexists(this);
|
||||
aoutput(out, this);
|
||||
this.finished = true;
|
||||
const { buffer, h } = this;
|
||||
let { pos } = this;
|
||||
if (pos) {
|
||||
// RFC 8439 §2.5 / RFC 7539 §2.5: the final short block appends a
|
||||
// single `0x01` byte and zero-fills the remaining bytes before the
|
||||
// last multiplication step.
|
||||
buffer[pos++] = 1;
|
||||
for (; pos < 16; pos++)
|
||||
buffer[pos] = 0;
|
||||
this.process(buffer, 0, true);
|
||||
}
|
||||
this.finalize();
|
||||
let opos = 0;
|
||||
for (let i = 0; i < 8; i++) {
|
||||
out[opos++] = h[i] >>> 0;
|
||||
out[opos++] = h[i] >>> 8;
|
||||
}
|
||||
}
|
||||
digest() {
|
||||
const { buffer, outputLen } = this;
|
||||
this.digestInto(buffer);
|
||||
// Copy out before destroy() zeroes the internal buffer.
|
||||
const res = buffer.slice(0, outputLen);
|
||||
this.destroy();
|
||||
return res;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Poly1305 MAC from RFC 8439.
|
||||
* @param msg - Message bytes to authenticate.
|
||||
* @param key - 32-byte Poly1305 one-time key.
|
||||
* @returns 16-byte authentication tag.
|
||||
* @example
|
||||
* Authenticates one message with a one-shot Poly1305 call and a fresh key.
|
||||
*
|
||||
* ```ts
|
||||
* import { poly1305 } from '@noble/ciphers/_poly1305.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* poly1305(new Uint8Array(), key);
|
||||
* ```
|
||||
*/
|
||||
export const poly1305 = /* @__PURE__ */ wrapMacConstructor(32, (key) => new Poly1305(key));
|
||||
//# sourceMappingURL=_poly1305.js.map
|
||||
1
node_modules/@noble/ciphers/_poly1305.js.map
generated
vendored
Normal file
1
node_modules/@noble/ciphers/_poly1305.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
121
node_modules/@noble/ciphers/_polyval.d.ts
generated
vendored
Normal file
121
node_modules/@noble/ciphers/_polyval.d.ts
generated
vendored
Normal file
@@ -0,0 +1,121 @@
|
||||
/**
|
||||
* GHash from AES-GCM and its little-endian "mirror image" Polyval from AES-SIV.
|
||||
*
|
||||
* Implemented in terms of GHash with conversion function for keys
|
||||
* GCM GHASH from
|
||||
* {@link https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf | NIST SP800-38d},
|
||||
* SIV from
|
||||
* {@link https://www.rfc-editor.org/rfc/rfc8452 | RFC 8452}.
|
||||
*
|
||||
* GHASH modulo: x^128 + x^7 + x^2 + x + 1
|
||||
* POLYVAL modulo: x^128 + x^127 + x^126 + x^121 + 1
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import { type CMac, type IHash2, type TArg, type TRet } from './utils.ts';
|
||||
/**
|
||||
* `mulX_GHASH(ByteReverse(H))` from RFC 8452 Appendix A.
|
||||
* @param k mutated in place
|
||||
*/
|
||||
export declare function _toGHASHKey(k: TArg<Uint8Array>): TRet<Uint8Array>;
|
||||
type Value = {
|
||||
s0: number;
|
||||
s1: number;
|
||||
s2: number;
|
||||
s3: number;
|
||||
};
|
||||
/**
|
||||
* Incremental GHASH state for AES-GCM.
|
||||
* @param key - 16-byte GHASH key.
|
||||
* @param expectedLength - Expected message length for table sizing.
|
||||
* Chunking is segment-based, not hash-streaming: every `update()` call is zero-padded
|
||||
* to the next 16-byte boundary before it is absorbed. This matches the internal AES/GCM
|
||||
* use where AAD, payload, and length block are separate padded segments.
|
||||
* @example
|
||||
* Feeds one ciphertext block into an incremental GHASH state with a fresh hash key.
|
||||
*
|
||||
* ```ts
|
||||
* import { GHASH } from '@noble/ciphers/_polyval.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const mac = new GHASH(key);
|
||||
* mac.update(new Uint8Array(16));
|
||||
* mac.digest();
|
||||
* ```
|
||||
*/
|
||||
export declare class GHASH implements IHash2 {
|
||||
readonly blockLen: number;
|
||||
readonly outputLen: number;
|
||||
protected s0: number;
|
||||
protected s1: number;
|
||||
protected s2: number;
|
||||
protected s3: number;
|
||||
protected finished: boolean;
|
||||
protected destroyed: boolean;
|
||||
protected t: Value[];
|
||||
private W;
|
||||
private windowSize;
|
||||
constructor(key: TArg<Uint8Array>, expectedLength?: number);
|
||||
protected _updateBlock(s0: number, s1: number, s2: number, s3: number): void;
|
||||
update(data: TArg<Uint8Array>): this;
|
||||
destroy(): void;
|
||||
digestInto(out: TArg<Uint8Array>): void;
|
||||
digest(): TRet<Uint8Array>;
|
||||
}
|
||||
/**
|
||||
* Incremental POLYVAL state for AES-SIV.
|
||||
* @param key - 16-byte POLYVAL key.
|
||||
* @param expectedLength - Expected message length for table sizing.
|
||||
* Inherits GHASH's segment-padded `update()` behavior: each call is padded
|
||||
* independently to a 16-byte boundary before absorption.
|
||||
* @example
|
||||
* Feeds one block into an incremental POLYVAL state with a fresh hash key.
|
||||
*
|
||||
* ```ts
|
||||
* import { Polyval } from '@noble/ciphers/_polyval.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const mac = new Polyval(key);
|
||||
* mac.update(new Uint8Array(16));
|
||||
* mac.digest();
|
||||
* ```
|
||||
*/
|
||||
export declare class Polyval extends GHASH {
|
||||
constructor(key: TArg<Uint8Array>, expectedLength?: number);
|
||||
update(data: TArg<Uint8Array>): this;
|
||||
digestInto(out: TArg<Uint8Array>): void;
|
||||
}
|
||||
/**
|
||||
* GHash MAC for AES-GCM.
|
||||
* @param msg - Message bytes to authenticate.
|
||||
* @param key - 16-byte GHASH key.
|
||||
* @returns 16-byte authentication tag.
|
||||
* @example
|
||||
* Authenticates a short message with GHASH and a fresh hash key.
|
||||
*
|
||||
* ```ts
|
||||
* import { ghash } from '@noble/ciphers/_polyval.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* ghash(new Uint8Array(), key);
|
||||
* ```
|
||||
*/
|
||||
export declare const ghash: TRet<CMac<GHASH, [expectedLength?: number]>>;
|
||||
/**
|
||||
* POLYVAL MAC for AES-SIV.
|
||||
* @param msg - Message bytes to authenticate.
|
||||
* @param key - 16-byte POLYVAL key.
|
||||
* @returns 16-byte authentication tag.
|
||||
* @example
|
||||
* Authenticates a short message with POLYVAL and a fresh hash key.
|
||||
*
|
||||
* ```ts
|
||||
* import { polyval } from '@noble/ciphers/_polyval.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* polyval(new Uint8Array(), key);
|
||||
* ```
|
||||
*/
|
||||
export declare const polyval: TRet<CMac<Polyval, [expectedLength?: number]>>;
|
||||
export {};
|
||||
//# sourceMappingURL=_polyval.d.ts.map
|
||||
1
node_modules/@noble/ciphers/_polyval.d.ts.map
generated
vendored
Normal file
1
node_modules/@noble/ciphers/_polyval.d.ts.map
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"_polyval.d.ts","sourceRoot":"","sources":["src/_polyval.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,OAAO,EAWL,KAAK,IAAI,EACT,KAAK,MAAM,EACX,KAAK,IAAI,EACT,KAAK,IAAI,EACV,MAAM,YAAY,CAAC;AAuCpB;;;GAGG;AACH,wBAAgB,WAAW,CAAC,CAAC,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI,CAAC,UAAU,CAAC,CAcjE;AAED,KAAK,KAAK,GAAG;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAA;CAAE,CAAC;AAUhE;;;;;;;;;;;;;;;;;;GAkBG;AACH,qBAAa,KAAM,YAAW,MAAM;IAClC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAc;IACvC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAc;IACxC,SAAS,CAAC,EAAE,SAAK;IACjB,SAAS,CAAC,EAAE,SAAK;IACjB,SAAS,CAAC,EAAE,SAAK;IACjB,SAAS,CAAC,EAAE,SAAK;IACjB,SAAS,CAAC,QAAQ,UAAS;IAC3B,SAAS,CAAC,SAAS,UAAS;IAC5B,SAAS,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC;IACrB,OAAO,CAAC,CAAC,CAAS;IAClB,OAAO,CAAC,UAAU,CAAS;gBAEf,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,cAAc,CAAC,EAAE,MAAM;IAuC1D,SAAS,CAAC,YAAY,CAAC,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,IAAI;IA0B5E,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI;IA6BpC,OAAO,IAAI,IAAI;IAWf,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI;IAiBvC,MAAM,IAAI,IAAI,CAAC,UAAU,CAAC;CAO3B;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,qBAAa,OAAQ,SAAQ,KAAK;gBACpB,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,cAAc,CAAC,EAAE,MAAM;IAS1D,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI;IA6BpC,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI;CAkBxC;AAED;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,KAAK,EAAE,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC,cAAc,CAAC,EAAE,MAAM,CAAC,CAAC,CAK5D,CAAC;AAEJ;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,OAAO,EAAE,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC,cAAc,CAAC,EAAE,MAAM,CAAC,CAAC,CAKhE,CAAC"}
|
||||
330
node_modules/@noble/ciphers/_polyval.js
generated
vendored
Normal file
330
node_modules/@noble/ciphers/_polyval.js
generated
vendored
Normal file
@@ -0,0 +1,330 @@
|
||||
/**
|
||||
* GHash from AES-GCM and its little-endian "mirror image" Polyval from AES-SIV.
|
||||
*
|
||||
* Implemented in terms of GHash with conversion function for keys
|
||||
* GCM GHASH from
|
||||
* {@link https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf | NIST SP800-38d},
|
||||
* SIV from
|
||||
* {@link https://www.rfc-editor.org/rfc/rfc8452 | RFC 8452}.
|
||||
*
|
||||
* GHASH modulo: x^128 + x^7 + x^2 + x + 1
|
||||
* POLYVAL modulo: x^128 + x^127 + x^126 + x^121 + 1
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import { abytes, aexists, aoutput, clean, copyBytes, createView, swap32IfBE, swap8IfBE, u32, wrapMacConstructor, } from "./utils.js";
|
||||
const BLOCK_SIZE = 16;
|
||||
// TODO: rewrite
|
||||
// temporary padding buffer
|
||||
// ZEROS32 aliases these bytes, so clean(ZEROS32) also resets this shared tail-padding scratch.
|
||||
const ZEROS16 = /* @__PURE__ */ new Uint8Array(16);
|
||||
const ZEROS32 = /* @__PURE__ */ u32(ZEROS16);
|
||||
// GHASH reduces modulo x^128 + x^7 + x^2 + x + 1, so the low-degree terms
|
||||
// x^7 + x^2 + x + 1 become bits `11100001` = 0xe1 in R = 0xe1 || 0^120.
|
||||
const POLY = 0xe1;
|
||||
// v = 2*v % POLY
|
||||
// NOTE: because x + x = 0 (add/sub is same), mul2(x) != x+x
|
||||
// Montgomery ladder can multiply any field element with this doubling step;
|
||||
// addition stays simple xor.
|
||||
const mul2 = (s0, s1, s2, s3) => {
|
||||
const hiBit = s3 & 1;
|
||||
return {
|
||||
s3: (s2 << 31) | (s3 >>> 1),
|
||||
s2: (s1 << 31) | (s2 >>> 1),
|
||||
s1: (s0 << 31) | (s1 >>> 1),
|
||||
// NIST SP 800-38D §6.3 applies `V >> 1` and XORs R on carry. In this
|
||||
// 4x32-bit split, R = 0xe1 || 0^120 lives in the top byte of s0.
|
||||
s0: (s0 >>> 1) ^ ((POLY << 24) & -(hiBit & 1)), // reduce % poly
|
||||
};
|
||||
};
|
||||
// Per-word part of RFC 8452 `ByteReverse`; callers also reverse the 32-bit word order.
|
||||
const swapLE = (n) => (((n >>> 0) & 0xff) << 24) |
|
||||
(((n >>> 8) & 0xff) << 16) |
|
||||
(((n >>> 16) & 0xff) << 8) |
|
||||
((n >>> 24) & 0xff) |
|
||||
0;
|
||||
// POLYVAL first applies RFC 8452's per-word byte reversal, then re-normalizes
|
||||
// host-endian u32 loads to the little-endian word value `_updateBlock()` expects.
|
||||
const swap8IfLE = (n) => swap8IfBE(swapLE(n));
|
||||
/**
|
||||
* `mulX_GHASH(ByteReverse(H))` from RFC 8452 Appendix A.
|
||||
* @param k mutated in place
|
||||
*/
|
||||
export function _toGHASHKey(k) {
|
||||
// The input is the original POLYVAL key H; reverse() materializes
|
||||
// RFC 8452's `ByteReverse(H)` before the GHASH mulX step.
|
||||
k.reverse();
|
||||
const hiBit = k[15] & 1;
|
||||
// k >>= 1
|
||||
let carry = 0;
|
||||
for (let i = 0; i < k.length; i++) {
|
||||
const t = k[i];
|
||||
k[i] = (t >>> 1) | carry;
|
||||
carry = (t & 1) << 7;
|
||||
}
|
||||
k[0] ^= -hiBit & 0xe1; // if (hiBit) n ^= 0xe1000000000000000000000000000000;
|
||||
return k;
|
||||
}
|
||||
// Precompute-window heuristic only: larger inputs trade memory for fewer table lookups.
|
||||
// Any caller-provided length hint still collapses to one of the supported windows {2, 4, 8}.
|
||||
const estimateWindow = (bytes) => {
|
||||
if (bytes > 64 * 1024)
|
||||
return 8;
|
||||
if (bytes > 1024)
|
||||
return 4;
|
||||
return 2;
|
||||
};
|
||||
/**
|
||||
* Incremental GHASH state for AES-GCM.
|
||||
* @param key - 16-byte GHASH key.
|
||||
* @param expectedLength - Expected message length for table sizing.
|
||||
* Chunking is segment-based, not hash-streaming: every `update()` call is zero-padded
|
||||
* to the next 16-byte boundary before it is absorbed. This matches the internal AES/GCM
|
||||
* use where AAD, payload, and length block are separate padded segments.
|
||||
* @example
|
||||
* Feeds one ciphertext block into an incremental GHASH state with a fresh hash key.
|
||||
*
|
||||
* ```ts
|
||||
* import { GHASH } from '@noble/ciphers/_polyval.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const mac = new GHASH(key);
|
||||
* mac.update(new Uint8Array(16));
|
||||
* mac.digest();
|
||||
* ```
|
||||
*/
|
||||
export class GHASH {
|
||||
blockLen = BLOCK_SIZE;
|
||||
outputLen = BLOCK_SIZE;
|
||||
s0 = 0;
|
||||
s1 = 0;
|
||||
s2 = 0;
|
||||
s3 = 0;
|
||||
finished = false;
|
||||
destroyed = false;
|
||||
t;
|
||||
W;
|
||||
windowSize;
|
||||
// We select bits per window adaptively based on expectedLength
|
||||
constructor(key, expectedLength) {
|
||||
abytes(key, 16, 'key');
|
||||
key = copyBytes(key);
|
||||
const kView = createView(key);
|
||||
let k0 = kView.getUint32(0, false);
|
||||
let k1 = kView.getUint32(4, false);
|
||||
let k2 = kView.getUint32(8, false);
|
||||
let k3 = kView.getUint32(12, false);
|
||||
// generate table of doubled keys (half of montgomery ladder)
|
||||
const doubles = [];
|
||||
for (let i = 0; i < 128; i++) {
|
||||
doubles.push({ s0: swapLE(k0), s1: swapLE(k1), s2: swapLE(k2), s3: swapLE(k3) });
|
||||
({ s0: k0, s1: k1, s2: k2, s3: k3 } = mul2(k0, k1, k2, k3));
|
||||
}
|
||||
const W = estimateWindow(expectedLength || 1024);
|
||||
if (![1, 2, 4, 8].includes(W))
|
||||
throw new Error('ghash: invalid window size, expected 2, 4 or 8');
|
||||
this.W = W;
|
||||
const bits = 128; // always 128 bits;
|
||||
const windows = bits / W;
|
||||
const windowSize = (this.windowSize = 2 ** W);
|
||||
const items = [];
|
||||
// Create precompute table for window of W bits
|
||||
for (let w = 0; w < windows; w++) {
|
||||
// truth table: 00, 01, 10, 11
|
||||
for (let byte = 0; byte < windowSize; byte++) {
|
||||
// prettier-ignore
|
||||
let s0 = 0, s1 = 0, s2 = 0, s3 = 0;
|
||||
for (let j = 0; j < W; j++) {
|
||||
const bit = (byte >>> (W - j - 1)) & 1;
|
||||
if (!bit)
|
||||
continue;
|
||||
const { s0: d0, s1: d1, s2: d2, s3: d3 } = doubles[W * w + j];
|
||||
((s0 ^= d0), (s1 ^= d1), (s2 ^= d2), (s3 ^= d3));
|
||||
}
|
||||
items.push({ s0, s1, s2, s3 });
|
||||
}
|
||||
}
|
||||
this.t = items;
|
||||
}
|
||||
_updateBlock(s0, s1, s2, s3) {
|
||||
((s0 ^= this.s0), (s1 ^= this.s1), (s2 ^= this.s2), (s3 ^= this.s3));
|
||||
const { W, t, windowSize } = this;
|
||||
// prettier-ignore
|
||||
let o0 = 0, o1 = 0, o2 = 0, o3 = 0;
|
||||
const mask = (1 << W) - 1; // 2**W will kill performance.
|
||||
let w = 0;
|
||||
// NIST SP 800-38D §6.3 interprets blocks as little-endian polynomials,
|
||||
// so the lookup walk consumes each word byte-by-byte from
|
||||
// least-significant to most-significant bits.
|
||||
for (const num of [s0, s1, s2, s3]) {
|
||||
for (let bytePos = 0; bytePos < 4; bytePos++) {
|
||||
const byte = (num >>> (8 * bytePos)) & 0xff;
|
||||
for (let bitPos = 8 / W - 1; bitPos >= 0; bitPos--) {
|
||||
const bit = (byte >>> (W * bitPos)) & mask;
|
||||
const { s0: e0, s1: e1, s2: e2, s3: e3 } = t[w * windowSize + bit];
|
||||
((o0 ^= e0), (o1 ^= e1), (o2 ^= e2), (o3 ^= e3));
|
||||
w += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
this.s0 = o0;
|
||||
this.s1 = o1;
|
||||
this.s2 = o2;
|
||||
this.s3 = o3;
|
||||
}
|
||||
update(data) {
|
||||
aexists(this);
|
||||
abytes(data);
|
||||
data = copyBytes(data);
|
||||
const b32 = u32(data);
|
||||
const blocks = Math.floor(data.length / BLOCK_SIZE);
|
||||
const left = data.length % BLOCK_SIZE;
|
||||
for (let i = 0; i < blocks; i++) {
|
||||
this._updateBlock(swap8IfBE(b32[i * 4 + 0]), swap8IfBE(b32[i * 4 + 1]), swap8IfBE(b32[i * 4 + 2]), swap8IfBE(b32[i * 4 + 3]));
|
||||
}
|
||||
if (left) {
|
||||
ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));
|
||||
// Tail blocks go through the shared ZEROS32 scratch, so they need the same host-endian
|
||||
// normalization as full blocks; otherwise segmented GHASH/POLYVAL updates diverge on BE.
|
||||
this._updateBlock(swap8IfBE(ZEROS32[0]), swap8IfBE(ZEROS32[1]), swap8IfBE(ZEROS32[2]), swap8IfBE(ZEROS32[3]));
|
||||
clean(ZEROS32); // clean tmp buffer
|
||||
}
|
||||
return this;
|
||||
}
|
||||
destroy() {
|
||||
// `aexists(this)` guards update/digest paths, so destroy must mark the instance unusable too.
|
||||
this.destroyed = true;
|
||||
const { t } = this;
|
||||
// Wipe the key-derived precompute table; scalar accumulator words remain,
|
||||
// but the destroyed guard blocks further use.
|
||||
// clean precompute table
|
||||
for (const elm of t) {
|
||||
((elm.s0 = 0), (elm.s1 = 0), (elm.s2 = 0), (elm.s3 = 0));
|
||||
}
|
||||
}
|
||||
digestInto(out) {
|
||||
aexists(this);
|
||||
// `digestInto(out)` is the no-allocation fast path, so callers must pass a
|
||||
// 32-bit-aligned buffer before we reinterpret it with `u32(out)`.
|
||||
aoutput(out, this, true);
|
||||
this.finished = true;
|
||||
// NIST SP 800-38D §6.4 returns the final 128-bit block Y_m.
|
||||
// `digestInto()` follows the relaxed `aoutput()` contract, so only
|
||||
// out[0..15] may be touched.
|
||||
const { s0, s1, s2, s3 } = this;
|
||||
const o32 = u32(out);
|
||||
o32[0] = s0;
|
||||
o32[1] = s1;
|
||||
o32[2] = s2;
|
||||
o32[3] = s3;
|
||||
swap32IfBE(o32);
|
||||
}
|
||||
digest() {
|
||||
const res = new Uint8Array(BLOCK_SIZE);
|
||||
this.digestInto(res);
|
||||
// `res` is independent of internal state, so it stays valid after destroy() wipes the table.
|
||||
this.destroy();
|
||||
return res;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Incremental POLYVAL state for AES-SIV.
|
||||
* @param key - 16-byte POLYVAL key.
|
||||
* @param expectedLength - Expected message length for table sizing.
|
||||
* Inherits GHASH's segment-padded `update()` behavior: each call is padded
|
||||
* independently to a 16-byte boundary before absorption.
|
||||
* @example
|
||||
* Feeds one block into an incremental POLYVAL state with a fresh hash key.
|
||||
*
|
||||
* ```ts
|
||||
* import { Polyval } from '@noble/ciphers/_polyval.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const mac = new Polyval(key);
|
||||
* mac.update(new Uint8Array(16));
|
||||
* mac.digest();
|
||||
* ```
|
||||
*/
|
||||
export class Polyval extends GHASH {
|
||||
constructor(key, expectedLength) {
|
||||
abytes(key);
|
||||
// RFC 8452 Appendix A converts the POLYVAL key with
|
||||
// `mulX_GHASH(ByteReverse(H))`; copy first because `_toGHASHKey(...)`
|
||||
// mutates in place.
|
||||
const ghKey = _toGHASHKey(copyBytes(key));
|
||||
super(ghKey, expectedLength);
|
||||
clean(ghKey);
|
||||
}
|
||||
update(data) {
|
||||
aexists(this);
|
||||
abytes(data);
|
||||
data = copyBytes(data);
|
||||
const b32 = u32(data);
|
||||
const left = data.length % BLOCK_SIZE;
|
||||
const blocks = Math.floor(data.length / BLOCK_SIZE);
|
||||
for (let i = 0; i < blocks; i++) {
|
||||
// RFC 8452 Appendix A feeds `ByteReverse(X_i)` into GHASH, so POLYVAL
|
||||
// reverses the 32-bit word order in addition to the per-word byte swap.
|
||||
this._updateBlock(swap8IfLE(b32[i * 4 + 3]), swap8IfLE(b32[i * 4 + 2]), swap8IfLE(b32[i * 4 + 1]), swap8IfLE(b32[i * 4 + 0]));
|
||||
}
|
||||
if (left) {
|
||||
ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));
|
||||
this._updateBlock(swap8IfLE(ZEROS32[3]), swap8IfLE(ZEROS32[2]), swap8IfLE(ZEROS32[1]), swap8IfLE(ZEROS32[0]));
|
||||
clean(ZEROS32);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
digestInto(out) {
|
||||
aexists(this);
|
||||
// `digestInto(out)` is the no-allocation fast path, so callers must pass a
|
||||
// 32-bit-aligned buffer before we reinterpret the output prefix with `u32(view)`.
|
||||
aoutput(out, this, true);
|
||||
this.finished = true;
|
||||
// RFC 8452 Appendix A maps POLYVAL output back through `ByteReverse(...)`.
|
||||
// `digestInto()` follows the relaxed `aoutput()` contract, so only out[0..15] may be touched.
|
||||
const view = out.subarray(0, this.outputLen);
|
||||
const { s0, s1, s2, s3 } = this;
|
||||
const o32 = u32(view);
|
||||
o32[0] = s0;
|
||||
o32[1] = s1;
|
||||
o32[2] = s2;
|
||||
o32[3] = s3;
|
||||
swap32IfBE(o32);
|
||||
view.reverse();
|
||||
}
|
||||
}
|
||||
/**
|
||||
* GHash MAC for AES-GCM.
|
||||
* @param msg - Message bytes to authenticate.
|
||||
* @param key - 16-byte GHASH key.
|
||||
* @returns 16-byte authentication tag.
|
||||
* @example
|
||||
* Authenticates a short message with GHASH and a fresh hash key.
|
||||
*
|
||||
* ```ts
|
||||
* import { ghash } from '@noble/ciphers/_polyval.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* ghash(new Uint8Array(), key);
|
||||
* ```
|
||||
*/
|
||||
export const ghash =
|
||||
/* @__PURE__ */ wrapMacConstructor(16, (key, expectedLength) => new GHASH(key, expectedLength), (msg) => [msg.length]);
|
||||
/**
|
||||
* POLYVAL MAC for AES-SIV.
|
||||
* @param msg - Message bytes to authenticate.
|
||||
* @param key - 16-byte POLYVAL key.
|
||||
* @returns 16-byte authentication tag.
|
||||
* @example
|
||||
* Authenticates a short message with POLYVAL and a fresh hash key.
|
||||
*
|
||||
* ```ts
|
||||
* import { polyval } from '@noble/ciphers/_polyval.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* polyval(new Uint8Array(), key);
|
||||
* ```
|
||||
*/
|
||||
export const polyval =
|
||||
/* @__PURE__ */ wrapMacConstructor(16, (key, expectedLength) => new Polyval(key, expectedLength), (msg) => [msg.length]);
|
||||
//# sourceMappingURL=_polyval.js.map
|
||||
1
node_modules/@noble/ciphers/_polyval.js.map
generated
vendored
Normal file
1
node_modules/@noble/ciphers/_polyval.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
462
node_modules/@noble/ciphers/aes.d.ts
generated
vendored
Normal file
462
node_modules/@noble/ciphers/aes.d.ts
generated
vendored
Normal file
@@ -0,0 +1,462 @@
|
||||
import { type Cipher, type CipherWithOutput, type CMac, type IHash2, type PRG, type TArg, type TRet, type Uint8ArrayBuffer } from './utils.ts';
|
||||
/**
|
||||
* Increments a counter block with wrap around.
|
||||
* AES call sites here currently use the big-endian branch, but the helper supports both layouts.
|
||||
* NIST SP 800-38A Appendix B.1 and SP 800-38D §6.2 increment the
|
||||
* least-significant/rightmost bits.
|
||||
* `isLE=false` matches that standard counter-block layout, while `isLE=true`
|
||||
* is a generic extension for non-AES callers.
|
||||
* The implementation keeps a 32-bit bitwise carry path, so `carry` is capped at `0xffffff00`;
|
||||
* larger values throw instead of silently overflowing before the next-byte propagation step.
|
||||
*/
|
||||
declare const incBytes: (data: TArg<Uint8Array>, isLE: boolean, carry?: number) => void;
|
||||
/** Forward AES key expansion used across ECB/CBC/CTR/GCM/CMAC/KW-style paths. */
|
||||
declare function expandKeyLE(key: TArg<Uint8Array>): TRet<Uint32Array>;
|
||||
declare function expandKeyDecLE(key: TArg<Uint8Array>): TRet<Uint32Array>;
|
||||
declare function encrypt(xk: TArg<Uint32Array>, s0: number, s1: number, s2: number, s3: number): {
|
||||
s0: number;
|
||||
s1: number;
|
||||
s2: number;
|
||||
s3: number;
|
||||
};
|
||||
declare function decrypt(xk: TArg<Uint32Array>, s0: number, s1: number, s2: number, s3: number): {
|
||||
s0: number;
|
||||
s1: number;
|
||||
s2: number;
|
||||
s3: number;
|
||||
};
|
||||
declare function ctrCounter(xk: TArg<Uint32Array>, nonce: TArg<Uint8Array>, src: TArg<Uint8Array>, dst?: TArg<Uint8Array>): TRet<Uint8Array>;
|
||||
declare function ctr32(xk: TArg<Uint32Array>, isLE: boolean, nonce: TArg<Uint8Array>, src: TArg<Uint8Array>, dst?: TArg<Uint8Array>): TRet<Uint8Array>;
|
||||
/**
|
||||
* **CTR** (Counter Mode): turns a block cipher into a stream cipher using a
|
||||
* full 16-byte counter block.
|
||||
* Efficient and parallelizable. Requires a unique nonce per encryption. Unauthenticated: needs MAC.
|
||||
* @param key - AES key bytes.
|
||||
* @param nonce - 16-byte counter block, incremented as a full AES block.
|
||||
* @returns Cipher instance with `encrypt()` and `decrypt()`.
|
||||
* @example
|
||||
* Encrypts a short payload with a fresh AES key and counter block.
|
||||
*
|
||||
* ```ts
|
||||
* import { ctr } from '@noble/ciphers/aes.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const nonce = randomBytes(16);
|
||||
* const cipher = ctr(key, nonce);
|
||||
* cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export declare const ctr: TRet<((key: TArg<Uint8Array>, nonce: TArg<Uint8Array>) => CipherWithOutput) & {
|
||||
blockSize: number;
|
||||
nonceLength: number;
|
||||
}>;
|
||||
/** Options for ECB and CBC. */
|
||||
export type BlockOpts = {
|
||||
/** Disable the library's PKCS#7 padding/unpadding layer and require exact-block inputs. */
|
||||
disablePadding?: boolean;
|
||||
};
|
||||
/**
|
||||
* **ECB** (Electronic Codebook): Deterministic encryption; identical plaintext blocks yield
|
||||
* identical ciphertexts. Not secure due to pattern leakage.
|
||||
* See {@link https://words.filippo.io/the-ecb-penguin/ | the AES Penguin}.
|
||||
* @param key - AES key bytes.
|
||||
* @param opts - Padding options. See {@link BlockOpts}.
|
||||
* @returns Cipher instance with `encrypt()` and `decrypt()`.
|
||||
* @example
|
||||
* Shows the basic ECB encrypt call shape with a fresh key; avoid ECB in new designs.
|
||||
*
|
||||
* ```ts
|
||||
* import { ecb } from '@noble/ciphers/aes.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const cipher = ecb(key);
|
||||
* cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export declare const ecb: TRet<((key: TArg<Uint8Array>, opts?: BlockOpts) => CipherWithOutput) & {
|
||||
blockSize: number;
|
||||
}>;
|
||||
/**
|
||||
* **CBC** (Cipher Block Chaining): Each plaintext block is XORed with the
|
||||
* previous block of ciphertext before encryption.
|
||||
* Hard to use: requires proper padding and an unpredictable IV. Unauthenticated: needs MAC.
|
||||
* @param key - AES key bytes.
|
||||
* @param iv - 16-byte unpredictable initialization vector.
|
||||
* @param opts - Padding options. See {@link BlockOpts}.
|
||||
* @returns Cipher instance with `encrypt()` and `decrypt()`.
|
||||
* @example
|
||||
* Encrypts a padded message with a fresh key and 16-byte IV.
|
||||
*
|
||||
* ```ts
|
||||
* import { cbc } from '@noble/ciphers/aes.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const iv = randomBytes(16);
|
||||
* const cipher = cbc(key, iv);
|
||||
* cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export declare const cbc: TRet<((key: TArg<Uint8Array>, iv: TArg<Uint8Array>, opts?: BlockOpts) => CipherWithOutput) & {
|
||||
blockSize: number;
|
||||
nonceLength: number;
|
||||
}>;
|
||||
/**
|
||||
* CFB (CFB-128): Cipher Feedback Mode with 128-bit segments. The input for the
|
||||
* block cipher is the previous cipher output.
|
||||
* Unauthenticated: needs MAC.
|
||||
* @param key - AES key bytes.
|
||||
* @param iv - 16-byte unpredictable initialization vector.
|
||||
* @returns Cipher instance with `encrypt()` and `decrypt()`.
|
||||
* @example
|
||||
* Encrypts a short message with feedback mode and a fresh key/IV pair.
|
||||
*
|
||||
* ```ts
|
||||
* import { cfb } from '@noble/ciphers/aes.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const iv = randomBytes(16);
|
||||
* const cipher = cfb(key, iv);
|
||||
* cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export declare const cfb: TRet<((key: TArg<Uint8Array>, iv: TArg<Uint8Array>) => CipherWithOutput) & {
|
||||
blockSize: number;
|
||||
nonceLength: number;
|
||||
}>;
|
||||
/**
|
||||
* **GCM** (Galois/Counter Mode): Combines CTR mode with polynomial MAC. Efficient and widely used.
|
||||
* Not perfect:
|
||||
* a) conservative key wear-out is `2**32` (4B) msgs.
|
||||
* b) key wear-out under random nonces is even smaller: `2**23` (8M) messages for `2**-50` chance.
|
||||
* c) MAC can be forged: see Poly1305 documentation.
|
||||
* @param key - AES key bytes.
|
||||
* @param nonce - Nonce bytes (12 recommended, minimum 8; other lengths use GHASH J0 derivation).
|
||||
* @param AAD - Additional authenticated data.
|
||||
* @returns AEAD cipher instance with a fixed 16-byte tag.
|
||||
* @example
|
||||
* Encrypts and authenticates plaintext with a fresh key and 12-byte nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { gcm } from '@noble/ciphers/aes.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const nonce = randomBytes(12);
|
||||
* const cipher = gcm(key, nonce);
|
||||
* cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export declare const gcm: TRet<((key: TArg<Uint8Array>, nonce: TArg<Uint8Array>, AAD?: TArg<Uint8Array>) => Cipher) & {
|
||||
blockSize: number;
|
||||
nonceLength: number;
|
||||
tagLength: number;
|
||||
varSizeNonce: true;
|
||||
}>;
|
||||
/**
|
||||
* **SIV** (Synthetic IV): GCM with nonce-misuse resistance.
|
||||
* Repeating nonces reveal only the fact plaintexts are identical.
|
||||
* Also suffers from GCM issues: key wear-out limits & MAC forging.
|
||||
* See {@link https://www.rfc-editor.org/rfc/rfc8452 | RFC 8452}.
|
||||
* RFC 8452 defines 16-byte and 32-byte AES keys for this mode.
|
||||
* This implementation also accepts 24-byte AES-192 keys as a local
|
||||
* extension; see the inline comment next to `validateKeyLength(key)` below
|
||||
* for the exact scope note.
|
||||
* @param key - AES key bytes.
|
||||
* @param nonce - 12-byte nonce.
|
||||
* @param AAD - Additional authenticated data.
|
||||
* @returns AEAD cipher instance.
|
||||
* @example
|
||||
* Encrypts and authenticates plaintext with a fresh key and nonce, while tolerating reuse.
|
||||
*
|
||||
* ```ts
|
||||
* import { gcmsiv } from '@noble/ciphers/aes.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const nonce = randomBytes(12);
|
||||
* const cipher = gcmsiv(key, nonce);
|
||||
* cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export declare const gcmsiv: TRet<((key: TArg<Uint8Array>, nonce: TArg<Uint8Array>, AAD?: TArg<Uint8Array>) => Cipher) & {
|
||||
blockSize: number;
|
||||
nonceLength: number;
|
||||
tagLength: number;
|
||||
varSizeNonce: true;
|
||||
}>;
|
||||
declare function encryptBlock(xk: TArg<Uint32Array>, block: TArg<Uint8Array>): TRet<Uint8Array>;
|
||||
declare function decryptBlock(xk: TArg<Uint32Array>, block: TArg<Uint8Array>): TRet<Uint8Array>;
|
||||
/**
|
||||
* AES-KW (key-wrap). Injects static IV into plaintext, adds counter, encrypts 6 times.
|
||||
* Reduces block size from 16 to 8 bytes.
|
||||
* Plaintext must be a non-empty multiple of 8 bytes with minimum 16 bytes.
|
||||
* 8-byte inputs use aeskwp.
|
||||
* Wrapped ciphertext must be a multiple of 8 bytes with minimum 24 bytes.
|
||||
* For padded version, use aeskwp.
|
||||
* See {@link https://www.rfc-editor.org/rfc/rfc3394/ | RFC 3394} and
|
||||
* {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf | NIST SP 800-38F}.
|
||||
* @param kek - AES key-encryption key.
|
||||
* @returns Key-wrap cipher instance.
|
||||
* As with other `wrapCipher(...)` wrappers, `encrypt()` is single-use per
|
||||
* instance.
|
||||
* @example
|
||||
* Wraps a 128-bit content-encryption key with a fresh key-encryption key.
|
||||
*
|
||||
* ```ts
|
||||
* import { aeskw } from '@noble/ciphers/aes.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const kek = randomBytes(16);
|
||||
* const cek = randomBytes(16);
|
||||
* const wrap = aeskw(kek);
|
||||
* wrap.encrypt(cek);
|
||||
* ```
|
||||
*/
|
||||
export declare const aeskw: TRet<((kek: TArg<Uint8Array>) => Cipher) & {
|
||||
blockSize: number;
|
||||
}>;
|
||||
/**
|
||||
* AES-KW, but with padding and allows random keys.
|
||||
* Uses the RFC 5649 alternative initial value; the second u32 stores the
|
||||
* 32-bit MLI in network order.
|
||||
* Wrapped ciphertext must be at least 16 bytes; malformed lengths are
|
||||
* rejected during AIV/padding checks.
|
||||
* See {@link https://www.rfc-editor.org/rfc/rfc5649 | RFC 5649}.
|
||||
* @param kek - AES key-encryption key.
|
||||
* @returns Padded key-wrap cipher instance.
|
||||
* @example
|
||||
* Wraps a short key blob using the padded variant and a fresh key-encryption key.
|
||||
*
|
||||
* ```ts
|
||||
* import { aeskwp } from '@noble/ciphers/aes.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const kek = randomBytes(16);
|
||||
* const wrap = aeskwp(kek);
|
||||
* wrap.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export declare const aeskwp: TRet<((kek: TArg<Uint8Array>) => Cipher) & {
|
||||
blockSize: number;
|
||||
}>;
|
||||
declare class _AesCtrDRBG implements PRG {
|
||||
readonly blockLen: number;
|
||||
private key;
|
||||
private nonce;
|
||||
private state;
|
||||
private reseedCnt;
|
||||
constructor(keyLen: number, seed: TArg<Uint8Array>, personalization?: TArg<Uint8Array>);
|
||||
private update;
|
||||
addEntropy(seed: TArg<Uint8Array>, info?: TArg<Uint8Array>): void;
|
||||
randomBytes(len: number, info?: TArg<Uint8Array>): TRet<Uint8Array>;
|
||||
clean(): void;
|
||||
}
|
||||
/**
|
||||
* Factory for AES-CTR DRBG instances.
|
||||
* @param seed - Initial entropy input.
|
||||
* @param personalization - Optional personalization string mixed into the state.
|
||||
* @returns Seeded AES-CTR DRBG instance.
|
||||
*/
|
||||
export type AesCtrDrbg = (seed: TArg<Uint8Array>, personalization?: TArg<Uint8Array>) => TRet<_AesCtrDRBG>;
|
||||
/**
|
||||
* AES-CTR DRBG 128-bit - CSPRNG (cryptographically secure pseudorandom number generator).
|
||||
* It's best to limit usage to non-production, non-critical cases: for example, test-only.
|
||||
* @param seed - Initial 32-byte entropy input.
|
||||
* @param personalization - Optional personalization string.
|
||||
* @returns Seeded DRBG instance. The concrete methods also accept optional additional-input bytes.
|
||||
* @example
|
||||
* Seeds the test-only AES-CTR DRBG from fresh entropy and reads bytes from it.
|
||||
*
|
||||
* ```ts
|
||||
* import { rngAesCtrDrbg128 } from '@noble/ciphers/aes.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const seed = randomBytes(32);
|
||||
* const prg = rngAesCtrDrbg128(seed);
|
||||
* prg.randomBytes(8);
|
||||
* ```
|
||||
*/
|
||||
export declare const rngAesCtrDrbg128: TRet<AesCtrDrbg>;
|
||||
/**
|
||||
* AES-CTR DRBG 256-bit - CSPRNG (cryptographically secure pseudorandom number generator).
|
||||
* It's best to limit usage to non-production, non-critical cases: for example, test-only.
|
||||
* @param seed - Initial 48-byte entropy input.
|
||||
* @param personalization - Optional personalization string.
|
||||
* @returns Seeded DRBG instance. The concrete methods also accept optional additional-input bytes.
|
||||
* @example
|
||||
* Seeds the test-only AES-CTR DRBG from fresh entropy and reads bytes from it.
|
||||
*
|
||||
* ```ts
|
||||
* import { rngAesCtrDrbg256 } from '@noble/ciphers/aes.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const seed = randomBytes(48);
|
||||
* const prg = rngAesCtrDrbg256(seed);
|
||||
* prg.randomBytes(8);
|
||||
* ```
|
||||
*/
|
||||
export declare const rngAesCtrDrbg256: TRet<AesCtrDrbg>;
|
||||
/**
|
||||
* Left-shift by one bit and conditionally XOR with 0x87:
|
||||
* ```
|
||||
* if MSB(L) is equal to 0
|
||||
* then K1 := L << 1;
|
||||
* else K1 := (L << 1) XOR const_Rb;
|
||||
* ```
|
||||
*
|
||||
* Specs:
|
||||
* {@link https://www.rfc-editor.org/rfc/rfc4493.html#section-2.3 | RFC 4493 Section 2.3},
|
||||
* {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.3 | RFC 5297 Section 2.3}
|
||||
*
|
||||
* @returns modified `block` (for chaining)
|
||||
*/
|
||||
declare function dbl<T extends Uint8Array>(block: T): T;
|
||||
/**
|
||||
* `a XOR b`, running in-place on `a`.
|
||||
* @param a left operand and output
|
||||
* @param b right operand
|
||||
* @returns `a` (for chaining)
|
||||
*/
|
||||
declare function xorBlock<T extends TArg<Uint8Array>>(a: T, b: TArg<Uint8Array>): T;
|
||||
/**
|
||||
* xorend as defined in
|
||||
* {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.1 | RFC 5297 Section 2.1}.
|
||||
*
|
||||
* ```
|
||||
* leftmost(A, len(A)-len(B)) || (rightmost(A, len(B)) xor B)
|
||||
* ```
|
||||
*
|
||||
* Mutates `a` in place so the left prefix stays untouched and only the
|
||||
* rightmost `len(B)` bytes are xored with `b`.
|
||||
*/
|
||||
declare function xorend<T extends TArg<Uint8Array>>(a: T, b: TArg<Uint8Array>): T;
|
||||
/**
|
||||
* Internal CMAC class.
|
||||
*/
|
||||
declare class _CMAC implements IHash2 {
|
||||
readonly blockLen: number;
|
||||
readonly outputLen: number;
|
||||
private buffer;
|
||||
private pos;
|
||||
private finished;
|
||||
private destroyed;
|
||||
private k1;
|
||||
private k2;
|
||||
private x;
|
||||
private xk;
|
||||
constructor(key: TArg<Uint8Array>);
|
||||
private process;
|
||||
update(data: TArg<Uint8Array>): this;
|
||||
digestInto(out: TArg<Uint8Array>): void;
|
||||
digest(): Uint8ArrayBuffer;
|
||||
destroy(): void;
|
||||
}
|
||||
/**
|
||||
* AES-CMAC (Cipher-based Message Authentication Code).
|
||||
* Specs: {@link https://www.rfc-editor.org/rfc/rfc4493.html | RFC 4493}.
|
||||
* @param msg - Message bytes to authenticate.
|
||||
* @param key - AES key bytes.
|
||||
* @returns 16-byte authentication tag. `cmac.create(...)` follows the same incremental MAC shape as
|
||||
* the other keyed helpers in this repo, including `blockLen`,
|
||||
* `outputLen`, `digestInto()` and `destroy()`.
|
||||
* @example
|
||||
* Authenticates a message with AES-CMAC and a fresh key.
|
||||
*
|
||||
* ```ts
|
||||
* import { cmac } from '@noble/ciphers/aes.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* cmac(new Uint8Array(), key);
|
||||
* ```
|
||||
*/
|
||||
export declare const cmac: TRet<CMac<_CMAC>>;
|
||||
/**
|
||||
* S2V (Synthetic Initialization Vector) function as described in
|
||||
* {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.4 | RFC 5297 Section 2.4}.
|
||||
*
|
||||
* ```
|
||||
* S2V(K, S1, ..., Sn) {
|
||||
* if n = 0 then
|
||||
* return V = AES-CMAC(K, <one>)
|
||||
* fi
|
||||
* D = AES-CMAC(K, <zero>)
|
||||
* for i = 1 to n-1 do
|
||||
* D = dbl(D) xor AES-CMAC(K, Si)
|
||||
* done
|
||||
* if len(Sn) >= 128 then
|
||||
* T = Sn xorend D
|
||||
* else
|
||||
* T = dbl(D) xor pad(Sn)
|
||||
* fi
|
||||
* return V = AES-CMAC(K, T)
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* S2V takes a key and a vector of strings S1, S2, ..., Sn and returns a 128-bit string.
|
||||
* The S2V function is used to generate a synthetic IV for AES-SIV.
|
||||
*
|
||||
* @param key - AES key (128, 192, or 256 bits)
|
||||
* @param strings - Array of byte arrays to process
|
||||
* @returns 128-bit synthetic IV
|
||||
*/
|
||||
declare function s2v(key: TArg<Uint8Array>, strings: TArg<Uint8Array[]>): TRet<Uint8Array>;
|
||||
/**
|
||||
* Use `gcmsiv` or `aessiv`.
|
||||
* @returns Never; always throws with the migration hint.
|
||||
* @throws If called; `siv()` is a removed v1 alias. {@link Error}
|
||||
* @example
|
||||
* `siv()` was removed in v2; use `gcmsiv()` for nonce-based SIV instead.
|
||||
*
|
||||
* ```ts
|
||||
* import { gcmsiv } from '@noble/ciphers/aes.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const nonce = randomBytes(12);
|
||||
* const cipher = gcmsiv(key, nonce);
|
||||
* cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export declare const siv: () => never;
|
||||
/**
|
||||
* **SIV**: Synthetic Initialization Vector (SIV) Authenticated Encryption
|
||||
* Nonce is derived from the plaintext and AAD using the S2V function.
|
||||
* Supports at most 126 AAD components. RFC 5297 nonce-based use is expressed by
|
||||
* passing the nonce as the final AAD component before the plaintext.
|
||||
* See {@link https://datatracker.ietf.org/doc/html/rfc5297.html | RFC 5297}.
|
||||
* @param key - 32-byte, 48-byte, or 64-byte key.
|
||||
* @param AAD - Additional authenticated data chunks (up to 126).
|
||||
* @returns AEAD cipher instance.
|
||||
* @example
|
||||
* Authenticates and encrypts plaintext with a fresh key without requiring unique nonces.
|
||||
*
|
||||
* ```ts
|
||||
* import { aessiv } from '@noble/ciphers/aes.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const cipher = aessiv(key);
|
||||
* cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export declare const aessiv: TRet<((key: TArg<Uint8Array>, ...AAD: TArg<Uint8Array[]>) => Cipher) & {
|
||||
blockSize: number;
|
||||
tagLength: number;
|
||||
}>;
|
||||
/**
|
||||
* Unsafe low-level internal methods. May change at any time.
|
||||
* Callers are expected to use reviewed expanded-key outputs, pass mutable and
|
||||
* aligned 16-byte blocks where required, and treat several helpers as in-place
|
||||
* mutations of their input buffers or counters.
|
||||
*/
|
||||
export declare const unsafe: {
|
||||
expandKeyLE: typeof expandKeyLE;
|
||||
expandKeyDecLE: typeof expandKeyDecLE;
|
||||
encrypt: typeof encrypt;
|
||||
decrypt: typeof decrypt;
|
||||
encryptBlock: typeof encryptBlock;
|
||||
decryptBlock: typeof decryptBlock;
|
||||
ctrCounter: typeof ctrCounter;
|
||||
ctr32: typeof ctr32;
|
||||
dbl: typeof dbl;
|
||||
xorBlock: typeof xorBlock;
|
||||
xorend: typeof xorend;
|
||||
s2v: typeof s2v;
|
||||
};
|
||||
export declare const __TESTS: {
|
||||
incBytes: typeof incBytes;
|
||||
};
|
||||
export {};
|
||||
//# sourceMappingURL=aes.d.ts.map
|
||||
1
node_modules/@noble/ciphers/aes.d.ts.map
generated
vendored
Normal file
1
node_modules/@noble/ciphers/aes.d.ts.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
1765
node_modules/@noble/ciphers/aes.js
generated
vendored
Normal file
1765
node_modules/@noble/ciphers/aes.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
1
node_modules/@noble/ciphers/aes.js.map
generated
vendored
Normal file
1
node_modules/@noble/ciphers/aes.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
249
node_modules/@noble/ciphers/chacha.d.ts
generated
vendored
Normal file
249
node_modules/@noble/ciphers/chacha.d.ts
generated
vendored
Normal file
@@ -0,0 +1,249 @@
|
||||
/**
|
||||
* ChaCha stream cipher, released
|
||||
* in 2008. Developed after Salsa20, ChaCha aims to increase diffusion per round.
|
||||
* It was standardized in
|
||||
* {@link https://www.rfc-editor.org/rfc/rfc8439 | RFC 8439} and
|
||||
* is now used in TLS 1.3.
|
||||
*
|
||||
* {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | XChaCha20}
|
||||
* extended-nonce variant is also provided. Similar to XSalsa, it's safe to use with
|
||||
* randomly-generated nonces.
|
||||
*
|
||||
* Check out
|
||||
* {@link http://cr.yp.to/chacha/chacha-20080128.pdf | PDF},
|
||||
* {@link https://en.wikipedia.org/wiki/Salsa20 | wiki}, and
|
||||
* {@link https://cr.yp.to/chacha.html | website}.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import { type XorPRG } from './_arx.ts';
|
||||
import { type ARXCipher, type CipherWithOutput, type TArg, type TRet, type XorStream } from './utils.ts';
|
||||
/** Identical to `chachaCore`. Reached only through the test-only `__TESTS` export. */
|
||||
declare const chachaCore_small: typeof chachaCore;
|
||||
/** RFC 8439 §2.3 block core for `state = constants | key | counter | nonce`. */
|
||||
declare function chachaCore(s: TArg<Uint32Array>, k: TArg<Uint32Array>, n: TArg<Uint32Array>, out: TArg<Uint32Array>, cnt: number, rounds?: number): void;
|
||||
/**
|
||||
* hchacha hashes key and nonce into key' and nonce' for xchacha20.
|
||||
* Algorithmically identical to `hchacha_small`, but this exported path
|
||||
* normalizes word order on big-endian hosts.
|
||||
* Need to find a way to merge it with `chachaCore` without 25% performance hit.
|
||||
* @param s - Sigma constants as 32-bit words.
|
||||
* @param k - Key words.
|
||||
* @param i - Nonce-prefix words.
|
||||
* @param out - Output buffer for the derived subkey.
|
||||
* @example
|
||||
* Derives the XChaCha subkey from sigma, key, and nonce-prefix words.
|
||||
*
|
||||
* ```ts
|
||||
* const sigma = new Uint32Array(4);
|
||||
* const key = new Uint32Array(8);
|
||||
* const nonce = new Uint32Array(4);
|
||||
* const out = new Uint32Array(8);
|
||||
* hchacha(sigma, key, nonce, out);
|
||||
* ```
|
||||
*/
|
||||
export declare function hchacha(s: TArg<Uint32Array>, k: TArg<Uint32Array>, i: TArg<Uint32Array>, out: TArg<Uint32Array>): void;
|
||||
/**
|
||||
* Original, non-RFC chacha20 from DJB. 8-byte nonce, 8-byte counter.
|
||||
* The nonce/counter layout still reserves 8 counter bytes internally, but the shared public
|
||||
* `counter` argument follows noble's strict non-wrapping 32-bit policy. See `src/_arx.ts`
|
||||
* near `MAX_COUNTER` for the full counter-policy rationale.
|
||||
* @param key - 16-byte or 32-byte key.
|
||||
* @param nonce - 8-byte nonce.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Initial block counter.
|
||||
* @returns Encrypted or decrypted bytes.
|
||||
* @example
|
||||
* Encrypts bytes with the original 8-byte-nonce ChaCha variant and a fresh key/nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { chacha20orig } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(8);
|
||||
* chacha20orig(key, nonce, new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export declare const chacha20orig: TRet<XorStream>;
|
||||
/**
|
||||
* ChaCha stream cipher. Conforms to RFC 8439 (IETF, TLS). 12-byte nonce, 4-byte counter.
|
||||
* With smaller nonce, it's not safe to make it random (CSPRNG), due to collision chance.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 12-byte nonce.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Initial block counter.
|
||||
* @returns Encrypted or decrypted bytes.
|
||||
* @example
|
||||
* Encrypts bytes with the RFC 8439 ChaCha20 stream cipher and a fresh key/nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { chacha20 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(12);
|
||||
* chacha20(key, nonce, new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export declare const chacha20: TRet<XorStream>;
|
||||
/**
|
||||
* XChaCha eXtended-nonce ChaCha. With 24-byte nonce, it's safe to make it random (CSPRNG).
|
||||
* See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | the IRTF draft}.
|
||||
* The nonce/counter layout still reserves 8 counter bytes internally, but the shared public
|
||||
* `counter` argument follows noble's strict non-wrapping 32-bit policy. See `src/_arx.ts`
|
||||
* near `MAX_COUNTER` for the full counter-policy rationale.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 24-byte extended nonce.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Initial block counter.
|
||||
* @returns Encrypted or decrypted bytes.
|
||||
* @example
|
||||
* Encrypts bytes with XChaCha20 using a fresh key and random 24-byte nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { xchacha20 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(24);
|
||||
* xchacha20(key, nonce, new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export declare const xchacha20: TRet<XorStream>;
|
||||
/**
|
||||
* Reduced 8-round chacha, described in original paper.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 12-byte nonce.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Initial block counter.
|
||||
* @returns Encrypted or decrypted bytes.
|
||||
* @example
|
||||
* Uses the reduced 8-round variant for non-critical workloads with a fresh key/nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { chacha8 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(12);
|
||||
* chacha8(key, nonce, new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export declare const chacha8: TRet<XorStream>;
|
||||
/**
|
||||
* Reduced 12-round chacha, described in original paper.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 12-byte nonce.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Initial block counter.
|
||||
* @returns Encrypted or decrypted bytes.
|
||||
* @example
|
||||
* Uses the reduced 12-round variant for non-critical workloads with a fresh key/nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { chacha12 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(12);
|
||||
* chacha12(key, nonce, new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export declare const chacha12: TRet<XorStream>;
|
||||
export declare const __TESTS: {
|
||||
chachaCore_small: typeof chachaCore_small;
|
||||
chachaCore: typeof chachaCore;
|
||||
};
|
||||
/**
|
||||
* AEAD algorithm from RFC 8439.
|
||||
* Salsa20 and chacha (RFC 8439) use poly1305 differently.
|
||||
* We could have composed them, but it's hard because of authKey:
|
||||
* In salsa20, authKey changes position in salsa stream.
|
||||
* In chacha, authKey can't be computed inside computeTag, it modifies the counter.
|
||||
*/
|
||||
export declare const _poly1305_aead: (xorStream: TArg<XorStream>) => (key: TArg<Uint8Array>, nonce: TArg<Uint8Array>, AAD?: TArg<Uint8Array>) => CipherWithOutput;
|
||||
/**
|
||||
* ChaCha20-Poly1305 from RFC 8439.
|
||||
*
|
||||
* Unsafe to use random nonces under the same key, due to collision chance.
|
||||
* Prefer XChaCha instead.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 12-byte nonce.
|
||||
* @param AAD - Additional authenticated data.
|
||||
* @returns AEAD cipher instance.
|
||||
* @example
|
||||
* Encrypts and authenticates plaintext with a fresh key and nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { chacha20poly1305 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(12);
|
||||
* const cipher = chacha20poly1305(key, nonce);
|
||||
* cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export declare const chacha20poly1305: TRet<ARXCipher>;
|
||||
/**
|
||||
* XChaCha20-Poly1305 extended-nonce chacha.
|
||||
*
|
||||
* Can be safely used with random nonces (CSPRNG).
|
||||
* See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | the IRTF draft}.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 24-byte nonce.
|
||||
* @param AAD - Additional authenticated data.
|
||||
* @returns AEAD cipher instance.
|
||||
* @example
|
||||
* Encrypts and authenticates plaintext with a fresh key and random 24-byte nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(24);
|
||||
* const cipher = xchacha20poly1305(key, nonce);
|
||||
* cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export declare const xchacha20poly1305: TRet<ARXCipher>;
|
||||
/**
|
||||
* Chacha20 CSPRNG (cryptographically secure pseudorandom number generator).
|
||||
* It's best to limit usage to non-production, non-critical cases: for example, test-only.
|
||||
* Compatible with libtomcrypt. It does not have a specification, so unclear how secure it is.
|
||||
* @param seed - Optional seed bytes mixed into the internal `key || nonce` state. When omitted,
|
||||
* only 32 random bytes are mixed into the 40-byte state.
|
||||
* @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`.
|
||||
* @example
|
||||
* Seeds the test-only ChaCha20 DRBG from fresh entropy.
|
||||
*
|
||||
* ```ts
|
||||
* import { rngChacha20 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const seed = randomBytes(32);
|
||||
* const prg = rngChacha20(seed);
|
||||
* prg.randomBytes(8);
|
||||
* ```
|
||||
*/
|
||||
export declare const rngChacha20: TRet<XorPRG>;
|
||||
/**
|
||||
* Chacha20/8 CSPRNG (cryptographically secure pseudorandom number generator).
|
||||
* It's best to limit usage to non-production, non-critical cases: for example, test-only.
|
||||
* Faster than `rngChacha20`.
|
||||
* @param seed - Optional seed bytes mixed into the internal `key || nonce` state. When omitted,
|
||||
* only 32 random bytes are mixed into the 44-byte state.
|
||||
* @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`.
|
||||
* @example
|
||||
* Seeds the faster test-only ChaCha8 DRBG from fresh entropy.
|
||||
*
|
||||
* ```ts
|
||||
* import { rngChacha8 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const seed = randomBytes(32);
|
||||
* const prg = rngChacha8(seed);
|
||||
* prg.randomBytes(8);
|
||||
* ```
|
||||
*/
|
||||
export declare const rngChacha8: TRet<XorPRG>;
|
||||
export {};
|
||||
//# sourceMappingURL=chacha.d.ts.map
|
||||
1
node_modules/@noble/ciphers/chacha.d.ts.map
generated
vendored
Normal file
1
node_modules/@noble/ciphers/chacha.d.ts.map
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"chacha.d.ts","sourceRoot":"","sources":["src/chacha.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AACH,OAAO,EAAE,KAAK,MAAM,EAAiC,MAAM,WAAW,CAAC;AAEvE,OAAO,EACL,KAAK,SAAS,EACd,KAAK,gBAAgB,EACrB,KAAK,IAAI,EACT,KAAK,IAAI,EACT,KAAK,SAAS,EASf,MAAM,YAAY,CAAC;AAkEpB,sFAAsF;AAEtF,QAAA,MAAM,gBAAgB,EAAE,OAAO,UAE8C,CAAC;AAK9E,gFAAgF;AAEhF,iBAAS,UAAU,CACjB,CAAC,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,GAAG,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,SAAK,GACjH,IAAI,CA6DN;AACD;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,wBAAgB,OAAO,CACrB,CAAC,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,GAAG,EAAE,IAAI,CAAC,WAAW,CAAC,GACvF,IAAI,CAqDN;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,eAAO,MAAM,YAAY,EAAE,IAAI,CAAC,SAAS,CAIvC,CAAC;AACH;;;;;;;;;;;;;;;;;;;GAmBG;AACH,eAAO,MAAM,QAAQ,EAAE,IAAI,CAAC,SAAS,CAInC,CAAC;AAEH;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,eAAO,MAAM,SAAS,EAAE,IAAI,CAAC,SAAS,CAKpC,CAAC;AAEH;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,OAAO,EAAE,IAAI,CAAC,SAAS,CAIlC,CAAC;AAEH;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,QAAQ,EAAE,IAAI,CAAC,SAAS,CAInC,CAAC;AAGH,eAAO,MAAM,OAAO,EAAE;IACpB,gBAAgB,EAAE,OAAO,gBAAgB,CAAC;IAC1C,UAAU,EAAE,OAAO,UAAU,CAAC;CACmC,CAAC;AA0CpE;;;;;;GAMG;AACH,eAAO,MAAM,cAAc,GACxB,WAAW,IAAI,CAAC,SAAS,CAAC,MAC1B,KAAK,IAAI,CAAC,UAAU,CAAC,EAAE,OAAO,IAAI,CAAC,UAAU,CAAC,EAAE,MAAM,IAAI,CAAC,UAAU,CAAC,KAAG,gBA+CzE,CAAC;AAEJ;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,eAAO,MAAM,gBAAgB,EAAE,IAAI,CAAC,SAAS,CAG5C,CAAC;AACF;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,eAAO,MAAM,iBAAiB,EAAE,IAAI,CAAC,SAAS,CAG7C,CAAC;AAEF;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,WAAW,EAAE,IAAI,CAAC,MAAM,CAAsD,CAAC;AAC5F;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,UAAU,EAAE,IAAI,CAAC,MAAM,CAAkD,CAAC"}
|
||||
575
node_modules/@noble/ciphers/chacha.js
generated
vendored
Normal file
575
node_modules/@noble/ciphers/chacha.js
generated
vendored
Normal file
@@ -0,0 +1,575 @@
|
||||
/**
|
||||
* ChaCha stream cipher, released
|
||||
* in 2008. Developed after Salsa20, ChaCha aims to increase diffusion per round.
|
||||
* It was standardized in
|
||||
* {@link https://www.rfc-editor.org/rfc/rfc8439 | RFC 8439} and
|
||||
* is now used in TLS 1.3.
|
||||
*
|
||||
* {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | XChaCha20}
|
||||
* extended-nonce variant is also provided. Similar to XSalsa, it's safe to use with
|
||||
* randomly-generated nonces.
|
||||
*
|
||||
* Check out
|
||||
* {@link http://cr.yp.to/chacha/chacha-20080128.pdf | PDF},
|
||||
* {@link https://en.wikipedia.org/wiki/Salsa20 | wiki}, and
|
||||
* {@link https://cr.yp.to/chacha.html | website}.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import { createCipher, createPRG, rotl } from "./_arx.js";
|
||||
import { poly1305 } from "./_poly1305.js";
|
||||
import { abytes, clean, equalBytes, getOutput, swap8IfBE, swap32IfBE, u64Lengths, wrapCipher, } from "./utils.js";
|
||||
/**
|
||||
* ChaCha core function. It is implemented twice:
|
||||
* 1. Simple loop (chachaCore_small, hchacha_small)
|
||||
* 2. Unrolled loop (chachaCore, hchacha) - 4x faster, but larger & harder to read
|
||||
* The specific implementation is selected in `createCipher` below.
|
||||
*/
|
||||
/** RFC 8439 §2.1 quarter round on words a, b, c, d. */
|
||||
// prettier-ignore
|
||||
function chachaQR(x, a, b, c, d) {
|
||||
x[a] = (x[a] + x[b]) | 0;
|
||||
x[d] = rotl(x[d] ^ x[a], 16);
|
||||
x[c] = (x[c] + x[d]) | 0;
|
||||
x[b] = rotl(x[b] ^ x[c], 12);
|
||||
x[a] = (x[a] + x[b]) | 0;
|
||||
x[d] = rotl(x[d] ^ x[a], 8);
|
||||
x[c] = (x[c] + x[d]) | 0;
|
||||
x[b] = rotl(x[b] ^ x[c], 7);
|
||||
}
|
||||
/** Repeated ChaCha double rounds; callers are expected to pass an even round count. */
|
||||
function chachaRound(x, rounds = 20) {
|
||||
for (let r = 0; r < rounds; r += 2) {
|
||||
// RFC 8439 §2.3 / §2.3.1 inner_block: four column rounds, then four diagonal rounds.
|
||||
chachaQR(x, 0, 4, 8, 12);
|
||||
chachaQR(x, 1, 5, 9, 13);
|
||||
chachaQR(x, 2, 6, 10, 14);
|
||||
chachaQR(x, 3, 7, 11, 15);
|
||||
chachaQR(x, 0, 5, 10, 15);
|
||||
chachaQR(x, 1, 6, 11, 12);
|
||||
chachaQR(x, 2, 7, 8, 13);
|
||||
chachaQR(x, 3, 4, 9, 14);
|
||||
}
|
||||
}
|
||||
// Shared scratch for the auditability-only helper below; only the test-only
|
||||
// __TESTS.chachaCore_small hook reaches it, so production exports stay reentrant.
|
||||
const ctmp = /* @__PURE__ */ new Uint32Array(16);
|
||||
/** Small version of chacha without loop unrolling. Unused, provided for auditability. */
|
||||
// prettier-ignore
|
||||
function chacha(s, k, i, out, isHChacha = true, rounds = 20) {
|
||||
// `i` is either `[counter, nonce0, nonce1, nonce2]` for the ChaCha block
|
||||
// function or the full 128-bit nonce prefix for the HChaCha subkey path.
|
||||
// Create initial array using common pattern
|
||||
const y = Uint32Array.from([
|
||||
s[0], s[1], s[2], s[3], // "expa" "nd 3" "2-by" "te k"
|
||||
k[0], k[1], k[2], k[3], // Key Key Key Key
|
||||
k[4], k[5], k[6], k[7], // Key Key Key Key
|
||||
i[0], i[1], i[2], i[3], // Counter Counter Nonce Nonce
|
||||
]);
|
||||
const x = ctmp;
|
||||
x.set(y);
|
||||
chachaRound(x, rounds);
|
||||
// HChaCha writes words 0..3 and 12..15 after the rounds; the ChaCha
|
||||
// block path adds the original state word-by-word.
|
||||
if (isHChacha) {
|
||||
const xindexes = [0, 1, 2, 3, 12, 13, 14, 15];
|
||||
for (let i = 0; i < 8; i++)
|
||||
out[i] = x[xindexes[i]];
|
||||
}
|
||||
else {
|
||||
for (let i = 0; i < 16; i++)
|
||||
out[i] = (y[i] + x[i]) | 0;
|
||||
}
|
||||
}
|
||||
/** Identical to `chachaCore`. Reached only through the test-only `__TESTS` export. */
|
||||
// @ts-ignore
|
||||
const chachaCore_small = (s, k, n, out, cnt, rounds) =>
|
||||
// Keep the reference wrapper on the same [counter, nonce0, nonce1, nonce2] layout as chacha().
|
||||
chacha(s, k, Uint32Array.from([cnt, n[0], n[1], n[2]]), out, false, rounds);
|
||||
/** Identical to `hchacha`. Unused. */
|
||||
// @ts-ignore
|
||||
const hchacha_small = chacha;
|
||||
/** RFC 8439 §2.3 block core for `state = constants | key | counter | nonce`. */
|
||||
// prettier-ignore
|
||||
function chachaCore(s, k, n, out, cnt, rounds = 20) {
|
||||
let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], // "expa" "nd 3" "2-by" "te k"
|
||||
y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], // Key Key Key Key
|
||||
y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], // Key Key Key Key
|
||||
y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2]; // Counter Nonce Nonce Nonce
|
||||
// Save state to temporary variables
|
||||
let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;
|
||||
for (let r = 0; r < rounds; r += 2) {
|
||||
x00 = (x00 + x04) | 0;
|
||||
x12 = rotl(x12 ^ x00, 16);
|
||||
x08 = (x08 + x12) | 0;
|
||||
x04 = rotl(x04 ^ x08, 12);
|
||||
x00 = (x00 + x04) | 0;
|
||||
x12 = rotl(x12 ^ x00, 8);
|
||||
x08 = (x08 + x12) | 0;
|
||||
x04 = rotl(x04 ^ x08, 7);
|
||||
x01 = (x01 + x05) | 0;
|
||||
x13 = rotl(x13 ^ x01, 16);
|
||||
x09 = (x09 + x13) | 0;
|
||||
x05 = rotl(x05 ^ x09, 12);
|
||||
x01 = (x01 + x05) | 0;
|
||||
x13 = rotl(x13 ^ x01, 8);
|
||||
x09 = (x09 + x13) | 0;
|
||||
x05 = rotl(x05 ^ x09, 7);
|
||||
x02 = (x02 + x06) | 0;
|
||||
x14 = rotl(x14 ^ x02, 16);
|
||||
x10 = (x10 + x14) | 0;
|
||||
x06 = rotl(x06 ^ x10, 12);
|
||||
x02 = (x02 + x06) | 0;
|
||||
x14 = rotl(x14 ^ x02, 8);
|
||||
x10 = (x10 + x14) | 0;
|
||||
x06 = rotl(x06 ^ x10, 7);
|
||||
x03 = (x03 + x07) | 0;
|
||||
x15 = rotl(x15 ^ x03, 16);
|
||||
x11 = (x11 + x15) | 0;
|
||||
x07 = rotl(x07 ^ x11, 12);
|
||||
x03 = (x03 + x07) | 0;
|
||||
x15 = rotl(x15 ^ x03, 8);
|
||||
x11 = (x11 + x15) | 0;
|
||||
x07 = rotl(x07 ^ x11, 7);
|
||||
x00 = (x00 + x05) | 0;
|
||||
x15 = rotl(x15 ^ x00, 16);
|
||||
x10 = (x10 + x15) | 0;
|
||||
x05 = rotl(x05 ^ x10, 12);
|
||||
x00 = (x00 + x05) | 0;
|
||||
x15 = rotl(x15 ^ x00, 8);
|
||||
x10 = (x10 + x15) | 0;
|
||||
x05 = rotl(x05 ^ x10, 7);
|
||||
x01 = (x01 + x06) | 0;
|
||||
x12 = rotl(x12 ^ x01, 16);
|
||||
x11 = (x11 + x12) | 0;
|
||||
x06 = rotl(x06 ^ x11, 12);
|
||||
x01 = (x01 + x06) | 0;
|
||||
x12 = rotl(x12 ^ x01, 8);
|
||||
x11 = (x11 + x12) | 0;
|
||||
x06 = rotl(x06 ^ x11, 7);
|
||||
x02 = (x02 + x07) | 0;
|
||||
x13 = rotl(x13 ^ x02, 16);
|
||||
x08 = (x08 + x13) | 0;
|
||||
x07 = rotl(x07 ^ x08, 12);
|
||||
x02 = (x02 + x07) | 0;
|
||||
x13 = rotl(x13 ^ x02, 8);
|
||||
x08 = (x08 + x13) | 0;
|
||||
x07 = rotl(x07 ^ x08, 7);
|
||||
x03 = (x03 + x04) | 0;
|
||||
x14 = rotl(x14 ^ x03, 16);
|
||||
x09 = (x09 + x14) | 0;
|
||||
x04 = rotl(x04 ^ x09, 12);
|
||||
x03 = (x03 + x04) | 0;
|
||||
x14 = rotl(x14 ^ x03, 8);
|
||||
x09 = (x09 + x14) | 0;
|
||||
x04 = rotl(x04 ^ x09, 7);
|
||||
}
|
||||
// RFC 8439 §2.3 / §2.3.1: add the original state words back in state order.
|
||||
let oi = 0;
|
||||
out[oi++] = (y00 + x00) | 0;
|
||||
out[oi++] = (y01 + x01) | 0;
|
||||
out[oi++] = (y02 + x02) | 0;
|
||||
out[oi++] = (y03 + x03) | 0;
|
||||
out[oi++] = (y04 + x04) | 0;
|
||||
out[oi++] = (y05 + x05) | 0;
|
||||
out[oi++] = (y06 + x06) | 0;
|
||||
out[oi++] = (y07 + x07) | 0;
|
||||
out[oi++] = (y08 + x08) | 0;
|
||||
out[oi++] = (y09 + x09) | 0;
|
||||
out[oi++] = (y10 + x10) | 0;
|
||||
out[oi++] = (y11 + x11) | 0;
|
||||
out[oi++] = (y12 + x12) | 0;
|
||||
out[oi++] = (y13 + x13) | 0;
|
||||
out[oi++] = (y14 + x14) | 0;
|
||||
out[oi++] = (y15 + x15) | 0;
|
||||
}
|
||||
/**
|
||||
* hchacha hashes key and nonce into key' and nonce' for xchacha20.
|
||||
* Algorithmically identical to `hchacha_small`, but this exported path
|
||||
* normalizes word order on big-endian hosts.
|
||||
* Need to find a way to merge it with `chachaCore` without 25% performance hit.
|
||||
* @param s - Sigma constants as 32-bit words.
|
||||
* @param k - Key words.
|
||||
* @param i - Nonce-prefix words.
|
||||
* @param out - Output buffer for the derived subkey.
|
||||
* @example
|
||||
* Derives the XChaCha subkey from sigma, key, and nonce-prefix words.
|
||||
*
|
||||
* ```ts
|
||||
* const sigma = new Uint32Array(4);
|
||||
* const key = new Uint32Array(8);
|
||||
* const nonce = new Uint32Array(4);
|
||||
* const out = new Uint32Array(8);
|
||||
* hchacha(sigma, key, nonce, out);
|
||||
* ```
|
||||
*/
|
||||
// prettier-ignore
|
||||
export function hchacha(s, k, i, out) {
|
||||
let x00 = swap8IfBE(s[0]), x01 = swap8IfBE(s[1]), x02 = swap8IfBE(s[2]), x03 = swap8IfBE(s[3]), x04 = swap8IfBE(k[0]), x05 = swap8IfBE(k[1]), x06 = swap8IfBE(k[2]), x07 = swap8IfBE(k[3]), x08 = swap8IfBE(k[4]), x09 = swap8IfBE(k[5]), x10 = swap8IfBE(k[6]), x11 = swap8IfBE(k[7]), x12 = swap8IfBE(i[0]), x13 = swap8IfBE(i[1]), x14 = swap8IfBE(i[2]), x15 = swap8IfBE(i[3]);
|
||||
for (let r = 0; r < 20; r += 2) {
|
||||
x00 = (x00 + x04) | 0;
|
||||
x12 = rotl(x12 ^ x00, 16);
|
||||
x08 = (x08 + x12) | 0;
|
||||
x04 = rotl(x04 ^ x08, 12);
|
||||
x00 = (x00 + x04) | 0;
|
||||
x12 = rotl(x12 ^ x00, 8);
|
||||
x08 = (x08 + x12) | 0;
|
||||
x04 = rotl(x04 ^ x08, 7);
|
||||
x01 = (x01 + x05) | 0;
|
||||
x13 = rotl(x13 ^ x01, 16);
|
||||
x09 = (x09 + x13) | 0;
|
||||
x05 = rotl(x05 ^ x09, 12);
|
||||
x01 = (x01 + x05) | 0;
|
||||
x13 = rotl(x13 ^ x01, 8);
|
||||
x09 = (x09 + x13) | 0;
|
||||
x05 = rotl(x05 ^ x09, 7);
|
||||
x02 = (x02 + x06) | 0;
|
||||
x14 = rotl(x14 ^ x02, 16);
|
||||
x10 = (x10 + x14) | 0;
|
||||
x06 = rotl(x06 ^ x10, 12);
|
||||
x02 = (x02 + x06) | 0;
|
||||
x14 = rotl(x14 ^ x02, 8);
|
||||
x10 = (x10 + x14) | 0;
|
||||
x06 = rotl(x06 ^ x10, 7);
|
||||
x03 = (x03 + x07) | 0;
|
||||
x15 = rotl(x15 ^ x03, 16);
|
||||
x11 = (x11 + x15) | 0;
|
||||
x07 = rotl(x07 ^ x11, 12);
|
||||
x03 = (x03 + x07) | 0;
|
||||
x15 = rotl(x15 ^ x03, 8);
|
||||
x11 = (x11 + x15) | 0;
|
||||
x07 = rotl(x07 ^ x11, 7);
|
||||
x00 = (x00 + x05) | 0;
|
||||
x15 = rotl(x15 ^ x00, 16);
|
||||
x10 = (x10 + x15) | 0;
|
||||
x05 = rotl(x05 ^ x10, 12);
|
||||
x00 = (x00 + x05) | 0;
|
||||
x15 = rotl(x15 ^ x00, 8);
|
||||
x10 = (x10 + x15) | 0;
|
||||
x05 = rotl(x05 ^ x10, 7);
|
||||
x01 = (x01 + x06) | 0;
|
||||
x12 = rotl(x12 ^ x01, 16);
|
||||
x11 = (x11 + x12) | 0;
|
||||
x06 = rotl(x06 ^ x11, 12);
|
||||
x01 = (x01 + x06) | 0;
|
||||
x12 = rotl(x12 ^ x01, 8);
|
||||
x11 = (x11 + x12) | 0;
|
||||
x06 = rotl(x06 ^ x11, 7);
|
||||
x02 = (x02 + x07) | 0;
|
||||
x13 = rotl(x13 ^ x02, 16);
|
||||
x08 = (x08 + x13) | 0;
|
||||
x07 = rotl(x07 ^ x08, 12);
|
||||
x02 = (x02 + x07) | 0;
|
||||
x13 = rotl(x13 ^ x02, 8);
|
||||
x08 = (x08 + x13) | 0;
|
||||
x07 = rotl(x07 ^ x08, 7);
|
||||
x03 = (x03 + x04) | 0;
|
||||
x14 = rotl(x14 ^ x03, 16);
|
||||
x09 = (x09 + x14) | 0;
|
||||
x04 = rotl(x04 ^ x09, 12);
|
||||
x03 = (x03 + x04) | 0;
|
||||
x14 = rotl(x14 ^ x03, 8);
|
||||
x09 = (x09 + x14) | 0;
|
||||
x04 = rotl(x04 ^ x09, 7);
|
||||
}
|
||||
// HChaCha derives the subkey from state words 0..3 and 12..15 after 20 rounds.
|
||||
let oi = 0;
|
||||
out[oi++] = x00;
|
||||
out[oi++] = x01;
|
||||
out[oi++] = x02;
|
||||
out[oi++] = x03;
|
||||
out[oi++] = x12;
|
||||
out[oi++] = x13;
|
||||
out[oi++] = x14;
|
||||
out[oi++] = x15;
|
||||
swap32IfBE(out);
|
||||
}
|
||||
/**
|
||||
* Original, non-RFC chacha20 from DJB. 8-byte nonce, 8-byte counter.
|
||||
* The nonce/counter layout still reserves 8 counter bytes internally, but the shared public
|
||||
* `counter` argument follows noble's strict non-wrapping 32-bit policy. See `src/_arx.ts`
|
||||
* near `MAX_COUNTER` for the full counter-policy rationale.
|
||||
* @param key - 16-byte or 32-byte key.
|
||||
* @param nonce - 8-byte nonce.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Initial block counter.
|
||||
* @returns Encrypted or decrypted bytes.
|
||||
* @example
|
||||
* Encrypts bytes with the original 8-byte-nonce ChaCha variant and a fresh key/nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { chacha20orig } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(8);
|
||||
* chacha20orig(key, nonce, new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export const chacha20orig = /* @__PURE__ */ createCipher(chachaCore, {
|
||||
counterRight: false,
|
||||
counterLength: 8,
|
||||
allowShortKeys: true,
|
||||
});
|
||||
/**
|
||||
* ChaCha stream cipher. Conforms to RFC 8439 (IETF, TLS). 12-byte nonce, 4-byte counter.
|
||||
* With smaller nonce, it's not safe to make it random (CSPRNG), due to collision chance.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 12-byte nonce.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Initial block counter.
|
||||
* @returns Encrypted or decrypted bytes.
|
||||
* @example
|
||||
* Encrypts bytes with the RFC 8439 ChaCha20 stream cipher and a fresh key/nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { chacha20 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(12);
|
||||
* chacha20(key, nonce, new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export const chacha20 = /* @__PURE__ */ createCipher(chachaCore, {
|
||||
counterRight: false,
|
||||
counterLength: 4,
|
||||
allowShortKeys: false,
|
||||
});
|
||||
/**
|
||||
* XChaCha eXtended-nonce ChaCha. With 24-byte nonce, it's safe to make it random (CSPRNG).
|
||||
* See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | the IRTF draft}.
|
||||
* The nonce/counter layout still reserves 8 counter bytes internally, but the shared public
|
||||
* `counter` argument follows noble's strict non-wrapping 32-bit policy. See `src/_arx.ts`
|
||||
* near `MAX_COUNTER` for the full counter-policy rationale.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 24-byte extended nonce.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Initial block counter.
|
||||
* @returns Encrypted or decrypted bytes.
|
||||
* @example
|
||||
* Encrypts bytes with XChaCha20 using a fresh key and random 24-byte nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { xchacha20 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(24);
|
||||
* xchacha20(key, nonce, new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export const xchacha20 = /* @__PURE__ */ createCipher(chachaCore, {
|
||||
counterRight: false,
|
||||
counterLength: 8,
|
||||
extendNonceFn: hchacha,
|
||||
allowShortKeys: false,
|
||||
});
|
||||
/**
|
||||
* Reduced 8-round chacha, described in original paper.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 12-byte nonce.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Initial block counter.
|
||||
* @returns Encrypted or decrypted bytes.
|
||||
* @example
|
||||
* Uses the reduced 8-round variant for non-critical workloads with a fresh key/nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { chacha8 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(12);
|
||||
* chacha8(key, nonce, new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export const chacha8 = /* @__PURE__ */ createCipher(chachaCore, {
|
||||
counterRight: false,
|
||||
counterLength: 4,
|
||||
rounds: 8,
|
||||
});
|
||||
/**
|
||||
* Reduced 12-round chacha, described in original paper.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 12-byte nonce.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Initial block counter.
|
||||
* @returns Encrypted or decrypted bytes.
|
||||
* @example
|
||||
* Uses the reduced 12-round variant for non-critical workloads with a fresh key/nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { chacha12 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(12);
|
||||
* chacha12(key, nonce, new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export const chacha12 = /* @__PURE__ */ createCipher(chachaCore, {
|
||||
counterRight: false,
|
||||
counterLength: 4,
|
||||
rounds: 12,
|
||||
});
|
||||
// Test-only hooks for keeping the simple/reference core aligned with the unrolled production core.
|
||||
export const __TESTS = /* @__PURE__ */ Object.freeze({ chachaCore_small, chachaCore });
|
||||
// RFC 8439 §2.8.1 pad16(x): shared zero block for AAD/ciphertext padding.
|
||||
const ZEROS16 = /* @__PURE__ */ new Uint8Array(16);
|
||||
// RFC 8439 §2.8 / §2.8.1: aligned inputs add nothing, otherwise append 16-(len%16) zero bytes.
|
||||
const updatePadded = (h, msg) => {
|
||||
h.update(msg);
|
||||
const leftover = msg.length % 16;
|
||||
if (leftover)
|
||||
h.update(ZEROS16.subarray(leftover));
|
||||
};
|
||||
// RFC 8439 §2.6.1 poly1305_key_gen returns `block[0..31]`, so AEAD key
|
||||
// generation only needs 32 zero bytes.
|
||||
const ZEROS32 = /* @__PURE__ */ new Uint8Array(32);
|
||||
function computeTag(fn, key, nonce, ciphertext, AAD) {
|
||||
if (AAD !== undefined)
|
||||
abytes(AAD, undefined, 'AAD');
|
||||
// RFC 8439 §2.6 / §2.8: derive the Poly1305 one-time key from counter 0,
|
||||
// then MAC AAD || pad16(AAD) || ciphertext || pad16(ciphertext) || len(AAD) || len(ciphertext).
|
||||
const authKey = fn(key, nonce, ZEROS32);
|
||||
const lengths = u64Lengths(ciphertext.length, AAD ? AAD.length : 0, true);
|
||||
// Methods below can be replaced with
|
||||
// return poly1305_computeTag_small(authKey, lengths, ciphertext, AAD)
|
||||
const h = poly1305.create(authKey);
|
||||
if (AAD)
|
||||
updatePadded(h, AAD);
|
||||
updatePadded(h, ciphertext);
|
||||
h.update(lengths);
|
||||
const res = h.digest();
|
||||
clean(authKey, lengths);
|
||||
return res;
|
||||
}
|
||||
/**
|
||||
* AEAD algorithm from RFC 8439.
|
||||
* Salsa20 and chacha (RFC 8439) use poly1305 differently.
|
||||
* We could have composed them, but it's hard because of authKey:
|
||||
* In salsa20, authKey changes position in salsa stream.
|
||||
* In chacha, authKey can't be computed inside computeTag, it modifies the counter.
|
||||
*/
|
||||
export const _poly1305_aead = (xorStream) => (key, nonce, AAD) => {
|
||||
// This borrows caller key/nonce/AAD buffers by reference; mutating them after construction
|
||||
// changes future encrypt/decrypt results.
|
||||
const tagLength = 16;
|
||||
return {
|
||||
encrypt(plaintext, output) {
|
||||
const plength = plaintext.length;
|
||||
output = getOutput(plength + tagLength, output, false);
|
||||
output.set(plaintext);
|
||||
const oPlain = output.subarray(0, -tagLength);
|
||||
// RFC 8439 §2.8: payload encryption starts at counter 1 because counter 0 produced the OTK.
|
||||
xorStream(key, nonce, oPlain, oPlain, 1);
|
||||
const tag = computeTag(xorStream, key, nonce, oPlain, AAD);
|
||||
output.set(tag, plength); // append tag
|
||||
clean(tag);
|
||||
return output;
|
||||
},
|
||||
decrypt(ciphertext, output) {
|
||||
output = getOutput(ciphertext.length - tagLength, output, false);
|
||||
const data = ciphertext.subarray(0, -tagLength);
|
||||
const passedTag = ciphertext.subarray(-tagLength);
|
||||
const tag = computeTag(xorStream, key, nonce, data, AAD);
|
||||
// RFC 8439 §2.8 / §4: authenticate ciphertext before decrypting it, and compare tags with
|
||||
// the constant-time equalBytes() helper rather than decrypting speculative plaintext first.
|
||||
if (!equalBytes(passedTag, tag)) {
|
||||
clean(tag);
|
||||
throw new Error('invalid tag');
|
||||
}
|
||||
output.set(ciphertext.subarray(0, -tagLength));
|
||||
// Actual decryption
|
||||
xorStream(key, nonce, output, output, 1); // start stream with i=1
|
||||
clean(tag);
|
||||
return output;
|
||||
},
|
||||
};
|
||||
};
|
||||
/**
|
||||
* ChaCha20-Poly1305 from RFC 8439.
|
||||
*
|
||||
* Unsafe to use random nonces under the same key, due to collision chance.
|
||||
* Prefer XChaCha instead.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 12-byte nonce.
|
||||
* @param AAD - Additional authenticated data.
|
||||
* @returns AEAD cipher instance.
|
||||
* @example
|
||||
* Encrypts and authenticates plaintext with a fresh key and nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { chacha20poly1305 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(12);
|
||||
* const cipher = chacha20poly1305(key, nonce);
|
||||
* cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export const chacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 12, tagLength: 16 },
|
||||
/* @__PURE__ */ _poly1305_aead(chacha20));
|
||||
/**
|
||||
* XChaCha20-Poly1305 extended-nonce chacha.
|
||||
*
|
||||
* Can be safely used with random nonces (CSPRNG).
|
||||
* See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | the IRTF draft}.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 24-byte nonce.
|
||||
* @param AAD - Additional authenticated data.
|
||||
* @returns AEAD cipher instance.
|
||||
* @example
|
||||
* Encrypts and authenticates plaintext with a fresh key and random 24-byte nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(24);
|
||||
* const cipher = xchacha20poly1305(key, nonce);
|
||||
* cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export const xchacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 24, tagLength: 16 },
|
||||
/* @__PURE__ */ _poly1305_aead(xchacha20));
|
||||
/**
|
||||
* Chacha20 CSPRNG (cryptographically secure pseudorandom number generator).
|
||||
* It's best to limit usage to non-production, non-critical cases: for example, test-only.
|
||||
* Compatible with libtomcrypt. It does not have a specification, so unclear how secure it is.
|
||||
* @param seed - Optional seed bytes mixed into the internal `key || nonce` state. When omitted,
|
||||
* only 32 random bytes are mixed into the 40-byte state.
|
||||
* @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`.
|
||||
* @example
|
||||
* Seeds the test-only ChaCha20 DRBG from fresh entropy.
|
||||
*
|
||||
* ```ts
|
||||
* import { rngChacha20 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const seed = randomBytes(32);
|
||||
* const prg = rngChacha20(seed);
|
||||
* prg.randomBytes(8);
|
||||
* ```
|
||||
*/
|
||||
export const rngChacha20 = /* @__PURE__ */ createPRG(chacha20orig, 64, 32, 8);
|
||||
/**
|
||||
* Chacha20/8 CSPRNG (cryptographically secure pseudorandom number generator).
|
||||
* It's best to limit usage to non-production, non-critical cases: for example, test-only.
|
||||
* Faster than `rngChacha20`.
|
||||
* @param seed - Optional seed bytes mixed into the internal `key || nonce` state. When omitted,
|
||||
* only 32 random bytes are mixed into the 44-byte state.
|
||||
* @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`.
|
||||
* @example
|
||||
* Seeds the faster test-only ChaCha8 DRBG from fresh entropy.
|
||||
*
|
||||
* ```ts
|
||||
* import { rngChacha8 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const seed = randomBytes(32);
|
||||
* const prg = rngChacha8(seed);
|
||||
* prg.randomBytes(8);
|
||||
* ```
|
||||
*/
|
||||
export const rngChacha8 = /* @__PURE__ */ createPRG(chacha8, 64, 32, 12);
|
||||
//# sourceMappingURL=chacha.js.map
|
||||
1
node_modules/@noble/ciphers/chacha.js.map
generated
vendored
Normal file
1
node_modules/@noble/ciphers/chacha.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
40
node_modules/@noble/ciphers/ff1.d.ts
generated
vendored
Normal file
40
node_modules/@noble/ciphers/ff1.d.ts
generated
vendored
Normal file
@@ -0,0 +1,40 @@
|
||||
import { type Cipher, type TArg, type TRet } from './utils.ts';
|
||||
/**
|
||||
* FPE-FF1 format-preserving encryption.
|
||||
* @param radix - Alphabet size for each input digit.
|
||||
* @param key - AES key bytes.
|
||||
* @param tweak - Optional tweak bytes.
|
||||
* @returns Encrypt/decrypt helpers over digit arrays.
|
||||
* @example
|
||||
* Encrypts decimal digits without changing their format, using a fresh AES key.
|
||||
*
|
||||
* ```ts
|
||||
* import { FF1 } from '@noble/ciphers/ff1.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const ff1 = FF1(10, key);
|
||||
* ff1.encrypt([1, 2, 3]);
|
||||
* ```
|
||||
*/
|
||||
export declare function FF1(radix: number, key: TArg<Uint8Array>, tweak?: TArg<Uint8Array>): {
|
||||
encrypt(x: number[]): number[];
|
||||
decrypt(x: number[]): number[];
|
||||
};
|
||||
/**
|
||||
* Binary FPE-FF1 wrapper over byte arrays.
|
||||
* @param key - AES key bytes.
|
||||
* @param tweak - Optional tweak bytes.
|
||||
* @returns Encrypt/decrypt helpers over byte arrays.
|
||||
* @example
|
||||
* Encrypts raw bytes through FF1's binary alphabet wrapper with a fresh AES key.
|
||||
*
|
||||
* ```ts
|
||||
* import { BinaryFF1 } from '@noble/ciphers/ff1.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const ff1 = BinaryFF1(key);
|
||||
* ff1.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export declare function BinaryFF1(key: TArg<Uint8Array>, tweak?: TArg<Uint8Array>): TRet<Cipher>;
|
||||
//# sourceMappingURL=ff1.d.ts.map
|
||||
1
node_modules/@noble/ciphers/ff1.d.ts.map
generated
vendored
Normal file
1
node_modules/@noble/ciphers/ff1.d.ts.map
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"ff1.d.ts","sourceRoot":"","sources":["src/ff1.ts"],"names":[],"mappings":"AAMA,OAAO,EAML,KAAK,MAAM,EACX,KAAK,IAAI,EACT,KAAK,IAAI,EACV,MAAM,YAAY,CAAC;AAqGpB;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,GAAG,CACjB,KAAK,EAAE,MAAM,EACb,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EACrB,KAAK,GAAE,IAAI,CAAC,UAAU,CAAa,GAClC;IAAE,OAAO,CAAC,CAAC,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,CAAC;IAAC,OAAO,CAAC,CAAC,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,CAAA;CAAE,CAkCpE;AAsBD;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,SAAS,CACvB,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EACrB,KAAK,GAAE,IAAI,CAAC,UAAU,CAAa,GAClC,IAAI,CAAC,MAAM,CAAC,CAQd"}
|
||||
204
node_modules/@noble/ciphers/ff1.js
generated
vendored
Normal file
204
node_modules/@noble/ciphers/ff1.js
generated
vendored
Normal file
@@ -0,0 +1,204 @@
|
||||
/**
|
||||
* FPE-FF1 (Format-preserving encryption algorithm) specified in
|
||||
* {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf | NIST 800-38G}.
|
||||
* @module
|
||||
*/
|
||||
import { unsafe } from "./aes.js";
|
||||
import { abytes, anumber, bytesToNumberBE, clean, numberToBytesBE, } from "./utils.js";
|
||||
// NIST SP 800-38G §4.3 / §5.1 Algorithm 7: FF1's designated CIPH_K here is AES, so this file
|
||||
// reuses the reviewed AES key schedule and single-block encryption helpers.
|
||||
// NOTE: no point in inlining encrypt instead of encryptBlock, since BigInt stuff will be slow
|
||||
const { expandKeyLE, encryptBlock } = unsafe;
|
||||
// Format-preserving encryption algorithm (FPE-FF1) specified in
|
||||
// {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf | NIST Special Publication 800-38G}.
|
||||
const BLOCK_LEN = 16;
|
||||
function mod(a, b) {
|
||||
const result = a % b;
|
||||
return result >= 0 ? result : b + result;
|
||||
}
|
||||
function NUMradix(radix, data) {
|
||||
let res = BigInt(0);
|
||||
for (let i of data)
|
||||
res = res * BigInt(radix) + BigInt(i);
|
||||
return res;
|
||||
}
|
||||
function getRound(radix, key, tweak, x) {
|
||||
if (radix > 2 ** 16 - 1)
|
||||
throw new Error('invalid radix ' + radix);
|
||||
// radix**minlen ≥ 100
|
||||
const minLen = Math.ceil(Math.log(100) / Math.log(radix));
|
||||
const maxLen = 2 ** 32 - 1;
|
||||
// 2 ≤ minlen ≤ maxlen < 2**32
|
||||
if (2 > minLen || minLen > maxLen || maxLen >= 2 ** 32)
|
||||
throw new Error('Invalid radix: 2 ≤ minlen ≤ maxlen < 2**32');
|
||||
if (!Array.isArray(x))
|
||||
throw new Error('invalid X');
|
||||
if (x.length < minLen || x.length > maxLen)
|
||||
throw new Error('X is outside minLen..maxLen bounds');
|
||||
// SP 800-38G defines FF1 over numeral strings in base `radix`; out-of-range digits must fail
|
||||
// before NUMradix(...) or round splitting can reinterpret them as a different numeral string.
|
||||
for (const i of x) {
|
||||
if (!Number.isSafeInteger(i) || i < 0 || i >= radix)
|
||||
throw new Error('invalid X: digit outside radix');
|
||||
}
|
||||
const u = Math.floor(x.length / 2);
|
||||
const v = x.length - u;
|
||||
const b = Math.ceil(Math.ceil(v * Math.log2(radix)) / 8);
|
||||
const d = 4 * Math.ceil(b / 4) + 4;
|
||||
const padding = mod(-tweak.length - b - 1, 16);
|
||||
// P = [1]1 || [2]1 || [1]1 || [radix]3 || [10]1 || [u mod 256]1 || [n]4 || [t]4.
|
||||
const P = Uint8Array.from([1, 2, 1, 0, 0, 0, 10, u, 0, 0, 0, 0, 0, 0, 0, 0]);
|
||||
const view = new DataView(P.buffer);
|
||||
// NIST SP 800-38G §5.1 bounds radix <= 2^16, so the 24-bit [radix]3 field is encoded here as
|
||||
// 0x00 || uint16_be(radix).
|
||||
view.setUint16(4, radix, false);
|
||||
view.setUint32(8, x.length, false);
|
||||
view.setUint32(12, tweak.length, false);
|
||||
// Q = T || [0](−t−b−1) mod 16 || [i]1 || [NUMradix(B)]b.
|
||||
const PQ = new Uint8Array(P.length + tweak.length + padding + 1 + b);
|
||||
PQ.set(P);
|
||||
clean(P);
|
||||
PQ.set(tweak, P.length);
|
||||
const xk = expandKeyLE(key);
|
||||
const round = (A, B, i, decrypt = false) => {
|
||||
// Q = ... || [i]1 || [NUMradix(B)]b.
|
||||
PQ[PQ.length - b - 1] = i;
|
||||
if (b)
|
||||
PQ.set(numberToBytesBE(NUMradix(radix, B), b), PQ.length - b);
|
||||
// NIST SP 800-38G Algorithm 6 PRF: Y_j = CIPH_K(Y_(j-1) xor X_j) starting from Y_0 = 0^128.
|
||||
let r = new Uint8Array(16);
|
||||
for (let j = 0; j < PQ.length / BLOCK_LEN; j++) {
|
||||
for (let i = 0; i < BLOCK_LEN; i++)
|
||||
r[i] ^= PQ[j * BLOCK_LEN + i];
|
||||
encryptBlock(xk, r);
|
||||
}
|
||||
// Let S be the first d bytes of the following string of ⎡d/16⎤ blocks:
|
||||
// R || CIPHK(R ⊕[1]16) || CIPHK(R ⊕[2]16) ...CIPHK(R ⊕[⎡d / 16⎤ – 1]16).
|
||||
let s = Array.from(r);
|
||||
for (let j = 1; s.length < d; j++) {
|
||||
const block = numberToBytesBE(BigInt(j), 16);
|
||||
for (let k = 0; k < BLOCK_LEN; k++)
|
||||
block[k] ^= r[k];
|
||||
s.push(...Array.from(encryptBlock(xk, block)));
|
||||
}
|
||||
let y = bytesToNumberBE(Uint8Array.from(s.slice(0, d)));
|
||||
s.fill(0);
|
||||
if (decrypt)
|
||||
y = -y;
|
||||
const m = i % 2 === 0 ? u : v;
|
||||
let c = mod(NUMradix(radix, A) + y, BigInt(radix) ** BigInt(m));
|
||||
// STR(radix, m, c)
|
||||
const C = Array(m).fill(0);
|
||||
for (let i = 0; i < m; i++, c /= BigInt(radix))
|
||||
C[m - 1 - i] = Number(c % BigInt(radix));
|
||||
A.fill(0);
|
||||
A = B;
|
||||
B = C;
|
||||
return [A, B];
|
||||
};
|
||||
const destroy = () => {
|
||||
clean(xk, PQ);
|
||||
};
|
||||
return { u, round, destroy };
|
||||
}
|
||||
const EMPTY_BUF = /* @__PURE__ */ Uint8Array.of();
|
||||
/**
|
||||
* FPE-FF1 format-preserving encryption.
|
||||
* @param radix - Alphabet size for each input digit.
|
||||
* @param key - AES key bytes.
|
||||
* @param tweak - Optional tweak bytes.
|
||||
* @returns Encrypt/decrypt helpers over digit arrays.
|
||||
* @example
|
||||
* Encrypts decimal digits without changing their format, using a fresh AES key.
|
||||
*
|
||||
* ```ts
|
||||
* import { FF1 } from '@noble/ciphers/ff1.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const ff1 = FF1(10, key);
|
||||
* ff1.encrypt([1, 2, 3]);
|
||||
* ```
|
||||
*/
|
||||
export function FF1(radix, key, tweak = EMPTY_BUF) {
|
||||
anumber(radix);
|
||||
abytes(key);
|
||||
abytes(tweak);
|
||||
// This borrows caller key/tweak buffers by reference through the bound closure; mutating them
|
||||
// after construction changes later encrypt/decrypt outputs.
|
||||
const PQ = getRound.bind(null, radix, key, tweak);
|
||||
return {
|
||||
encrypt(x) {
|
||||
const { u, round, destroy } = PQ(x);
|
||||
let [A, B] = [x.slice(0, u), x.slice(u)];
|
||||
for (let i = 0; i < 10; i++)
|
||||
[A, B] = round(A, B, i);
|
||||
destroy();
|
||||
const res = A.concat(B);
|
||||
A.fill(0);
|
||||
B.fill(0);
|
||||
return res;
|
||||
},
|
||||
decrypt(x) {
|
||||
const { u, round, destroy } = PQ(x);
|
||||
// The FF1.Decrypt algorithm is similar to the FF1.Encrypt algorithm;
|
||||
// the differences are in Step 6, where:
|
||||
// 1) the order of the indices is reversed,
|
||||
// 2) the roles of A and B are swapped
|
||||
// 3) modular addition is replaced by modular subtraction, in Step 6vi.
|
||||
let [B, A] = [x.slice(0, u), x.slice(u)];
|
||||
for (let i = 9; i >= 0; i--)
|
||||
[A, B] = round(A, B, i, true);
|
||||
destroy();
|
||||
const res = B.concat(A);
|
||||
A.fill(0);
|
||||
B.fill(0);
|
||||
return res;
|
||||
},
|
||||
};
|
||||
}
|
||||
// Binary wrapper uses little-endian bit order within each byte so bit 0 stays
|
||||
// in the first numeral slot for this library-defined byte-array surface.
|
||||
const binLE = {
|
||||
encode(bytes) {
|
||||
const x = [];
|
||||
for (let i = 0; i < bytes.length; i++) {
|
||||
for (let j = 0, tmp = bytes[i]; j < 8; j++, tmp >>= 1)
|
||||
x.push(tmp & 1);
|
||||
}
|
||||
return x;
|
||||
},
|
||||
decode(b) {
|
||||
if (!Array.isArray(b) || b.length % 8)
|
||||
throw new Error('Invalid binary string');
|
||||
const res = new Uint8Array(b.length / 8);
|
||||
for (let i = 0, j = 0; i < res.length; i++) {
|
||||
res[i] = b[j++] | (b[j++] << 1) | (b[j++] << 2) | (b[j++] << 3);
|
||||
res[i] |= (b[j++] << 4) | (b[j++] << 5) | (b[j++] << 6) | (b[j++] << 7);
|
||||
}
|
||||
return res;
|
||||
},
|
||||
};
|
||||
/**
|
||||
* Binary FPE-FF1 wrapper over byte arrays.
|
||||
* @param key - AES key bytes.
|
||||
* @param tweak - Optional tweak bytes.
|
||||
* @returns Encrypt/decrypt helpers over byte arrays.
|
||||
* @example
|
||||
* Encrypts raw bytes through FF1's binary alphabet wrapper with a fresh AES key.
|
||||
*
|
||||
* ```ts
|
||||
* import { BinaryFF1 } from '@noble/ciphers/ff1.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const ff1 = BinaryFF1(key);
|
||||
* ff1.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export function BinaryFF1(key, tweak = EMPTY_BUF) {
|
||||
const ff1 = FF1(2, key, tweak);
|
||||
return {
|
||||
encrypt: (x) => binLE.decode(ff1.encrypt(binLE.encode(x))),
|
||||
decrypt: (x) => binLE.decode(ff1.decrypt(binLE.encode(x))),
|
||||
};
|
||||
}
|
||||
//# sourceMappingURL=ff1.js.map
|
||||
1
node_modules/@noble/ciphers/ff1.js.map
generated
vendored
Normal file
1
node_modules/@noble/ciphers/ff1.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
2
node_modules/@noble/ciphers/index.d.ts
generated
vendored
Normal file
2
node_modules/@noble/ciphers/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
export {};
|
||||
//# sourceMappingURL=index.d.ts.map
|
||||
1
node_modules/@noble/ciphers/index.d.ts.map
generated
vendored
Normal file
1
node_modules/@noble/ciphers/index.d.ts.map
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":""}
|
||||
27
node_modules/@noble/ciphers/index.js
generated
vendored
Normal file
27
node_modules/@noble/ciphers/index.js
generated
vendored
Normal file
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* Audited & minimal JS implementation of Salsa20, ChaCha and AES. Check out individual modules.
|
||||
* @example
|
||||
```js
|
||||
import { gcm, aessiv } from '@noble/ciphers/aes.js';
|
||||
import { xsalsa20poly1305 } from '@noble/ciphers/salsa.js';
|
||||
import { secretbox } from '@noble/ciphers/salsa.js'; // == xsalsa20poly1305
|
||||
import { chacha20poly1305, xchacha20poly1305 } from '@noble/ciphers/chacha.js';
|
||||
|
||||
// Unauthenticated encryption: make sure to use HMAC or similar
|
||||
import { ctr, cfb, cbc, ecb } from '@noble/ciphers/aes.js';
|
||||
import { salsa20, xsalsa20 } from '@noble/ciphers/salsa.js';
|
||||
import { chacha20, xchacha20, chacha8, chacha12 } from '@noble/ciphers/chacha.js';
|
||||
|
||||
// KW
|
||||
import { aeskw, aeskwp } from '@noble/ciphers/aes.js';
|
||||
|
||||
// Utilities
|
||||
import { managedNonce, randomBytes, bytesToHex, hexToBytes } from '@noble/ciphers/utils.js';
|
||||
import { poly1305 } from '@noble/ciphers/_poly1305.js';
|
||||
import { ghash, polyval } from '@noble/ciphers/_polyval.js';
|
||||
```
|
||||
* @module
|
||||
*/
|
||||
throw new Error('root module cannot be imported: import submodules instead. Check out README');
|
||||
export {};
|
||||
//# sourceMappingURL=index.js.map
|
||||
1
node_modules/@noble/ciphers/index.js.map
generated
vendored
Normal file
1
node_modules/@noble/ciphers/index.js.map
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"index.js","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,IAAI,KAAK,CAAC,6EAA6E,CAAC,CAAC"}
|
||||
85
node_modules/@noble/ciphers/package.json
generated
vendored
Normal file
85
node_modules/@noble/ciphers/package.json
generated
vendored
Normal file
@@ -0,0 +1,85 @@
|
||||
{
|
||||
"name": "@noble/ciphers",
|
||||
"version": "2.2.0",
|
||||
"description": "Audited & minimal JS implementation of Salsa20, ChaCha and AES",
|
||||
"files": [
|
||||
"src",
|
||||
"*.js",
|
||||
"*.js.map",
|
||||
"*.d.ts",
|
||||
"*.d.ts.map"
|
||||
],
|
||||
"devDependencies": {
|
||||
"@paulmillr/jsbt": "0.5.0",
|
||||
"@scure/base": "2.0.0",
|
||||
"@types/node": "25.3.0",
|
||||
"fast-check": "4.2.0",
|
||||
"prettier": "3.6.2",
|
||||
"typescript": "6.0.2"
|
||||
},
|
||||
"scripts": {
|
||||
"bench": "node test/benchmark/noble.ts",
|
||||
"bench:compare": "cd test/benchmark; npm install; node compare.ts",
|
||||
"build": "tsc",
|
||||
"build:release": "npx --no @paulmillr/jsbt esbuild test/build",
|
||||
"check": "npm run check:readme && npm run check:treeshake && npm run check:jsdoc",
|
||||
"check:readme": "npx --no @paulmillr/jsbt readme package.json",
|
||||
"check:treeshake": "npx --no @paulmillr/jsbt treeshake package.json test/build/out-treeshake",
|
||||
"check:jsdoc": "npx --no @paulmillr/jsbt tsdoc package.json",
|
||||
"build:clean": "rm *.{js,js.map,d.ts,d.ts.map} 2> /dev/null",
|
||||
"format": "prettier --write 'src/**/*.{js,ts}' 'test/**/*.{js,ts,mjs}'",
|
||||
"test": "node test/index.ts",
|
||||
"test:bun": "bun test/index.ts",
|
||||
"test:deno": "deno --allow-env --allow-read test/index.ts",
|
||||
"test:node20": "cd test; npx tsc; node compiled/test/index.js",
|
||||
"test:slow": "node test/crosstest.test.ts slow"
|
||||
},
|
||||
"exports": {
|
||||
".": "./index.js",
|
||||
"./_arx.js": "./_arx.js",
|
||||
"./_poly1305.js": "./_poly1305.js",
|
||||
"./_polyval.js": "./_polyval.js",
|
||||
"./aes.js": "./aes.js",
|
||||
"./chacha.js": "./chacha.js",
|
||||
"./ff1.js": "./ff1.js",
|
||||
"./salsa.js": "./salsa.js",
|
||||
"./utils.js": "./utils.js",
|
||||
"./webcrypto.js": "./webcrypto.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 20.19.0"
|
||||
},
|
||||
"keywords": [
|
||||
"salsa20",
|
||||
"chacha",
|
||||
"aes",
|
||||
"cryptography",
|
||||
"crypto",
|
||||
"noble",
|
||||
"cipher",
|
||||
"ciphers",
|
||||
"xsalsa20",
|
||||
"xchacha20",
|
||||
"poly1305",
|
||||
"xsalsa20poly1305",
|
||||
"chacha20poly1305",
|
||||
"xchacha20poly1305",
|
||||
"secretbox",
|
||||
"rijndael",
|
||||
"siv",
|
||||
"ff1"
|
||||
],
|
||||
"homepage": "https://paulmillr.com/noble/",
|
||||
"funding": "https://paulmillr.com/funding/",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/paulmillr/noble-ciphers.git"
|
||||
},
|
||||
"type": "module",
|
||||
"main": "index.js",
|
||||
"module": "index.js",
|
||||
"types": "index.d.ts",
|
||||
"sideEffects": false,
|
||||
"author": "Paul Miller (https://paulmillr.com)",
|
||||
"license": "MIT"
|
||||
}
|
||||
115
node_modules/@noble/ciphers/salsa.d.ts
generated
vendored
Normal file
115
node_modules/@noble/ciphers/salsa.d.ts
generated
vendored
Normal file
@@ -0,0 +1,115 @@
|
||||
import { type ARXCipher, type TArg, type TRet, type XorStream } from './utils.ts';
|
||||
/**
|
||||
* hsalsa hashes key and nonce-prefix words into the 32-byte subkey used by XSalsa20.
|
||||
* Identical to `hsalsa_small`.
|
||||
* Need to find a way to merge it with `salsaCore` without 25% performance hit.
|
||||
* @param s - Sigma constants as 32-bit words.
|
||||
* @param k - Key words.
|
||||
* @param i - Nonce-prefix words.
|
||||
* @param out - Output buffer for the derived subkey.
|
||||
* @example
|
||||
* Derives the XSalsa20 subkey from sigma, key, and nonce-prefix words.
|
||||
*
|
||||
* ```ts
|
||||
* const sigma = new Uint32Array(4);
|
||||
* const key = new Uint32Array(8);
|
||||
* const nonce = new Uint32Array(4);
|
||||
* const out = new Uint32Array(8);
|
||||
* hsalsa(sigma, key, nonce, out);
|
||||
* ```
|
||||
*/
|
||||
export declare function hsalsa(s: TArg<Uint32Array>, k: TArg<Uint32Array>, i: TArg<Uint32Array>, out: TArg<Uint32Array>): void;
|
||||
/**
|
||||
* Salsa20 from original paper. 8-byte nonce.
|
||||
* With smaller nonce, it's not safe to make it random (CSPRNG), due to collision chance.
|
||||
* @param key - 16-byte or 32-byte key.
|
||||
* @param nonce - 8-byte nonce.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Initial block counter.
|
||||
* Only the low 32 bits of Salsa20's 64-bit counter state are exposed here;
|
||||
* the high word stays zero and the implementation still caps the public
|
||||
* value to 32 bits.
|
||||
* @returns Encrypted or decrypted bytes.
|
||||
* @example
|
||||
* Encrypts bytes with the original 8-byte-nonce Salsa20 stream cipher.
|
||||
*
|
||||
* ```ts
|
||||
* import { salsa20 } from '@noble/ciphers/salsa.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(8);
|
||||
* salsa20(key, nonce, new Uint8Array([1, 2, 3, 4]));
|
||||
* ```
|
||||
*/
|
||||
export declare const salsa20: TRet<XorStream>;
|
||||
/**
|
||||
* XSalsa20 extended-nonce salsa.
|
||||
* With 24-byte nonce, it's safe to make it random (CSPRNG).
|
||||
* @param key - 32-byte key.
|
||||
* This XSalsa20 wrapper does not enable Salsa20's 16-byte legacy key mode.
|
||||
* @param nonce - 24-byte nonce.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Initial block counter.
|
||||
* @returns Encrypted or decrypted bytes.
|
||||
* @example
|
||||
* Encrypts bytes with XSalsa20 and a random 24-byte nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { xsalsa20 } from '@noble/ciphers/salsa.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(24);
|
||||
* xsalsa20(key, nonce, new Uint8Array([1, 2, 3, 4]));
|
||||
* ```
|
||||
*/
|
||||
export declare const xsalsa20: TRet<XorStream>;
|
||||
/**
|
||||
* xsalsa20-poly1305 eXtended-nonce (24 bytes) salsa.
|
||||
* With 24-byte nonce, it's safe to make it random (CSPRNG).
|
||||
* Also known as `secretbox` from libsodium / nacl.
|
||||
* No AAD input is supported here. Caller-provided `output` buffers for
|
||||
* `encrypt()` / `decrypt()` must be `input.length + 32` bytes because the
|
||||
* implementation uses a 32-byte leading scratch area before returning `+16`.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 24-byte nonce.
|
||||
* @param AAD - Must be omitted; XSalsa20-Poly1305 secretbox does not support associated data.
|
||||
* @returns AEAD cipher instance.
|
||||
* @example
|
||||
* Encrypts and authenticates plaintext with XSalsa20-Poly1305.
|
||||
*
|
||||
* ```ts
|
||||
* import { xsalsa20poly1305 } from '@noble/ciphers/salsa.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(24);
|
||||
* const cipher = xsalsa20poly1305(key, nonce);
|
||||
* cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export declare const xsalsa20poly1305: TRet<ARXCipher>;
|
||||
/**
|
||||
* Alias to `xsalsa20poly1305`, for compatibility with libsodium / nacl.
|
||||
* Check out {@link https://github.com/serenity-kit/noble-sodium | noble-sodium}
|
||||
* for `crypto_box`.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 24-byte nonce.
|
||||
* @returns Wrapper with `seal()` and `open()` helpers.
|
||||
* @example
|
||||
* Uses the libsodium-style `seal()` and `open()` wrapper.
|
||||
*
|
||||
* ```ts
|
||||
* import { secretbox } from '@noble/ciphers/salsa.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(24);
|
||||
* const box = secretbox(key, nonce);
|
||||
* box.seal(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export declare function secretbox(key: TArg<Uint8Array>, nonce: TArg<Uint8Array>): TRet<{
|
||||
seal: (plaintext: TArg<Uint8Array>, output?: TArg<Uint8Array>) => TRet<Uint8Array>;
|
||||
open: (ciphertext: TArg<Uint8Array>, output?: TArg<Uint8Array>) => TRet<Uint8Array>;
|
||||
}>;
|
||||
//# sourceMappingURL=salsa.d.ts.map
|
||||
1
node_modules/@noble/ciphers/salsa.d.ts.map
generated
vendored
Normal file
1
node_modules/@noble/ciphers/salsa.d.ts.map
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"salsa.d.ts","sourceRoot":"","sources":["src/salsa.ts"],"names":[],"mappings":"AAqBA,OAAO,EAQL,KAAK,SAAS,EAEd,KAAK,IAAI,EACT,KAAK,IAAI,EACT,KAAK,SAAS,EACf,MAAM,YAAY,CAAC;AAuHpB;;;;;;;;;;;;;;;;;;GAkBG;AAEH,wBAAgB,MAAM,CACpB,CAAC,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,GAAG,EAAE,IAAI,CAAC,WAAW,CAAC,GACvF,IAAI,CA8BN;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,eAAO,MAAM,OAAO,EAAE,IAAI,CAAC,SAAS,CAGlC,CAAC;AAEH;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,eAAO,MAAM,QAAQ,EAAE,IAAI,CAAC,SAAS,CAGnC,CAAC;AAEH;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,eAAO,MAAM,gBAAgB,EAAE,IAAI,CAAC,SAAS,CAwD5C,CAAC;AAEF;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,SAAS,CACvB,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EACrB,KAAK,EAAE,IAAI,CAAC,UAAU,CAAC,GACtB,IAAI,CAAC;IACN,IAAI,EAAE,CAAC,SAAS,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC,EAAE,IAAI,CAAC,UAAU,CAAC,KAAK,IAAI,CAAC,UAAU,CAAC,CAAC;IACnF,IAAI,EAAE,CAAC,UAAU,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC,EAAE,IAAI,CAAC,UAAU,CAAC,KAAK,IAAI,CAAC,UAAU,CAAC,CAAC;CACrF,CAAC,CAMD"}
|
||||
371
node_modules/@noble/ciphers/salsa.js
generated
vendored
Normal file
371
node_modules/@noble/ciphers/salsa.js
generated
vendored
Normal file
@@ -0,0 +1,371 @@
|
||||
/**
|
||||
* Salsa20 stream cipher, released in 2005.
|
||||
* Salsa's goal was to implement AES replacement that does not rely on S-Boxes,
|
||||
* which are hard to implement in a constant-time manner.
|
||||
* Salsa20 is usually faster than AES, a big deal on slow, budget mobile phones.
|
||||
*
|
||||
* - {@link https://cr.yp.to/snuffle/xsalsa-20110204.pdf | XSalsa20},
|
||||
* extended-nonce
|
||||
* variant was released in 2008. It extends Salsa20's 64-bit nonce to 192 bits,
|
||||
* and became safe to be picked at random.
|
||||
* - Nacl / Libsodium popularized term "secretbox", - which is just xsalsa20poly1305.
|
||||
* We provide the alias and corresponding seal / open methods.
|
||||
* "crypto_box" and "sealedbox" are available in package
|
||||
* {@link https://github.com/serenity-kit/noble-sodium | noble-sodium}.
|
||||
* - Check out
|
||||
* {@link https://cr.yp.to/snuffle/salsafamily-20071225.pdf | PDF}
|
||||
* and {@link https://cr.yp.to/snuffle.html | website}.
|
||||
* @module
|
||||
*/
|
||||
import { createCipher, rotl } from "./_arx.js";
|
||||
import { poly1305 } from "./_poly1305.js";
|
||||
import { abytes, clean, equalBytes, getOutput, swap32IfBE, swap8IfBE, wrapCipher, } from "./utils.js";
|
||||
/**
|
||||
* Salsa20 core function. It is implemented twice:
|
||||
* 1. Simple loop (salsaCore_small, hsalsa_small)
|
||||
* 2. Unrolled loop (salsaCore, hsalsa) - 4x faster, but larger & harder to read
|
||||
* The specific implementation is selected in `createCipher` below.
|
||||
* Performance numbers for 1MB inputs:
|
||||
* * default x 779 ops/sec @ 1ms/op
|
||||
* * if salsa+hsalsa are merged x 459 ops/sec @ 2ms/op
|
||||
* * small x 132 ops/sec @ 7ms/op
|
||||
*/
|
||||
/** RFC 7914 §3 Salsa20/8 core quarter-round on words a, b, c, d. */
|
||||
function salsaQR(x, a, b, c, d) {
|
||||
x[b] ^= rotl((x[a] + x[d]) | 0, 7);
|
||||
x[c] ^= rotl((x[b] + x[a]) | 0, 9);
|
||||
x[d] ^= rotl((x[c] + x[b]) | 0, 13);
|
||||
x[a] ^= rotl((x[d] + x[c]) | 0, 18);
|
||||
}
|
||||
/** RFC 7914 §3 double-round schedule: four column rounds, then four row rounds. */
|
||||
function salsaRound(x, rounds = 20) {
|
||||
for (let r = 0; r < rounds; r += 2) {
|
||||
salsaQR(x, 0, 4, 8, 12);
|
||||
salsaQR(x, 5, 9, 13, 1);
|
||||
salsaQR(x, 10, 14, 2, 6);
|
||||
salsaQR(x, 15, 3, 7, 11);
|
||||
salsaQR(x, 0, 1, 2, 3);
|
||||
salsaQR(x, 5, 6, 7, 4);
|
||||
salsaQR(x, 10, 11, 8, 9);
|
||||
salsaQR(x, 15, 12, 13, 14);
|
||||
}
|
||||
}
|
||||
// Shared scratch for the unused auditability helper below; it would be
|
||||
// non-reentrant under overlapping/nested calls, but current code doesn't invoke it.
|
||||
const stmp = /* @__PURE__ */ new Uint32Array(16);
|
||||
/** Small version of salsa without loop unrolling. Unused, provided for auditability. */
|
||||
// prettier-ignore
|
||||
function salsa(s, k, i, out, isHSalsa = true, rounds = 20) {
|
||||
// Create initial array using common pattern
|
||||
const y = Uint32Array.from([
|
||||
s[0], k[0], k[1], k[2], // "expa" Key Key Key
|
||||
k[3], s[1], i[0], i[1], // Key "nd 3" Nonce Nonce
|
||||
i[2], i[3], s[2], k[4], // Pos. Pos. "2-by" Key
|
||||
k[5], k[6], k[7], s[3], // Key Key Key "te k"
|
||||
]);
|
||||
const x = stmp;
|
||||
x.set(y);
|
||||
// const x = y.slice();
|
||||
salsaRound(x, rounds);
|
||||
// hsalsa extracts 8 specific words for the 32-byte subkey; salsa adds the original state.
|
||||
if (isHSalsa) {
|
||||
const xindexes = [0, 5, 10, 15, 6, 7, 8, 9];
|
||||
for (let i = 0; i < 8; i++)
|
||||
out[i] = x[xindexes[i]];
|
||||
}
|
||||
else {
|
||||
for (let i = 0; i < 16; i++)
|
||||
out[i] = (y[i] + x[i]) | 0;
|
||||
}
|
||||
}
|
||||
/** Identical to `salsaCore`. Unused. */
|
||||
// @ts-ignore
|
||||
const salsaCore_small = (s, k, n, out, cnt, rounds) => salsa(s, k, Uint32Array.from([n[0], n[1], cnt, 0]), out, false, rounds);
|
||||
/** Identical to `hsalsa`. Unused. */
|
||||
// @ts-ignore
|
||||
const hsalsa_small = salsa;
|
||||
/** Identical to `salsaCore_small`. Uses only the low 32 bits of Salsa20's 64-bit counter state. */
|
||||
// prettier-ignore
|
||||
function salsaCore(s, k, n, out, cnt, rounds = 20) {
|
||||
// Public wrappers expose only the low 32 bits of Salsa20's 64-bit counter; y09 stays zero.
|
||||
// Based on {@link https://cr.yp.to/salsa20.html | the Salsa20 reference page}.
|
||||
let y00 = s[0], y01 = k[0], y02 = k[1], y03 = k[2], // "expa" Key Key Key
|
||||
y04 = k[3], y05 = s[1], y06 = n[0], y07 = n[1], // Key "nd 3" Nonce Nonce
|
||||
y08 = cnt, y09 = 0, y10 = s[2], y11 = k[4], // Pos. Pos. "2-by" Key
|
||||
y12 = k[5], y13 = k[6], y14 = k[7], y15 = s[3]; // Key Key Key "te k"
|
||||
// Save state to temporary variables
|
||||
let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;
|
||||
for (let r = 0; r < rounds; r += 2) {
|
||||
x04 ^= rotl(x00 + x12 | 0, 7);
|
||||
x08 ^= rotl(x04 + x00 | 0, 9);
|
||||
x12 ^= rotl(x08 + x04 | 0, 13);
|
||||
x00 ^= rotl(x12 + x08 | 0, 18);
|
||||
x09 ^= rotl(x05 + x01 | 0, 7);
|
||||
x13 ^= rotl(x09 + x05 | 0, 9);
|
||||
x01 ^= rotl(x13 + x09 | 0, 13);
|
||||
x05 ^= rotl(x01 + x13 | 0, 18);
|
||||
x14 ^= rotl(x10 + x06 | 0, 7);
|
||||
x02 ^= rotl(x14 + x10 | 0, 9);
|
||||
x06 ^= rotl(x02 + x14 | 0, 13);
|
||||
x10 ^= rotl(x06 + x02 | 0, 18);
|
||||
x03 ^= rotl(x15 + x11 | 0, 7);
|
||||
x07 ^= rotl(x03 + x15 | 0, 9);
|
||||
x11 ^= rotl(x07 + x03 | 0, 13);
|
||||
x15 ^= rotl(x11 + x07 | 0, 18);
|
||||
x01 ^= rotl(x00 + x03 | 0, 7);
|
||||
x02 ^= rotl(x01 + x00 | 0, 9);
|
||||
x03 ^= rotl(x02 + x01 | 0, 13);
|
||||
x00 ^= rotl(x03 + x02 | 0, 18);
|
||||
x06 ^= rotl(x05 + x04 | 0, 7);
|
||||
x07 ^= rotl(x06 + x05 | 0, 9);
|
||||
x04 ^= rotl(x07 + x06 | 0, 13);
|
||||
x05 ^= rotl(x04 + x07 | 0, 18);
|
||||
x11 ^= rotl(x10 + x09 | 0, 7);
|
||||
x08 ^= rotl(x11 + x10 | 0, 9);
|
||||
x09 ^= rotl(x08 + x11 | 0, 13);
|
||||
x10 ^= rotl(x09 + x08 | 0, 18);
|
||||
x12 ^= rotl(x15 + x14 | 0, 7);
|
||||
x13 ^= rotl(x12 + x15 | 0, 9);
|
||||
x14 ^= rotl(x13 + x12 | 0, 13);
|
||||
x15 ^= rotl(x14 + x13 | 0, 18);
|
||||
}
|
||||
// Write output
|
||||
let oi = 0;
|
||||
out[oi++] = (y00 + x00) | 0;
|
||||
out[oi++] = (y01 + x01) | 0;
|
||||
out[oi++] = (y02 + x02) | 0;
|
||||
out[oi++] = (y03 + x03) | 0;
|
||||
out[oi++] = (y04 + x04) | 0;
|
||||
out[oi++] = (y05 + x05) | 0;
|
||||
out[oi++] = (y06 + x06) | 0;
|
||||
out[oi++] = (y07 + x07) | 0;
|
||||
out[oi++] = (y08 + x08) | 0;
|
||||
out[oi++] = (y09 + x09) | 0;
|
||||
out[oi++] = (y10 + x10) | 0;
|
||||
out[oi++] = (y11 + x11) | 0;
|
||||
out[oi++] = (y12 + x12) | 0;
|
||||
out[oi++] = (y13 + x13) | 0;
|
||||
out[oi++] = (y14 + x14) | 0;
|
||||
out[oi++] = (y15 + x15) | 0;
|
||||
}
|
||||
/**
|
||||
* hsalsa hashes key and nonce-prefix words into the 32-byte subkey used by XSalsa20.
|
||||
* Identical to `hsalsa_small`.
|
||||
* Need to find a way to merge it with `salsaCore` without 25% performance hit.
|
||||
* @param s - Sigma constants as 32-bit words.
|
||||
* @param k - Key words.
|
||||
* @param i - Nonce-prefix words.
|
||||
* @param out - Output buffer for the derived subkey.
|
||||
* @example
|
||||
* Derives the XSalsa20 subkey from sigma, key, and nonce-prefix words.
|
||||
*
|
||||
* ```ts
|
||||
* const sigma = new Uint32Array(4);
|
||||
* const key = new Uint32Array(8);
|
||||
* const nonce = new Uint32Array(4);
|
||||
* const out = new Uint32Array(8);
|
||||
* hsalsa(sigma, key, nonce, out);
|
||||
* ```
|
||||
*/
|
||||
// prettier-ignore
|
||||
export function hsalsa(s, k, i, out) {
|
||||
let x00 = swap8IfBE(s[0]), x01 = swap8IfBE(k[0]), x02 = swap8IfBE(k[1]), x03 = swap8IfBE(k[2]), x04 = swap8IfBE(k[3]), x05 = swap8IfBE(s[1]), x06 = swap8IfBE(i[0]), x07 = swap8IfBE(i[1]), x08 = swap8IfBE(i[2]), x09 = swap8IfBE(i[3]), x10 = swap8IfBE(s[2]), x11 = swap8IfBE(k[4]), x12 = swap8IfBE(k[5]), x13 = swap8IfBE(k[6]), x14 = swap8IfBE(k[7]), x15 = swap8IfBE(s[3]);
|
||||
for (let r = 0; r < 20; r += 2) {
|
||||
x04 ^= rotl(x00 + x12 | 0, 7);
|
||||
x08 ^= rotl(x04 + x00 | 0, 9);
|
||||
x12 ^= rotl(x08 + x04 | 0, 13);
|
||||
x00 ^= rotl(x12 + x08 | 0, 18);
|
||||
x09 ^= rotl(x05 + x01 | 0, 7);
|
||||
x13 ^= rotl(x09 + x05 | 0, 9);
|
||||
x01 ^= rotl(x13 + x09 | 0, 13);
|
||||
x05 ^= rotl(x01 + x13 | 0, 18);
|
||||
x14 ^= rotl(x10 + x06 | 0, 7);
|
||||
x02 ^= rotl(x14 + x10 | 0, 9);
|
||||
x06 ^= rotl(x02 + x14 | 0, 13);
|
||||
x10 ^= rotl(x06 + x02 | 0, 18);
|
||||
x03 ^= rotl(x15 + x11 | 0, 7);
|
||||
x07 ^= rotl(x03 + x15 | 0, 9);
|
||||
x11 ^= rotl(x07 + x03 | 0, 13);
|
||||
x15 ^= rotl(x11 + x07 | 0, 18);
|
||||
x01 ^= rotl(x00 + x03 | 0, 7);
|
||||
x02 ^= rotl(x01 + x00 | 0, 9);
|
||||
x03 ^= rotl(x02 + x01 | 0, 13);
|
||||
x00 ^= rotl(x03 + x02 | 0, 18);
|
||||
x06 ^= rotl(x05 + x04 | 0, 7);
|
||||
x07 ^= rotl(x06 + x05 | 0, 9);
|
||||
x04 ^= rotl(x07 + x06 | 0, 13);
|
||||
x05 ^= rotl(x04 + x07 | 0, 18);
|
||||
x11 ^= rotl(x10 + x09 | 0, 7);
|
||||
x08 ^= rotl(x11 + x10 | 0, 9);
|
||||
x09 ^= rotl(x08 + x11 | 0, 13);
|
||||
x10 ^= rotl(x09 + x08 | 0, 18);
|
||||
x12 ^= rotl(x15 + x14 | 0, 7);
|
||||
x13 ^= rotl(x12 + x15 | 0, 9);
|
||||
x14 ^= rotl(x13 + x12 | 0, 13);
|
||||
x15 ^= rotl(x14 + x13 | 0, 18);
|
||||
}
|
||||
let oi = 0;
|
||||
// XSalsa20 takes words 0,5,10,15 and 6,7,8,9 as the 32-byte subkey material.
|
||||
out[oi++] = x00;
|
||||
out[oi++] = x05;
|
||||
out[oi++] = x10;
|
||||
out[oi++] = x15;
|
||||
out[oi++] = x06;
|
||||
out[oi++] = x07;
|
||||
out[oi++] = x08;
|
||||
out[oi++] = x09;
|
||||
swap32IfBE(out);
|
||||
}
|
||||
/**
|
||||
* Salsa20 from original paper. 8-byte nonce.
|
||||
* With smaller nonce, it's not safe to make it random (CSPRNG), due to collision chance.
|
||||
* @param key - 16-byte or 32-byte key.
|
||||
* @param nonce - 8-byte nonce.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Initial block counter.
|
||||
* Only the low 32 bits of Salsa20's 64-bit counter state are exposed here;
|
||||
* the high word stays zero and the implementation still caps the public
|
||||
* value to 32 bits.
|
||||
* @returns Encrypted or decrypted bytes.
|
||||
* @example
|
||||
* Encrypts bytes with the original 8-byte-nonce Salsa20 stream cipher.
|
||||
*
|
||||
* ```ts
|
||||
* import { salsa20 } from '@noble/ciphers/salsa.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(8);
|
||||
* salsa20(key, nonce, new Uint8Array([1, 2, 3, 4]));
|
||||
* ```
|
||||
*/
|
||||
export const salsa20 = /* @__PURE__ */ createCipher(salsaCore, {
|
||||
allowShortKeys: true,
|
||||
counterRight: true,
|
||||
});
|
||||
/**
|
||||
* XSalsa20 extended-nonce salsa.
|
||||
* With 24-byte nonce, it's safe to make it random (CSPRNG).
|
||||
* @param key - 32-byte key.
|
||||
* This XSalsa20 wrapper does not enable Salsa20's 16-byte legacy key mode.
|
||||
* @param nonce - 24-byte nonce.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Initial block counter.
|
||||
* @returns Encrypted or decrypted bytes.
|
||||
* @example
|
||||
* Encrypts bytes with XSalsa20 and a random 24-byte nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { xsalsa20 } from '@noble/ciphers/salsa.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(24);
|
||||
* xsalsa20(key, nonce, new Uint8Array([1, 2, 3, 4]));
|
||||
* ```
|
||||
*/
|
||||
export const xsalsa20 = /* @__PURE__ */ createCipher(salsaCore, {
|
||||
counterRight: true,
|
||||
extendNonceFn: hsalsa,
|
||||
});
|
||||
/**
|
||||
* xsalsa20-poly1305 eXtended-nonce (24 bytes) salsa.
|
||||
* With 24-byte nonce, it's safe to make it random (CSPRNG).
|
||||
* Also known as `secretbox` from libsodium / nacl.
|
||||
* No AAD input is supported here. Caller-provided `output` buffers for
|
||||
* `encrypt()` / `decrypt()` must be `input.length + 32` bytes because the
|
||||
* implementation uses a 32-byte leading scratch area before returning `+16`.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 24-byte nonce.
|
||||
* @param AAD - Must be omitted; XSalsa20-Poly1305 secretbox does not support associated data.
|
||||
* @returns AEAD cipher instance.
|
||||
* @example
|
||||
* Encrypts and authenticates plaintext with XSalsa20-Poly1305.
|
||||
*
|
||||
* ```ts
|
||||
* import { xsalsa20poly1305 } from '@noble/ciphers/salsa.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(24);
|
||||
* const cipher = xsalsa20poly1305(key, nonce);
|
||||
* cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export const xsalsa20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 24, tagLength: 16 }, (key, nonce) => {
|
||||
// This borrows caller key/nonce buffers by reference; mutating them after construction changes
|
||||
// later encrypt/decrypt outputs.
|
||||
return {
|
||||
encrypt(plaintext, output) {
|
||||
// xsalsa20poly1305 optimizes by calculating auth key during the same call as encryption.
|
||||
// Unfortunately, makes it hard to separate tag calculation & encryption itself,
|
||||
// because 32 bytes is half-block of 64-byte salsa.
|
||||
// Need 32 extra bytes up front for the auth-key scratch area described above.
|
||||
output = getOutput(plaintext.length + 32, output, false);
|
||||
// output[0..32] = Poly1305 auth key, output[32..] = plaintext then ciphertext.
|
||||
const authKey = output.subarray(0, 32);
|
||||
const ciphPlaintext = output.subarray(32);
|
||||
output.set(plaintext, 32);
|
||||
// authKey is produced by xoring the first 32 bytes with zeros.
|
||||
clean(authKey);
|
||||
// output = stream ^ output; authKey = stream ^ zeros(32)
|
||||
xsalsa20(key, nonce, output, output);
|
||||
const tag = poly1305(ciphPlaintext, authKey);
|
||||
output.set(tag, 16);
|
||||
// Clean up auth-key remnants and the temporary tag copy.
|
||||
clean(output.subarray(0, 16), tag);
|
||||
// Return output[16..].
|
||||
return output.subarray(16);
|
||||
},
|
||||
decrypt(ciphertext, output) {
|
||||
// tmp part passed tag ciphertext
|
||||
// [0..32] [32..48] [48..]
|
||||
// Authenticate the ciphertext before decrypting it; on tag failure the scratch/output
|
||||
// buffer may already contain copied ciphertext and derived auth-key material.
|
||||
abytes(ciphertext);
|
||||
output = getOutput(ciphertext.length + 32, output, false);
|
||||
// output[0..32] is auth-key scratch, output[32..48] is passed tag,
|
||||
// output[48..] is ciphertext then plaintext.
|
||||
const tmp = output.subarray(0, 32);
|
||||
const passedTag = output.subarray(32, 48);
|
||||
const ciphPlaintext = output.subarray(48);
|
||||
output.set(ciphertext, 32);
|
||||
// authKey is produced by xoring the scratch area with zeros.
|
||||
clean(tmp);
|
||||
const authKey = xsalsa20(key, nonce, tmp, tmp);
|
||||
const tag = poly1305(ciphPlaintext, authKey);
|
||||
if (!equalBytes(passedTag, tag)) {
|
||||
clean(output);
|
||||
throw new Error('invalid tag');
|
||||
}
|
||||
// output = stream ^ output[16..]
|
||||
xsalsa20(key, nonce, output.subarray(16), output.subarray(16));
|
||||
clean(tmp, passedTag, tag);
|
||||
// Return output[48..], skipping zeroized output[0..48].
|
||||
return ciphPlaintext;
|
||||
},
|
||||
};
|
||||
});
|
||||
/**
|
||||
* Alias to `xsalsa20poly1305`, for compatibility with libsodium / nacl.
|
||||
* Check out {@link https://github.com/serenity-kit/noble-sodium | noble-sodium}
|
||||
* for `crypto_box`.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 24-byte nonce.
|
||||
* @returns Wrapper with `seal()` and `open()` helpers.
|
||||
* @example
|
||||
* Uses the libsodium-style `seal()` and `open()` wrapper.
|
||||
*
|
||||
* ```ts
|
||||
* import { secretbox } from '@noble/ciphers/salsa.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(24);
|
||||
* const box = secretbox(key, nonce);
|
||||
* box.seal(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export function secretbox(key, nonce) {
|
||||
const xs = xsalsa20poly1305(key, nonce);
|
||||
return { seal: xs.encrypt, open: xs.decrypt };
|
||||
}
|
||||
//# sourceMappingURL=salsa.js.map
|
||||
1
node_modules/@noble/ciphers/salsa.js.map
generated
vendored
Normal file
1
node_modules/@noble/ciphers/salsa.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
499
node_modules/@noble/ciphers/src/_arx.ts
generated
vendored
Normal file
499
node_modules/@noble/ciphers/src/_arx.ts
generated
vendored
Normal file
@@ -0,0 +1,499 @@
|
||||
/**
|
||||
* Basic utils for ARX (add-rotate-xor) salsa and chacha ciphers.
|
||||
|
||||
RFC8439 requires multi-step cipher stream, where
|
||||
authKey starts with counter: 0, actual msg with counter: 1.
|
||||
|
||||
For this, we need a way to re-use nonce / counter:
|
||||
|
||||
const counter = new Uint8Array(4);
|
||||
chacha(..., counter, ...); // counter is now 1
|
||||
chacha(..., counter, ...); // counter is now 2
|
||||
|
||||
This is complicated:
|
||||
|
||||
- 32-bit counters are enough, no need for 64-bit: max ArrayBuffer size in JS is 4GB
|
||||
- Original papers don't allow mutating counters
|
||||
- Counter overflow is undefined [^1]
|
||||
- Idea A: allow providing (nonce | counter) instead of just nonce, re-use it
|
||||
- Caveat: Cannot be re-used through all cases:
|
||||
- * chacha has (counter | nonce)
|
||||
- * xchacha has (nonce16 | counter | nonce16)
|
||||
- Idea B: separate nonce / counter and provide separate API for counter re-use
|
||||
- Caveat: there are different counter sizes depending on an algorithm.
|
||||
- salsa & chacha also differ in structures of key & sigma:
|
||||
salsa20: s[0] | k(4) | s[1] | nonce(2) | cnt(2) | s[2] | k(4) | s[3]
|
||||
chacha: s(4) | k(8) | cnt(1) | nonce(3)
|
||||
chacha20orig: s(4) | k(8) | cnt(2) | nonce(2)
|
||||
- Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)`
|
||||
- Caveat: we can't re-use counter array
|
||||
|
||||
xchacha uses the subkey and remaining 8 byte nonce with ChaCha20 as normal
|
||||
(prefixed by 4 NUL bytes, since RFC8439 specifies a 12-byte nonce).
|
||||
Counter overflow is undefined; see {@link https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/ | the CFRG thread}.
|
||||
Current noble policy is strict non-wrap for the shared 32-bit counter path:
|
||||
exported ARX ciphers reject initial `0xffffffff` and stop before any implicit
|
||||
wrap back to zero.
|
||||
See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2 | the XChaCha appendix} for the extended-nonce construction.
|
||||
|
||||
* @module
|
||||
*/
|
||||
import {
|
||||
type PRG,
|
||||
type TArg,
|
||||
type TRet,
|
||||
type XorStream,
|
||||
abool,
|
||||
abytes,
|
||||
anumber,
|
||||
checkOpts,
|
||||
clean,
|
||||
copyBytes,
|
||||
getOutput,
|
||||
isAligned32,
|
||||
isLE,
|
||||
randomBytes,
|
||||
swap32IfBE,
|
||||
u32,
|
||||
} from './utils.ts';
|
||||
|
||||
// Replaces `TextEncoder` for ASCII literals, which is enough for sigma constants.
|
||||
// Non-ASCII input would not match UTF-8 `TextEncoder` output.
|
||||
const encodeStr = (str: string) => Uint8Array.from(str.split(''), (c) => c.charCodeAt(0));
|
||||
// Raw `createCipher(...)` exports consume these native-endian `u32(...)` views directly.
|
||||
// Public `wrapCipher(...)` APIs reject non-little-endian platforms before reaching this path.
|
||||
// RFC 8439 §2.3 / RFC 7539 §2.3 only define the 256-bit-key constants; this 16-byte sigma is
|
||||
// kept for legacy allowShortKeys Salsa/ChaCha variants.
|
||||
const sigma16_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr('expand 16-byte k'))))();
|
||||
// RFC 8439 §2.3 / RFC 7539 §2.3 define words 0-3 as
|
||||
// `0x61707865 0x3320646e 0x79622d32 0x6b206574`, i.e. `expand 32-byte k`.
|
||||
const sigma32_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr('expand 32-byte k'))))();
|
||||
|
||||
/**
|
||||
* Rotates a 32-bit word left.
|
||||
* @param a - Input word.
|
||||
* @param b - Rotation count in bits.
|
||||
* @returns Rotated 32-bit word.
|
||||
* @example
|
||||
* Moves the top byte of `0x12345678` into the low byte position.
|
||||
* ```ts
|
||||
* rotl(0x12345678, 8);
|
||||
* ```
|
||||
*/
|
||||
export function rotl(a: number, b: number): number {
|
||||
return (a << b) | (a >>> (32 - b));
|
||||
}
|
||||
|
||||
/**
|
||||
* ARX core function operating on 32-bit words. Ciphers must use u32 for efficiency.
|
||||
* @param sigma - Sigma constants for the selected cipher layout.
|
||||
* @param key - Expanded key words.
|
||||
* @param nonce - Nonce and counter words prepared for the round function.
|
||||
* @param output - Output block written in place.
|
||||
* @param counter - Block counter value.
|
||||
* @param rounds - Optional round count override.
|
||||
*/
|
||||
export type CipherCoreFn = (
|
||||
sigma: TArg<Uint32Array>,
|
||||
key: TArg<Uint32Array>,
|
||||
nonce: TArg<Uint32Array>,
|
||||
output: TArg<Uint32Array>,
|
||||
counter: number,
|
||||
rounds?: number
|
||||
) => void;
|
||||
|
||||
/**
|
||||
* Nonce-extension function used by XChaCha and XSalsa.
|
||||
* @param sigma - Sigma constants for the selected cipher layout.
|
||||
* @param key - Expanded key words.
|
||||
* @param input - Input nonce words used for subkey derivation.
|
||||
* @param output - Output buffer written with the derived nonce words.
|
||||
*/
|
||||
export type ExtendNonceFn = (
|
||||
sigma: TArg<Uint32Array>,
|
||||
key: TArg<Uint32Array>,
|
||||
input: TArg<Uint32Array>,
|
||||
output: TArg<Uint32Array>
|
||||
) => void;
|
||||
|
||||
/** ARX cipher options.
|
||||
* * `allowShortKeys` for 16-byte keys
|
||||
* * `counterLength` in bytes
|
||||
* * `counterRight`: right: `nonce|counter`; left: `counter|nonce`
|
||||
* */
|
||||
export type CipherOpts = {
|
||||
/** Whether 16-byte keys are accepted for legacy Salsa and ChaCha variants. */
|
||||
allowShortKeys?: boolean;
|
||||
/** Optional nonce-expansion hook used by extended-nonce variants. */
|
||||
extendNonceFn?: ExtendNonceFn;
|
||||
/** Counter length in bytes inside the nonce/counter layout. */
|
||||
counterLength?: number;
|
||||
/** Whether the layout is `nonce|counter` instead of `counter|nonce`. */
|
||||
counterRight?: boolean;
|
||||
/** Number of core rounds to execute. */
|
||||
rounds?: number;
|
||||
};
|
||||
|
||||
// Salsa and Chacha block length is always 512-bit
|
||||
const BLOCK_LEN = 64;
|
||||
// RFC 8439 §2.2 / RFC 7539 §2.2: the ChaCha state has 16 32-bit words.
|
||||
const BLOCK_LEN32 = 16;
|
||||
|
||||
// Counter policy for the shared public `counter` argument:
|
||||
// - RFC/IETF ChaCha20 uses a 32-bit counter.
|
||||
// - OpenSSL/Node `chacha20` instead treat the full 16-byte IV as a 128-bit
|
||||
// counter state and carry into the next word.
|
||||
// - Raw `chacha20orig`, `salsa20`, `xsalsa20`, and `xchacha20` use 64-bit counters in libsodium
|
||||
// and libtomcrypt, while some libs (for example libtomcrypt's RFC/IETF path) reject the max
|
||||
// boundary instead of carrying.
|
||||
// - AEAD wrappers diverge too: libsodium `xchacha20poly1305` uses the IETF payload counter from
|
||||
// block 1, while `secretstream_xchacha20poly1305` is a different protocol with rekey/reset.
|
||||
// Noble intentionally throws instead of silently picking one wrap model for users. In the default
|
||||
// path, even a 32-bit boundary would take 2^32 blocks * 64 bytes = 256 GiB, which is practically
|
||||
// unreachable for normal JS callers; advanced users who pass `counter` explicitly can implement
|
||||
// whatever wider carry / wrap policy they need on top.
|
||||
const MAX_COUNTER = /* @__PURE__ */ (() => 2 ** 32 - 1)();
|
||||
const U32_EMPTY = /* @__PURE__ */ Uint32Array.of();
|
||||
function runCipher(
|
||||
core: TArg<CipherCoreFn>,
|
||||
sigma: TArg<Uint32Array>,
|
||||
key: TArg<Uint32Array>,
|
||||
nonce: TArg<Uint32Array>,
|
||||
data: TArg<Uint8Array>,
|
||||
output: TArg<Uint8Array>,
|
||||
counter: number,
|
||||
rounds: number
|
||||
): void {
|
||||
const len = data.length;
|
||||
const block = new Uint8Array(BLOCK_LEN);
|
||||
const b32 = u32(block);
|
||||
// Make sure that buffers aligned to 4 bytes
|
||||
const isAligned = isLE && isAligned32(data) && isAligned32(output);
|
||||
const d32 = isAligned ? u32(data) : U32_EMPTY;
|
||||
const o32 = isAligned ? u32(output) : U32_EMPTY;
|
||||
// RFC 8439 §2.4.1 / RFC 7539 §2.4.1 allow XORing one keystream block at a time and
|
||||
// truncating the final partial block instead of materializing the whole keystream.
|
||||
if (!isLE) {
|
||||
for (let pos = 0; pos < len; counter++) {
|
||||
core(
|
||||
sigma as TRet<Uint32Array>,
|
||||
key as TRet<Uint32Array>,
|
||||
nonce as TRet<Uint32Array>,
|
||||
b32,
|
||||
counter,
|
||||
rounds
|
||||
);
|
||||
// RFC 8439 §2.4 / RFC 7539 §2.4 serialize keystream words in little-endian order.
|
||||
swap32IfBE(b32);
|
||||
if (counter >= MAX_COUNTER) throw new Error('arx: counter overflow');
|
||||
const take = Math.min(BLOCK_LEN, len - pos);
|
||||
for (let j = 0, posj; j < take; j++) {
|
||||
posj = pos + j;
|
||||
output[posj] = data[posj] ^ block[j];
|
||||
}
|
||||
pos += take;
|
||||
}
|
||||
return;
|
||||
}
|
||||
for (let pos = 0; pos < len; counter++) {
|
||||
core(
|
||||
sigma as TRet<Uint32Array>,
|
||||
key as TRet<Uint32Array>,
|
||||
nonce as TRet<Uint32Array>,
|
||||
b32,
|
||||
counter,
|
||||
rounds
|
||||
);
|
||||
// See MAX_COUNTER policy note above: never silently wrap the shared public counter.
|
||||
if (counter >= MAX_COUNTER) throw new Error('arx: counter overflow');
|
||||
const take = Math.min(BLOCK_LEN, len - pos);
|
||||
// aligned to 4 bytes
|
||||
if (isAligned && take === BLOCK_LEN) {
|
||||
const pos32 = pos / 4;
|
||||
if (pos % 4 !== 0) throw new Error('arx: invalid block position');
|
||||
for (let j = 0, posj: number; j < BLOCK_LEN32; j++) {
|
||||
posj = pos32 + j;
|
||||
o32[posj] = d32[posj] ^ b32[j];
|
||||
}
|
||||
pos += BLOCK_LEN;
|
||||
continue;
|
||||
}
|
||||
for (let j = 0, posj; j < take; j++) {
|
||||
posj = pos + j;
|
||||
output[posj] = data[posj] ^ block[j];
|
||||
}
|
||||
pos += take;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an ARX stream cipher from a 32-bit core permutation.
|
||||
* Used internally to build the exported Salsa and ChaCha stream ciphers.
|
||||
* @param core - Core function that fills one keystream block.
|
||||
* @param opts - Cipher layout and nonce-extension options. See {@link CipherOpts}.
|
||||
* @returns Stream cipher function over byte arrays.
|
||||
* @throws If the core callback, key size, counter, or output sizing is invalid. {@link Error}
|
||||
*/
|
||||
export function createCipher(core: TArg<CipherCoreFn>, opts: TArg<CipherOpts>): TRet<XorStream> {
|
||||
const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts(
|
||||
{ allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 },
|
||||
opts
|
||||
);
|
||||
if (typeof core !== 'function') throw new Error('core must be a function');
|
||||
anumber(counterLength);
|
||||
anumber(rounds);
|
||||
abool(counterRight);
|
||||
abool(allowShortKeys);
|
||||
return (
|
||||
key: TArg<Uint8Array>,
|
||||
nonce: TArg<Uint8Array>,
|
||||
data: TArg<Uint8Array>,
|
||||
output?: TArg<Uint8Array>,
|
||||
counter = 0
|
||||
): TRet<Uint8Array> => {
|
||||
abytes(key, undefined, 'key');
|
||||
abytes(nonce, undefined, 'nonce');
|
||||
abytes(data, undefined, 'data');
|
||||
const len = data.length;
|
||||
// Raw XorStream APIs return ciphertext/plaintext bytes directly, so caller-provided outputs
|
||||
// must match the logical result length exactly instead of returning an oversized workspace.
|
||||
output = getOutput(len, output, false);
|
||||
anumber(counter);
|
||||
// See MAX_COUNTER policy note above: reject advanced explicit-counter requests before any wrap.
|
||||
if (counter < 0 || counter >= MAX_COUNTER) throw new Error('arx: counter overflow');
|
||||
const toClean = [];
|
||||
|
||||
// Key & sigma
|
||||
// key=16 -> sigma16, k=key|key
|
||||
// key=32 -> sigma32, k=key
|
||||
let l = key.length;
|
||||
let k: Uint8Array;
|
||||
let sigma: Uint32Array;
|
||||
if (l === 32) {
|
||||
// Copy caller keys too: big-endian normalization, extended-nonce subkey derivation, and
|
||||
// final clean(...) all mutate or wipe the temporary buffer in place.
|
||||
toClean.push((k = copyBytes(key)));
|
||||
sigma = sigma32_32;
|
||||
} else if (l === 16 && allowShortKeys) {
|
||||
k = new Uint8Array(32);
|
||||
k.set(key);
|
||||
k.set(key, 16);
|
||||
sigma = sigma16_32;
|
||||
toClean.push(k);
|
||||
} else {
|
||||
abytes(key, 32, 'arx key');
|
||||
throw new Error('invalid key size');
|
||||
// throw new Error(`"arx key" expected Uint8Array of length 32, got length=${l}`);
|
||||
}
|
||||
|
||||
// Nonce
|
||||
// salsa20: 8 (8-byte counter)
|
||||
// chacha20orig: 8 (8-byte counter)
|
||||
// chacha20: 12 (4-byte counter)
|
||||
// xsalsa20: 24 (16 -> hsalsa, 8 -> old nonce)
|
||||
// xchacha20: 24 (16 -> hchacha, 8 -> old nonce)
|
||||
// Copy before taking u32(...) views on misaligned inputs, and on big-endian so later
|
||||
// swap32IfBE(...) never mutates caller nonce bytes in place.
|
||||
if (!isLE || !isAligned32(nonce)) toClean.push((nonce = copyBytes(nonce)));
|
||||
|
||||
let k32 = u32(k);
|
||||
// hsalsa & hchacha: handle extended nonce
|
||||
if (extendNonceFn) {
|
||||
if (nonce.length !== 24) throw new Error(`arx: extended nonce must be 24 bytes`);
|
||||
const n16 = nonce.subarray(0, 16);
|
||||
if (isLE) extendNonceFn(sigma as TRet<Uint32Array>, k32, u32(n16), k32);
|
||||
else {
|
||||
const sigmaRaw = swap32IfBE(Uint32Array.from(sigma));
|
||||
extendNonceFn(sigmaRaw, k32, u32(n16), k32);
|
||||
clean(sigmaRaw);
|
||||
swap32IfBE(k32);
|
||||
}
|
||||
nonce = nonce.subarray(16);
|
||||
} else if (!isLE) swap32IfBE(k32);
|
||||
|
||||
// Handle nonce counter
|
||||
const nonceNcLen = 16 - counterLength;
|
||||
if (nonceNcLen !== nonce.length)
|
||||
throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);
|
||||
|
||||
// Normalize 64-bit-nonce layouts to the 12-byte core input: ChaCha/XChaCha prefix 4 zero
|
||||
// counter bytes, while Salsa/XSalsa append them after the nonce words.
|
||||
if (nonceNcLen !== 12) {
|
||||
const nc = new Uint8Array(12);
|
||||
nc.set(nonce, counterRight ? 0 : 12 - nonce.length);
|
||||
nonce = nc;
|
||||
toClean.push(nonce);
|
||||
}
|
||||
const n32 = swap32IfBE(u32(nonce));
|
||||
// Ensure temporary key/nonce copies are wiped even if the remaining
|
||||
// runtime guard in runCipher(...) throws on counter overflow.
|
||||
try {
|
||||
runCipher(core, sigma, k32, n32, data, output, counter, rounds);
|
||||
return output as TRet<Uint8Array>;
|
||||
} finally {
|
||||
clean(...toClean);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** Internal class which wraps chacha20 or chacha8 to create CSPRNG. */
|
||||
export class _XorStreamPRG implements PRG {
|
||||
readonly blockLen: number;
|
||||
readonly keyLen: number;
|
||||
readonly nonceLen: number;
|
||||
private state: TRet<Uint8Array>;
|
||||
private buf: TRet<Uint8Array>;
|
||||
private key: TRet<Uint8Array>;
|
||||
private nonce: TRet<Uint8Array>;
|
||||
private pos: number;
|
||||
private ctr: number;
|
||||
private cipher: TArg<XorStream>;
|
||||
constructor(
|
||||
cipher: TArg<XorStream>,
|
||||
blockLen: number,
|
||||
keyLen: number,
|
||||
nonceLen: number,
|
||||
seed: TArg<Uint8Array>
|
||||
) {
|
||||
this.cipher = cipher;
|
||||
this.blockLen = blockLen;
|
||||
this.keyLen = keyLen;
|
||||
this.nonceLen = nonceLen;
|
||||
this.state = new Uint8Array(this.keyLen + this.nonceLen) as TRet<Uint8Array>;
|
||||
this.reseed(seed);
|
||||
this.ctr = 0;
|
||||
this.pos = this.blockLen;
|
||||
this.buf = new Uint8Array(this.blockLen) as TRet<Uint8Array>;
|
||||
// Keep a single key||nonce backing buffer so reseed/addEntropy/clean update the live cipher
|
||||
// inputs in place through these subarray views.
|
||||
this.key = this.state.subarray(0, this.keyLen) as TRet<Uint8Array>;
|
||||
this.nonce = this.state.subarray(this.keyLen) as TRet<Uint8Array>;
|
||||
}
|
||||
private reseed(seed: TArg<Uint8Array>) {
|
||||
abytes(seed);
|
||||
if (!seed || seed.length === 0) throw new Error('entropy required');
|
||||
// Mix variable-length entropy cyclically across the whole key||nonce state, then restart the
|
||||
// keystream so buffered leftovers from the previous state are never reused.
|
||||
for (let i = 0; i < seed.length; i++) this.state[i % this.state.length] ^= seed[i];
|
||||
this.ctr = 0;
|
||||
this.pos = this.blockLen;
|
||||
}
|
||||
addEntropy(seed: TArg<Uint8Array>): void {
|
||||
// Reject empty entropy before re-keying, otherwise a throwing call would still advance state.
|
||||
abytes(seed);
|
||||
if (seed.length === 0) throw new Error('entropy required');
|
||||
// Re-key from the current stream first, then mix external entropy into the fresh key||nonce
|
||||
// state through reseed() so stale buffered bytes are discarded.
|
||||
this.state.set(this.randomBytes(this.state.length));
|
||||
this.reseed(seed);
|
||||
}
|
||||
randomBytes(len: number): TRet<Uint8Array> {
|
||||
anumber(len);
|
||||
if (len === 0) return new Uint8Array(0) as TRet<Uint8Array>;
|
||||
const avail = this.pos < this.blockLen ? this.blockLen - this.pos : 0;
|
||||
const blocks = Math.ceil(Math.max(0, len - avail) / this.blockLen);
|
||||
// Preflight overflow so failed reads don't partially consume keystream
|
||||
// and leave the PRG repeating blocks.
|
||||
if (blocks > 0 && this.ctr > MAX_COUNTER - blocks) throw new Error('arx: counter overflow');
|
||||
const out = new Uint8Array(len);
|
||||
let outPos = 0;
|
||||
// `out` starts zero-filled, and `buf.fill(0)` below does the same for leftovers: XOR-stream
|
||||
// ciphers then emit raw keystream bytes directly into those buffers.
|
||||
// Serve buffered leftovers first so split reads stay identical to one larger read.
|
||||
if (this.pos < this.blockLen) {
|
||||
const take = Math.min(len, this.blockLen - this.pos);
|
||||
out.set(this.buf.subarray(this.pos, this.pos + take), 0);
|
||||
this.pos += take;
|
||||
outPos += take;
|
||||
if (outPos === len) return out as TRet<Uint8Array>; // fast path
|
||||
}
|
||||
// Full blocks directly to out
|
||||
const full = Math.floor((len - outPos) / this.blockLen);
|
||||
if (full > 0) {
|
||||
const blockBytes = full * this.blockLen;
|
||||
const b = out.subarray(outPos, outPos + blockBytes);
|
||||
this.cipher(this.key, this.nonce, b as TRet<Uint8Array>, b as TRet<Uint8Array>, this.ctr);
|
||||
this.ctr += full;
|
||||
outPos += blockBytes;
|
||||
}
|
||||
// Save leftovers
|
||||
const left = len - outPos;
|
||||
if (left > 0) {
|
||||
this.buf.fill(0);
|
||||
// NOTE: cipher will handle overflow
|
||||
this.cipher(
|
||||
this.key,
|
||||
this.nonce,
|
||||
this.buf as TRet<Uint8Array>,
|
||||
this.buf as TRet<Uint8Array>,
|
||||
this.ctr++
|
||||
);
|
||||
out.set(this.buf.subarray(0, left), outPos);
|
||||
this.pos = left;
|
||||
}
|
||||
return out as TRet<Uint8Array>;
|
||||
}
|
||||
// Clone seeds the new instance from this stream, so the source PRG advances too.
|
||||
clone(): _XorStreamPRG {
|
||||
return new _XorStreamPRG(
|
||||
this.cipher,
|
||||
this.blockLen,
|
||||
this.keyLen,
|
||||
this.nonceLen,
|
||||
this.randomBytes(this.state.length)
|
||||
);
|
||||
}
|
||||
// Zeroes the current state and leftover buffer, but does not make the instance unusable:
|
||||
// Later reads first drain zeros from the cleared buffer and then continue
|
||||
// from zero key||nonce state.
|
||||
clean(): void {
|
||||
this.pos = 0;
|
||||
this.ctr = 0;
|
||||
this.buf.fill(0);
|
||||
this.state.fill(0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* PRG constructor backed by an ARX stream cipher.
|
||||
* @param seed - Optional seed bytes mixed into the initial state. When omitted, exactly 32
|
||||
* random bytes are mixed in by default: larger states keep a zero tail, while smaller states
|
||||
* wrap those bytes through `reseed()`'s XOR schedule.
|
||||
* @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`.
|
||||
*/
|
||||
export type XorPRG = (seed?: TArg<Uint8Array>) => TRet<_XorStreamPRG>;
|
||||
|
||||
/**
|
||||
* Creates a PRG constructor from a stream cipher.
|
||||
* @param cipher - Stream cipher used to fill output blocks.
|
||||
* @param blockLen - Keystream block length in bytes.
|
||||
* @param keyLen - Internal key length in bytes.
|
||||
* @param nonceLen - Internal nonce length in bytes.
|
||||
* @returns PRG factory for seeded concrete `_XorStreamPRG` instances.
|
||||
* @example
|
||||
* Builds a PRG from XChaCha20 and reads bytes from a randomly seeded instance.
|
||||
* ```ts
|
||||
* import { xchacha20 } from '@noble/ciphers/chacha.js';
|
||||
* import { createPRG } from '@noble/ciphers/_arx.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const seed = randomBytes(32);
|
||||
* const init = createPRG(xchacha20, 64, 32, 24);
|
||||
* const prg = init(seed);
|
||||
* prg.randomBytes(8);
|
||||
* ```
|
||||
*/
|
||||
export const createPRG = (
|
||||
cipher: TArg<XorStream>,
|
||||
blockLen: number,
|
||||
keyLen: number,
|
||||
nonceLen: number
|
||||
): TRet<XorPRG> => {
|
||||
return ((seed: TArg<Uint8Array> = randomBytes(32)): TRet<_XorStreamPRG> =>
|
||||
new _XorStreamPRG(
|
||||
cipher,
|
||||
blockLen,
|
||||
keyLen,
|
||||
nonceLen,
|
||||
seed
|
||||
) as TRet<_XorStreamPRG>) as TRet<XorPRG>;
|
||||
};
|
||||
399
node_modules/@noble/ciphers/src/_poly1305.ts
generated
vendored
Normal file
399
node_modules/@noble/ciphers/src/_poly1305.ts
generated
vendored
Normal file
@@ -0,0 +1,399 @@
|
||||
/**
|
||||
* Poly1305 ({@link https://cr.yp.to/mac/poly1305-20050329.pdf | PDF},
|
||||
* {@link https://en.wikipedia.org/wiki/Poly1305 | wiki})
|
||||
* is a fast and parallel secret-key message-authentication code suitable for
|
||||
* a wide variety of applications. It was standardized in
|
||||
* {@link https://www.rfc-editor.org/rfc/rfc8439 | RFC 8439} and is now used in TLS 1.3.
|
||||
*
|
||||
* Polynomial MACs are not perfect for every situation:
|
||||
* they lack Random Key Robustness: the MAC can be forged, and can't be used in PAKE schemes.
|
||||
* See {@link https://keymaterial.net/2020/09/07/invisible-salamanders-in-aes-gcm-siv/ | the invisible salamanders attack writeup}.
|
||||
* To combat invisible salamanders, `hash(key)` can be included in ciphertext,
|
||||
* however, this would violate ciphertext indistinguishability:
|
||||
* an attacker would know which key was used - so `HKDF(key, i)`
|
||||
* could be used instead.
|
||||
*
|
||||
* Check out the {@link https://cr.yp.to/mac.html | original website}.
|
||||
* Based on public-domain {@link https://github.com/floodyberry/poly1305-donna | poly1305-donna}.
|
||||
* @module
|
||||
*/
|
||||
// prettier-ignore
|
||||
import {
|
||||
abytes, aexists, aoutput, bytesToHex,
|
||||
clean, concatBytes, copyBytes, hexToNumber, numberToBytesBE,
|
||||
wrapMacConstructor, type CMac, type IHash2, type TArg, type TRet
|
||||
} from './utils.ts';
|
||||
|
||||
// Little-endian 2-byte load used by the Poly1305 limb decomposition.
|
||||
function u8to16(a: TArg<Uint8Array>, i: number) {
|
||||
return (a[i++] & 0xff) | ((a[i++] & 0xff) << 8);
|
||||
}
|
||||
|
||||
function bytesToNumberLE(bytes: TArg<Uint8Array>): bigint {
|
||||
return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
|
||||
}
|
||||
|
||||
/** Small version of `poly1305` without loop unrolling. Unused, provided for auditability. */
|
||||
function poly1305_small(msg: TArg<Uint8Array>, key: TArg<Uint8Array>): TRet<Uint8Array> {
|
||||
abytes(msg);
|
||||
abytes(key, 32, 'key');
|
||||
const POW_2_130_5 = BigInt(2) ** BigInt(130) - BigInt(5); // 2^130-5
|
||||
const POW_2_128_1 = BigInt(2) ** BigInt(128) - BigInt(1); // 2^128-1
|
||||
const CLAMP_R = BigInt('0x0ffffffc0ffffffc0ffffffc0fffffff');
|
||||
const r = bytesToNumberLE(key.subarray(0, 16)) & CLAMP_R;
|
||||
const s = bytesToNumberLE(key.subarray(16));
|
||||
// Process by 16 byte chunks
|
||||
let acc = BigInt(0);
|
||||
for (let i = 0; i < msg.length; i += 16) {
|
||||
const m = msg.subarray(i, i + 16);
|
||||
// RFC 8439 §2.5.1 / RFC 7539 §2.5.1 append [0x01] to each chunk before multiplying by r.
|
||||
const n = bytesToNumberLE(m) | (BigInt(1) << BigInt(8 * m.length));
|
||||
acc = ((acc + n) * r) % POW_2_130_5;
|
||||
}
|
||||
const res = (acc + s) & POW_2_128_1;
|
||||
// RFC 8439 §2.5 / RFC 7539 §2.5 serialize the low 128 bits in little-endian order.
|
||||
return numberToBytesBE(res, 16).reverse() as TRet<Uint8Array>; // LE
|
||||
}
|
||||
|
||||
// Can be used to replace `computeTag` in chacha.ts. Unused, provided for auditability.
|
||||
// @ts-expect-error
|
||||
function poly1305_computeTag_small(
|
||||
authKey: TArg<Uint8Array>,
|
||||
// AEAD trailer must already be the 16-byte length block:
|
||||
// 8-byte little-endian AAD length || 8-byte little-endian ciphertext length.
|
||||
lengths: TArg<Uint8Array>,
|
||||
ciphertext: TArg<Uint8Array>,
|
||||
AAD?: TArg<Uint8Array>
|
||||
): TRet<Uint8Array> {
|
||||
// RFC 8439 §2.8.1 / RFC 7539 §2.8.1 MAC input is
|
||||
// AAD || pad16(AAD) || ciphertext || pad16(ciphertext) || lengths.
|
||||
const res = [];
|
||||
const updatePadded2 = (msg: TArg<Uint8Array>) => {
|
||||
res.push(msg);
|
||||
const leftover = msg.length % 16;
|
||||
// RFC 8439 §2.8.1 / RFC 7539 §2.8.1: pad16(x) is empty for aligned
|
||||
// inputs, else 16-(len%16) zero bytes.
|
||||
if (leftover) res.push(new Uint8Array(16).slice(leftover));
|
||||
};
|
||||
if (AAD) updatePadded2(AAD);
|
||||
updatePadded2(ciphertext);
|
||||
res.push(lengths);
|
||||
return poly1305_small(concatBytes(...res), authKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Incremental Poly1305 MAC state.
|
||||
* Prefer `poly1305()` for one-shot use.
|
||||
* @param key - 32-byte Poly1305 one-time key.
|
||||
* @example
|
||||
* Feeds one chunk into an incremental Poly1305 state with a fresh one-time key.
|
||||
*
|
||||
* ```ts
|
||||
* import { Poly1305 } from '@noble/ciphers/_poly1305.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const mac = new Poly1305(key);
|
||||
* mac.update(new Uint8Array([1, 2, 3]));
|
||||
* mac.digest();
|
||||
* ```
|
||||
*/
|
||||
export class Poly1305 implements IHash2 {
|
||||
readonly blockLen = 16;
|
||||
readonly outputLen = 16;
|
||||
private buffer = new Uint8Array(16);
|
||||
private r = new Uint16Array(10); // Allocating 1 array with .subarray() here is slower than 3
|
||||
private h = new Uint16Array(10);
|
||||
private pad = new Uint16Array(8);
|
||||
private pos = 0;
|
||||
protected finished = false;
|
||||
protected destroyed = false;
|
||||
|
||||
// Can be speed-up using BigUint64Array, at the cost of complexity
|
||||
constructor(key: TArg<Uint8Array>) {
|
||||
key = copyBytes(abytes(key, 32, 'key'));
|
||||
const t0 = u8to16(key, 0);
|
||||
const t1 = u8to16(key, 2);
|
||||
const t2 = u8to16(key, 4);
|
||||
const t3 = u8to16(key, 6);
|
||||
const t4 = u8to16(key, 8);
|
||||
const t5 = u8to16(key, 10);
|
||||
const t6 = u8to16(key, 12);
|
||||
const t7 = u8to16(key, 14);
|
||||
|
||||
// RFC 8439 §2.5.1 / RFC 7539 §2.5.1 clamp r before multiplication.
|
||||
// These masks unpack that clamped value into 13-bit limbs, while pad
|
||||
// keeps the raw s half for finalize().
|
||||
// {@link https://github.com/floodyberry/poly1305-donna/blob/e6ad6e091d30d7f4ec2d4f978be1fcfcbce72781/poly1305-donna-16.h#L47 | poly1305-donna reference}
|
||||
this.r[0] = t0 & 0x1fff;
|
||||
this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;
|
||||
this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;
|
||||
this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;
|
||||
this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;
|
||||
this.r[5] = (t4 >>> 1) & 0x1ffe;
|
||||
this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;
|
||||
this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;
|
||||
this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;
|
||||
this.r[9] = (t7 >>> 5) & 0x007f;
|
||||
for (let i = 0; i < 8; i++) this.pad[i] = u8to16(key, 16 + 2 * i);
|
||||
}
|
||||
|
||||
private process(data: TArg<Uint8Array>, offset: number, isLast = false) {
|
||||
// RFC 8439 §2.5 / §2.5.1 and RFC 7539 §2.5 / §2.5.1 add an extra high
|
||||
// bit to every full 16-byte block. The final partial block gets its
|
||||
// explicit `1` byte during digestInto(), so `hibit` stays zero there.
|
||||
const hibit = isLast ? 0 : 1 << 11;
|
||||
const { h, r } = this;
|
||||
const r0 = r[0];
|
||||
const r1 = r[1];
|
||||
const r2 = r[2];
|
||||
const r3 = r[3];
|
||||
const r4 = r[4];
|
||||
const r5 = r[5];
|
||||
const r6 = r[6];
|
||||
const r7 = r[7];
|
||||
const r8 = r[8];
|
||||
const r9 = r[9];
|
||||
|
||||
const t0 = u8to16(data, offset + 0);
|
||||
const t1 = u8to16(data, offset + 2);
|
||||
const t2 = u8to16(data, offset + 4);
|
||||
const t3 = u8to16(data, offset + 6);
|
||||
const t4 = u8to16(data, offset + 8);
|
||||
const t5 = u8to16(data, offset + 10);
|
||||
const t6 = u8to16(data, offset + 12);
|
||||
const t7 = u8to16(data, offset + 14);
|
||||
|
||||
let h0 = h[0] + (t0 & 0x1fff);
|
||||
let h1 = h[1] + (((t0 >>> 13) | (t1 << 3)) & 0x1fff);
|
||||
let h2 = h[2] + (((t1 >>> 10) | (t2 << 6)) & 0x1fff);
|
||||
let h3 = h[3] + (((t2 >>> 7) | (t3 << 9)) & 0x1fff);
|
||||
let h4 = h[4] + (((t3 >>> 4) | (t4 << 12)) & 0x1fff);
|
||||
let h5 = h[5] + ((t4 >>> 1) & 0x1fff);
|
||||
let h6 = h[6] + (((t4 >>> 14) | (t5 << 2)) & 0x1fff);
|
||||
let h7 = h[7] + (((t5 >>> 11) | (t6 << 5)) & 0x1fff);
|
||||
let h8 = h[8] + (((t6 >>> 8) | (t7 << 8)) & 0x1fff);
|
||||
let h9 = h[9] + ((t7 >>> 5) | hibit);
|
||||
|
||||
let c = 0;
|
||||
|
||||
let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) + h4 * (5 * r6);
|
||||
c = d0 >>> 13;
|
||||
d0 &= 0x1fff;
|
||||
d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) + h9 * (5 * r1);
|
||||
c += d0 >>> 13;
|
||||
d0 &= 0x1fff;
|
||||
|
||||
let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) + h4 * (5 * r7);
|
||||
c = d1 >>> 13;
|
||||
d1 &= 0x1fff;
|
||||
d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) + h9 * (5 * r2);
|
||||
c += d1 >>> 13;
|
||||
d1 &= 0x1fff;
|
||||
|
||||
let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8);
|
||||
c = d2 >>> 13;
|
||||
d2 &= 0x1fff;
|
||||
d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) + h9 * (5 * r3);
|
||||
c += d2 >>> 13;
|
||||
d2 &= 0x1fff;
|
||||
|
||||
let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9);
|
||||
c = d3 >>> 13;
|
||||
d3 &= 0x1fff;
|
||||
d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) + h9 * (5 * r4);
|
||||
c += d3 >>> 13;
|
||||
d3 &= 0x1fff;
|
||||
|
||||
let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0;
|
||||
c = d4 >>> 13;
|
||||
d4 &= 0x1fff;
|
||||
d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r5);
|
||||
c += d4 >>> 13;
|
||||
d4 &= 0x1fff;
|
||||
|
||||
let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1;
|
||||
c = d5 >>> 13;
|
||||
d5 &= 0x1fff;
|
||||
d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6);
|
||||
c += d5 >>> 13;
|
||||
d5 &= 0x1fff;
|
||||
|
||||
let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2;
|
||||
c = d6 >>> 13;
|
||||
d6 &= 0x1fff;
|
||||
d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7);
|
||||
c += d6 >>> 13;
|
||||
d6 &= 0x1fff;
|
||||
|
||||
let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3;
|
||||
c = d7 >>> 13;
|
||||
d7 &= 0x1fff;
|
||||
d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8);
|
||||
c += d7 >>> 13;
|
||||
d7 &= 0x1fff;
|
||||
|
||||
let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4;
|
||||
c = d8 >>> 13;
|
||||
d8 &= 0x1fff;
|
||||
d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9);
|
||||
c += d8 >>> 13;
|
||||
d8 &= 0x1fff;
|
||||
|
||||
let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5;
|
||||
c = d9 >>> 13;
|
||||
d9 &= 0x1fff;
|
||||
d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0;
|
||||
c += d9 >>> 13;
|
||||
d9 &= 0x1fff;
|
||||
|
||||
c = ((c << 2) + c) | 0;
|
||||
c = (c + d0) | 0;
|
||||
d0 = c & 0x1fff;
|
||||
c = c >>> 13;
|
||||
d1 += c;
|
||||
|
||||
h[0] = d0;
|
||||
h[1] = d1;
|
||||
h[2] = d2;
|
||||
h[3] = d3;
|
||||
h[4] = d4;
|
||||
h[5] = d5;
|
||||
h[6] = d6;
|
||||
h[7] = d7;
|
||||
h[8] = d8;
|
||||
h[9] = d9;
|
||||
}
|
||||
|
||||
private finalize() {
|
||||
const { h, pad } = this;
|
||||
const g = new Uint16Array(10);
|
||||
let c = h[1] >>> 13;
|
||||
h[1] &= 0x1fff;
|
||||
for (let i = 2; i < 10; i++) {
|
||||
h[i] += c;
|
||||
c = h[i] >>> 13;
|
||||
h[i] &= 0x1fff;
|
||||
}
|
||||
h[0] += c * 5;
|
||||
c = h[0] >>> 13;
|
||||
h[0] &= 0x1fff;
|
||||
h[1] += c;
|
||||
c = h[1] >>> 13;
|
||||
h[1] &= 0x1fff;
|
||||
h[2] += c;
|
||||
|
||||
// RFC 8439 §2.5 / RFC 7539 §2.5 reduce modulo 2^130-5 before repacking
|
||||
// to 16-bit words and adding the raw s half.
|
||||
g[0] = h[0] + 5;
|
||||
c = g[0] >>> 13;
|
||||
g[0] &= 0x1fff;
|
||||
for (let i = 1; i < 10; i++) {
|
||||
g[i] = h[i] + c;
|
||||
c = g[i] >>> 13;
|
||||
g[i] &= 0x1fff;
|
||||
}
|
||||
g[9] -= 1 << 13;
|
||||
|
||||
let mask = (c ^ 1) - 1;
|
||||
for (let i = 0; i < 10; i++) g[i] &= mask;
|
||||
mask = ~mask;
|
||||
for (let i = 0; i < 10; i++) h[i] = (h[i] & mask) | g[i];
|
||||
h[0] = (h[0] | (h[1] << 13)) & 0xffff;
|
||||
h[1] = ((h[1] >>> 3) | (h[2] << 10)) & 0xffff;
|
||||
h[2] = ((h[2] >>> 6) | (h[3] << 7)) & 0xffff;
|
||||
h[3] = ((h[3] >>> 9) | (h[4] << 4)) & 0xffff;
|
||||
h[4] = ((h[4] >>> 12) | (h[5] << 1) | (h[6] << 14)) & 0xffff;
|
||||
h[5] = ((h[6] >>> 2) | (h[7] << 11)) & 0xffff;
|
||||
h[6] = ((h[7] >>> 5) | (h[8] << 8)) & 0xffff;
|
||||
h[7] = ((h[8] >>> 8) | (h[9] << 5)) & 0xffff;
|
||||
|
||||
let f = h[0] + pad[0];
|
||||
h[0] = f & 0xffff;
|
||||
for (let i = 1; i < 8; i++) {
|
||||
f = (((h[i] + pad[i]) | 0) + (f >>> 16)) | 0;
|
||||
h[i] = f & 0xffff;
|
||||
}
|
||||
clean(g);
|
||||
}
|
||||
update(data: TArg<Uint8Array>): this {
|
||||
aexists(this);
|
||||
abytes(data);
|
||||
data = copyBytes(data);
|
||||
const { buffer, blockLen } = this;
|
||||
const len = data.length;
|
||||
|
||||
for (let pos = 0; pos < len; ) {
|
||||
const take = Math.min(blockLen - this.pos, len - pos);
|
||||
// Fast path: we have at least one block in input
|
||||
if (take === blockLen) {
|
||||
for (; blockLen <= len - pos; pos += blockLen) this.process(data, pos);
|
||||
continue;
|
||||
}
|
||||
buffer.set(data.subarray(pos, pos + take), this.pos);
|
||||
this.pos += take;
|
||||
pos += take;
|
||||
if (this.pos === blockLen) {
|
||||
this.process(buffer, 0, false);
|
||||
this.pos = 0;
|
||||
}
|
||||
}
|
||||
return this;
|
||||
}
|
||||
destroy(): void {
|
||||
// `aexists(this)` guards update/digest paths, so destroy must mark the instance unusable too.
|
||||
this.destroyed = true;
|
||||
clean(this.h, this.r, this.buffer, this.pad);
|
||||
}
|
||||
digestInto(out: TArg<Uint8Array>): void {
|
||||
aexists(this);
|
||||
aoutput(out, this);
|
||||
this.finished = true;
|
||||
const { buffer, h } = this;
|
||||
let { pos } = this;
|
||||
if (pos) {
|
||||
// RFC 8439 §2.5 / RFC 7539 §2.5: the final short block appends a
|
||||
// single `0x01` byte and zero-fills the remaining bytes before the
|
||||
// last multiplication step.
|
||||
buffer[pos++] = 1;
|
||||
for (; pos < 16; pos++) buffer[pos] = 0;
|
||||
this.process(buffer, 0, true);
|
||||
}
|
||||
this.finalize();
|
||||
let opos = 0;
|
||||
for (let i = 0; i < 8; i++) {
|
||||
out[opos++] = h[i] >>> 0;
|
||||
out[opos++] = h[i] >>> 8;
|
||||
}
|
||||
}
|
||||
digest(): TRet<Uint8Array> {
|
||||
const { buffer, outputLen } = this;
|
||||
this.digestInto(buffer);
|
||||
// Copy out before destroy() zeroes the internal buffer.
|
||||
const res = buffer.slice(0, outputLen);
|
||||
this.destroy();
|
||||
return res as TRet<Uint8Array>;
|
||||
}
|
||||
}
|
||||
|
||||
/** One-shot keyed hash helper with `.create()`. */
|
||||
export type CHash = CMac<Poly1305>;
|
||||
|
||||
/**
|
||||
* Poly1305 MAC from RFC 8439.
|
||||
* @param msg - Message bytes to authenticate.
|
||||
* @param key - 32-byte Poly1305 one-time key.
|
||||
* @returns 16-byte authentication tag.
|
||||
* @example
|
||||
* Authenticates one message with a one-shot Poly1305 call and a fresh key.
|
||||
*
|
||||
* ```ts
|
||||
* import { poly1305 } from '@noble/ciphers/_poly1305.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* poly1305(new Uint8Array(), key);
|
||||
* ```
|
||||
*/
|
||||
export const poly1305: TRet<CHash> = /* @__PURE__ */ wrapMacConstructor(
|
||||
32,
|
||||
(key: TArg<Uint8Array>) => new Poly1305(key)
|
||||
);
|
||||
381
node_modules/@noble/ciphers/src/_polyval.ts
generated
vendored
Normal file
381
node_modules/@noble/ciphers/src/_polyval.ts
generated
vendored
Normal file
@@ -0,0 +1,381 @@
|
||||
/**
|
||||
* GHash from AES-GCM and its little-endian "mirror image" Polyval from AES-SIV.
|
||||
*
|
||||
* Implemented in terms of GHash with conversion function for keys
|
||||
* GCM GHASH from
|
||||
* {@link https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf | NIST SP800-38d},
|
||||
* SIV from
|
||||
* {@link https://www.rfc-editor.org/rfc/rfc8452 | RFC 8452}.
|
||||
*
|
||||
* GHASH modulo: x^128 + x^7 + x^2 + x + 1
|
||||
* POLYVAL modulo: x^128 + x^127 + x^126 + x^121 + 1
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import {
|
||||
abytes,
|
||||
aexists,
|
||||
aoutput,
|
||||
clean,
|
||||
copyBytes,
|
||||
createView,
|
||||
swap32IfBE,
|
||||
swap8IfBE,
|
||||
u32,
|
||||
wrapMacConstructor,
|
||||
type CMac,
|
||||
type IHash2,
|
||||
type TArg,
|
||||
type TRet,
|
||||
} from './utils.ts';
|
||||
|
||||
const BLOCK_SIZE = 16;
|
||||
// TODO: rewrite
|
||||
// temporary padding buffer
|
||||
// ZEROS32 aliases these bytes, so clean(ZEROS32) also resets this shared tail-padding scratch.
|
||||
const ZEROS16 = /* @__PURE__ */ new Uint8Array(16);
|
||||
const ZEROS32 = /* @__PURE__ */ u32(ZEROS16);
|
||||
// GHASH reduces modulo x^128 + x^7 + x^2 + x + 1, so the low-degree terms
|
||||
// x^7 + x^2 + x + 1 become bits `11100001` = 0xe1 in R = 0xe1 || 0^120.
|
||||
const POLY = 0xe1;
|
||||
|
||||
// v = 2*v % POLY
|
||||
// NOTE: because x + x = 0 (add/sub is same), mul2(x) != x+x
|
||||
// Montgomery ladder can multiply any field element with this doubling step;
|
||||
// addition stays simple xor.
|
||||
const mul2 = (s0: number, s1: number, s2: number, s3: number) => {
|
||||
const hiBit = s3 & 1;
|
||||
return {
|
||||
s3: (s2 << 31) | (s3 >>> 1),
|
||||
s2: (s1 << 31) | (s2 >>> 1),
|
||||
s1: (s0 << 31) | (s1 >>> 1),
|
||||
// NIST SP 800-38D §6.3 applies `V >> 1` and XORs R on carry. In this
|
||||
// 4x32-bit split, R = 0xe1 || 0^120 lives in the top byte of s0.
|
||||
s0: (s0 >>> 1) ^ ((POLY << 24) & -(hiBit & 1)), // reduce % poly
|
||||
};
|
||||
};
|
||||
|
||||
// Per-word part of RFC 8452 `ByteReverse`; callers also reverse the 32-bit word order.
|
||||
const swapLE = (n: number) =>
|
||||
(((n >>> 0) & 0xff) << 24) |
|
||||
(((n >>> 8) & 0xff) << 16) |
|
||||
(((n >>> 16) & 0xff) << 8) |
|
||||
((n >>> 24) & 0xff) |
|
||||
0;
|
||||
// POLYVAL first applies RFC 8452's per-word byte reversal, then re-normalizes
|
||||
// host-endian u32 loads to the little-endian word value `_updateBlock()` expects.
|
||||
const swap8IfLE = (n: number) => swap8IfBE(swapLE(n));
|
||||
|
||||
/**
|
||||
* `mulX_GHASH(ByteReverse(H))` from RFC 8452 Appendix A.
|
||||
* @param k mutated in place
|
||||
*/
|
||||
export function _toGHASHKey(k: TArg<Uint8Array>): TRet<Uint8Array> {
|
||||
// The input is the original POLYVAL key H; reverse() materializes
|
||||
// RFC 8452's `ByteReverse(H)` before the GHASH mulX step.
|
||||
k.reverse();
|
||||
const hiBit = k[15] & 1;
|
||||
// k >>= 1
|
||||
let carry = 0;
|
||||
for (let i = 0; i < k.length; i++) {
|
||||
const t = k[i];
|
||||
k[i] = (t >>> 1) | carry;
|
||||
carry = (t & 1) << 7;
|
||||
}
|
||||
k[0] ^= -hiBit & 0xe1; // if (hiBit) n ^= 0xe1000000000000000000000000000000;
|
||||
return k as TRet<Uint8Array>;
|
||||
}
|
||||
|
||||
type Value = { s0: number; s1: number; s2: number; s3: number };
|
||||
|
||||
// Precompute-window heuristic only: larger inputs trade memory for fewer table lookups.
|
||||
// Any caller-provided length hint still collapses to one of the supported windows {2, 4, 8}.
|
||||
const estimateWindow = (bytes: number) => {
|
||||
if (bytes > 64 * 1024) return 8;
|
||||
if (bytes > 1024) return 4;
|
||||
return 2;
|
||||
};
|
||||
|
||||
/**
|
||||
* Incremental GHASH state for AES-GCM.
|
||||
* @param key - 16-byte GHASH key.
|
||||
* @param expectedLength - Expected message length for table sizing.
|
||||
* Chunking is segment-based, not hash-streaming: every `update()` call is zero-padded
|
||||
* to the next 16-byte boundary before it is absorbed. This matches the internal AES/GCM
|
||||
* use where AAD, payload, and length block are separate padded segments.
|
||||
* @example
|
||||
* Feeds one ciphertext block into an incremental GHASH state with a fresh hash key.
|
||||
*
|
||||
* ```ts
|
||||
* import { GHASH } from '@noble/ciphers/_polyval.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const mac = new GHASH(key);
|
||||
* mac.update(new Uint8Array(16));
|
||||
* mac.digest();
|
||||
* ```
|
||||
*/
|
||||
export class GHASH implements IHash2 {
|
||||
readonly blockLen: number = BLOCK_SIZE;
|
||||
readonly outputLen: number = BLOCK_SIZE;
|
||||
protected s0 = 0;
|
||||
protected s1 = 0;
|
||||
protected s2 = 0;
|
||||
protected s3 = 0;
|
||||
protected finished = false;
|
||||
protected destroyed = false;
|
||||
protected t: Value[];
|
||||
private W: number;
|
||||
private windowSize: number;
|
||||
// We select bits per window adaptively based on expectedLength
|
||||
constructor(key: TArg<Uint8Array>, expectedLength?: number) {
|
||||
abytes(key, 16, 'key');
|
||||
key = copyBytes(key);
|
||||
const kView = createView(key);
|
||||
let k0 = kView.getUint32(0, false);
|
||||
let k1 = kView.getUint32(4, false);
|
||||
let k2 = kView.getUint32(8, false);
|
||||
let k3 = kView.getUint32(12, false);
|
||||
// generate table of doubled keys (half of montgomery ladder)
|
||||
const doubles: Value[] = [];
|
||||
for (let i = 0; i < 128; i++) {
|
||||
doubles.push({ s0: swapLE(k0), s1: swapLE(k1), s2: swapLE(k2), s3: swapLE(k3) });
|
||||
({ s0: k0, s1: k1, s2: k2, s3: k3 } = mul2(k0, k1, k2, k3));
|
||||
}
|
||||
const W = estimateWindow(expectedLength || 1024);
|
||||
if (![1, 2, 4, 8].includes(W))
|
||||
throw new Error('ghash: invalid window size, expected 2, 4 or 8');
|
||||
this.W = W;
|
||||
const bits = 128; // always 128 bits;
|
||||
const windows = bits / W;
|
||||
const windowSize = (this.windowSize = 2 ** W);
|
||||
const items: Value[] = [];
|
||||
// Create precompute table for window of W bits
|
||||
for (let w = 0; w < windows; w++) {
|
||||
// truth table: 00, 01, 10, 11
|
||||
for (let byte = 0; byte < windowSize; byte++) {
|
||||
// prettier-ignore
|
||||
let s0 = 0, s1 = 0, s2 = 0, s3 = 0;
|
||||
for (let j = 0; j < W; j++) {
|
||||
const bit = (byte >>> (W - j - 1)) & 1;
|
||||
if (!bit) continue;
|
||||
const { s0: d0, s1: d1, s2: d2, s3: d3 } = doubles[W * w + j];
|
||||
((s0 ^= d0), (s1 ^= d1), (s2 ^= d2), (s3 ^= d3));
|
||||
}
|
||||
items.push({ s0, s1, s2, s3 });
|
||||
}
|
||||
}
|
||||
this.t = items;
|
||||
}
|
||||
protected _updateBlock(s0: number, s1: number, s2: number, s3: number): void {
|
||||
((s0 ^= this.s0), (s1 ^= this.s1), (s2 ^= this.s2), (s3 ^= this.s3));
|
||||
const { W, t, windowSize } = this;
|
||||
// prettier-ignore
|
||||
let o0 = 0, o1 = 0, o2 = 0, o3 = 0;
|
||||
const mask = (1 << W) - 1; // 2**W will kill performance.
|
||||
let w = 0;
|
||||
// NIST SP 800-38D §6.3 interprets blocks as little-endian polynomials,
|
||||
// so the lookup walk consumes each word byte-by-byte from
|
||||
// least-significant to most-significant bits.
|
||||
for (const num of [s0, s1, s2, s3]) {
|
||||
for (let bytePos = 0; bytePos < 4; bytePos++) {
|
||||
const byte = (num >>> (8 * bytePos)) & 0xff;
|
||||
for (let bitPos = 8 / W - 1; bitPos >= 0; bitPos--) {
|
||||
const bit = (byte >>> (W * bitPos)) & mask;
|
||||
const { s0: e0, s1: e1, s2: e2, s3: e3 } = t[w * windowSize + bit];
|
||||
((o0 ^= e0), (o1 ^= e1), (o2 ^= e2), (o3 ^= e3));
|
||||
w += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
this.s0 = o0;
|
||||
this.s1 = o1;
|
||||
this.s2 = o2;
|
||||
this.s3 = o3;
|
||||
}
|
||||
update(data: TArg<Uint8Array>): this {
|
||||
aexists(this);
|
||||
abytes(data);
|
||||
data = copyBytes(data);
|
||||
const b32 = u32(data);
|
||||
const blocks = Math.floor(data.length / BLOCK_SIZE);
|
||||
const left = data.length % BLOCK_SIZE;
|
||||
for (let i = 0; i < blocks; i++) {
|
||||
this._updateBlock(
|
||||
swap8IfBE(b32[i * 4 + 0]),
|
||||
swap8IfBE(b32[i * 4 + 1]),
|
||||
swap8IfBE(b32[i * 4 + 2]),
|
||||
swap8IfBE(b32[i * 4 + 3])
|
||||
);
|
||||
}
|
||||
if (left) {
|
||||
ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));
|
||||
// Tail blocks go through the shared ZEROS32 scratch, so they need the same host-endian
|
||||
// normalization as full blocks; otherwise segmented GHASH/POLYVAL updates diverge on BE.
|
||||
this._updateBlock(
|
||||
swap8IfBE(ZEROS32[0]),
|
||||
swap8IfBE(ZEROS32[1]),
|
||||
swap8IfBE(ZEROS32[2]),
|
||||
swap8IfBE(ZEROS32[3])
|
||||
);
|
||||
clean(ZEROS32); // clean tmp buffer
|
||||
}
|
||||
return this;
|
||||
}
|
||||
destroy(): void {
|
||||
// `aexists(this)` guards update/digest paths, so destroy must mark the instance unusable too.
|
||||
this.destroyed = true;
|
||||
const { t } = this;
|
||||
// Wipe the key-derived precompute table; scalar accumulator words remain,
|
||||
// but the destroyed guard blocks further use.
|
||||
// clean precompute table
|
||||
for (const elm of t) {
|
||||
((elm.s0 = 0), (elm.s1 = 0), (elm.s2 = 0), (elm.s3 = 0));
|
||||
}
|
||||
}
|
||||
digestInto(out: TArg<Uint8Array>): void {
|
||||
aexists(this);
|
||||
// `digestInto(out)` is the no-allocation fast path, so callers must pass a
|
||||
// 32-bit-aligned buffer before we reinterpret it with `u32(out)`.
|
||||
aoutput(out, this, true);
|
||||
this.finished = true;
|
||||
// NIST SP 800-38D §6.4 returns the final 128-bit block Y_m.
|
||||
// `digestInto()` follows the relaxed `aoutput()` contract, so only
|
||||
// out[0..15] may be touched.
|
||||
const { s0, s1, s2, s3 } = this;
|
||||
const o32 = u32(out);
|
||||
o32[0] = s0;
|
||||
o32[1] = s1;
|
||||
o32[2] = s2;
|
||||
o32[3] = s3;
|
||||
swap32IfBE(o32);
|
||||
}
|
||||
digest(): TRet<Uint8Array> {
|
||||
const res = new Uint8Array(BLOCK_SIZE);
|
||||
this.digestInto(res);
|
||||
// `res` is independent of internal state, so it stays valid after destroy() wipes the table.
|
||||
this.destroy();
|
||||
return res as TRet<Uint8Array>;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Incremental POLYVAL state for AES-SIV.
|
||||
* @param key - 16-byte POLYVAL key.
|
||||
* @param expectedLength - Expected message length for table sizing.
|
||||
* Inherits GHASH's segment-padded `update()` behavior: each call is padded
|
||||
* independently to a 16-byte boundary before absorption.
|
||||
* @example
|
||||
* Feeds one block into an incremental POLYVAL state with a fresh hash key.
|
||||
*
|
||||
* ```ts
|
||||
* import { Polyval } from '@noble/ciphers/_polyval.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const mac = new Polyval(key);
|
||||
* mac.update(new Uint8Array(16));
|
||||
* mac.digest();
|
||||
* ```
|
||||
*/
|
||||
export class Polyval extends GHASH {
|
||||
constructor(key: TArg<Uint8Array>, expectedLength?: number) {
|
||||
abytes(key);
|
||||
// RFC 8452 Appendix A converts the POLYVAL key with
|
||||
// `mulX_GHASH(ByteReverse(H))`; copy first because `_toGHASHKey(...)`
|
||||
// mutates in place.
|
||||
const ghKey = _toGHASHKey(copyBytes(key));
|
||||
super(ghKey, expectedLength);
|
||||
clean(ghKey);
|
||||
}
|
||||
update(data: TArg<Uint8Array>): this {
|
||||
aexists(this);
|
||||
abytes(data);
|
||||
data = copyBytes(data);
|
||||
const b32 = u32(data);
|
||||
const left = data.length % BLOCK_SIZE;
|
||||
const blocks = Math.floor(data.length / BLOCK_SIZE);
|
||||
for (let i = 0; i < blocks; i++) {
|
||||
// RFC 8452 Appendix A feeds `ByteReverse(X_i)` into GHASH, so POLYVAL
|
||||
// reverses the 32-bit word order in addition to the per-word byte swap.
|
||||
this._updateBlock(
|
||||
swap8IfLE(b32[i * 4 + 3]),
|
||||
swap8IfLE(b32[i * 4 + 2]),
|
||||
swap8IfLE(b32[i * 4 + 1]),
|
||||
swap8IfLE(b32[i * 4 + 0])
|
||||
);
|
||||
}
|
||||
if (left) {
|
||||
ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));
|
||||
this._updateBlock(
|
||||
swap8IfLE(ZEROS32[3]),
|
||||
swap8IfLE(ZEROS32[2]),
|
||||
swap8IfLE(ZEROS32[1]),
|
||||
swap8IfLE(ZEROS32[0])
|
||||
);
|
||||
clean(ZEROS32);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
digestInto(out: TArg<Uint8Array>): void {
|
||||
aexists(this);
|
||||
// `digestInto(out)` is the no-allocation fast path, so callers must pass a
|
||||
// 32-bit-aligned buffer before we reinterpret the output prefix with `u32(view)`.
|
||||
aoutput(out, this, true);
|
||||
this.finished = true;
|
||||
// RFC 8452 Appendix A maps POLYVAL output back through `ByteReverse(...)`.
|
||||
// `digestInto()` follows the relaxed `aoutput()` contract, so only out[0..15] may be touched.
|
||||
const view = out.subarray(0, this.outputLen);
|
||||
const { s0, s1, s2, s3 } = this;
|
||||
const o32 = u32(view);
|
||||
o32[0] = s0;
|
||||
o32[1] = s1;
|
||||
o32[2] = s2;
|
||||
o32[3] = s3;
|
||||
swap32IfBE(o32);
|
||||
view.reverse();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* GHash MAC for AES-GCM.
|
||||
* @param msg - Message bytes to authenticate.
|
||||
* @param key - 16-byte GHASH key.
|
||||
* @returns 16-byte authentication tag.
|
||||
* @example
|
||||
* Authenticates a short message with GHASH and a fresh hash key.
|
||||
*
|
||||
* ```ts
|
||||
* import { ghash } from '@noble/ciphers/_polyval.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* ghash(new Uint8Array(), key);
|
||||
* ```
|
||||
*/
|
||||
export const ghash: TRet<CMac<GHASH, [expectedLength?: number]>> =
|
||||
/* @__PURE__ */ wrapMacConstructor(
|
||||
16,
|
||||
(key: TArg<Uint8Array>, expectedLength?: number) => new GHASH(key, expectedLength),
|
||||
(msg: TArg<Uint8Array>): [expectedLength?: number] => [msg.length]
|
||||
);
|
||||
|
||||
/**
|
||||
* POLYVAL MAC for AES-SIV.
|
||||
* @param msg - Message bytes to authenticate.
|
||||
* @param key - 16-byte POLYVAL key.
|
||||
* @returns 16-byte authentication tag.
|
||||
* @example
|
||||
* Authenticates a short message with POLYVAL and a fresh hash key.
|
||||
*
|
||||
* ```ts
|
||||
* import { polyval } from '@noble/ciphers/_polyval.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* polyval(new Uint8Array(), key);
|
||||
* ```
|
||||
*/
|
||||
export const polyval: TRet<CMac<Polyval, [expectedLength?: number]>> =
|
||||
/* @__PURE__ */ wrapMacConstructor(
|
||||
16,
|
||||
(key: TArg<Uint8Array>, expectedLength?: number) => new Polyval(key, expectedLength),
|
||||
(msg: TArg<Uint8Array>): [expectedLength?: number] => [msg.length]
|
||||
);
|
||||
2018
node_modules/@noble/ciphers/src/aes.ts
generated
vendored
Normal file
2018
node_modules/@noble/ciphers/src/aes.ts
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
579
node_modules/@noble/ciphers/src/chacha.ts
generated
vendored
Normal file
579
node_modules/@noble/ciphers/src/chacha.ts
generated
vendored
Normal file
@@ -0,0 +1,579 @@
|
||||
/**
|
||||
* ChaCha stream cipher, released
|
||||
* in 2008. Developed after Salsa20, ChaCha aims to increase diffusion per round.
|
||||
* It was standardized in
|
||||
* {@link https://www.rfc-editor.org/rfc/rfc8439 | RFC 8439} and
|
||||
* is now used in TLS 1.3.
|
||||
*
|
||||
* {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | XChaCha20}
|
||||
* extended-nonce variant is also provided. Similar to XSalsa, it's safe to use with
|
||||
* randomly-generated nonces.
|
||||
*
|
||||
* Check out
|
||||
* {@link http://cr.yp.to/chacha/chacha-20080128.pdf | PDF},
|
||||
* {@link https://en.wikipedia.org/wiki/Salsa20 | wiki}, and
|
||||
* {@link https://cr.yp.to/chacha.html | website}.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import { type XorPRG, createCipher, createPRG, rotl } from './_arx.ts';
|
||||
import { poly1305 } from './_poly1305.ts';
|
||||
import {
|
||||
type ARXCipher,
|
||||
type CipherWithOutput,
|
||||
type TArg,
|
||||
type TRet,
|
||||
type XorStream,
|
||||
abytes,
|
||||
clean,
|
||||
equalBytes,
|
||||
getOutput,
|
||||
swap8IfBE,
|
||||
swap32IfBE,
|
||||
u64Lengths,
|
||||
wrapCipher,
|
||||
} from './utils.ts';
|
||||
|
||||
/**
|
||||
* ChaCha core function. It is implemented twice:
|
||||
* 1. Simple loop (chachaCore_small, hchacha_small)
|
||||
* 2. Unrolled loop (chachaCore, hchacha) - 4x faster, but larger & harder to read
|
||||
* The specific implementation is selected in `createCipher` below.
|
||||
*/
|
||||
|
||||
/** RFC 8439 §2.1 quarter round on words a, b, c, d. */
|
||||
// prettier-ignore
|
||||
function chachaQR(x: TArg<Uint32Array>, a: number, b: number, c: number, d: number) {
|
||||
x[a] = (x[a] + x[b]) | 0; x[d] = rotl(x[d] ^ x[a], 16);
|
||||
x[c] = (x[c] + x[d]) | 0; x[b] = rotl(x[b] ^ x[c], 12);
|
||||
x[a] = (x[a] + x[b]) | 0; x[d] = rotl(x[d] ^ x[a], 8);
|
||||
x[c] = (x[c] + x[d]) | 0; x[b] = rotl(x[b] ^ x[c], 7);
|
||||
}
|
||||
|
||||
/** Repeated ChaCha double rounds; callers are expected to pass an even round count. */
|
||||
function chachaRound(x: TArg<Uint32Array>, rounds = 20) {
|
||||
for (let r = 0; r < rounds; r += 2) {
|
||||
// RFC 8439 §2.3 / §2.3.1 inner_block: four column rounds, then four diagonal rounds.
|
||||
chachaQR(x, 0, 4, 8, 12);
|
||||
chachaQR(x, 1, 5, 9, 13);
|
||||
chachaQR(x, 2, 6, 10, 14);
|
||||
chachaQR(x, 3, 7, 11, 15);
|
||||
chachaQR(x, 0, 5, 10, 15);
|
||||
chachaQR(x, 1, 6, 11, 12);
|
||||
chachaQR(x, 2, 7, 8, 13);
|
||||
chachaQR(x, 3, 4, 9, 14);
|
||||
}
|
||||
}
|
||||
|
||||
// Shared scratch for the auditability-only helper below; only the test-only
|
||||
// __TESTS.chachaCore_small hook reaches it, so production exports stay reentrant.
|
||||
const ctmp = /* @__PURE__ */ new Uint32Array(16);
|
||||
|
||||
/** Small version of chacha without loop unrolling. Unused, provided for auditability. */
|
||||
// prettier-ignore
|
||||
function chacha(
|
||||
s: TArg<Uint32Array>, k: TArg<Uint32Array>, i: TArg<Uint32Array>, out: TArg<Uint32Array>,
|
||||
isHChacha: boolean = true, rounds: number = 20
|
||||
): void {
|
||||
// `i` is either `[counter, nonce0, nonce1, nonce2]` for the ChaCha block
|
||||
// function or the full 128-bit nonce prefix for the HChaCha subkey path.
|
||||
// Create initial array using common pattern
|
||||
const y = Uint32Array.from([
|
||||
s[0], s[1], s[2], s[3], // "expa" "nd 3" "2-by" "te k"
|
||||
k[0], k[1], k[2], k[3], // Key Key Key Key
|
||||
k[4], k[5], k[6], k[7], // Key Key Key Key
|
||||
i[0], i[1], i[2], i[3], // Counter Counter Nonce Nonce
|
||||
]);
|
||||
const x = ctmp;
|
||||
x.set(y);
|
||||
chachaRound(x, rounds);
|
||||
|
||||
// HChaCha writes words 0..3 and 12..15 after the rounds; the ChaCha
|
||||
// block path adds the original state word-by-word.
|
||||
if (isHChacha) {
|
||||
const xindexes = [0, 1, 2, 3, 12, 13, 14, 15];
|
||||
for (let i = 0; i < 8; i++) out[i] = x[xindexes[i]];
|
||||
} else {
|
||||
for (let i = 0; i < 16; i++) out[i] = (y[i] + x[i]) | 0;
|
||||
}
|
||||
}
|
||||
|
||||
/** Identical to `chachaCore`. Reached only through the test-only `__TESTS` export. */
|
||||
// @ts-ignore
|
||||
const chachaCore_small: typeof chachaCore = (s, k, n, out, cnt, rounds) =>
|
||||
// Keep the reference wrapper on the same [counter, nonce0, nonce1, nonce2] layout as chacha().
|
||||
chacha(s, k, Uint32Array.from([cnt, n[0], n[1], n[2]]), out, false, rounds);
|
||||
/** Identical to `hchacha`. Unused. */
|
||||
// @ts-ignore
|
||||
const hchacha_small: typeof hchacha = chacha;
|
||||
|
||||
/** RFC 8439 §2.3 block core for `state = constants | key | counter | nonce`. */
|
||||
// prettier-ignore
|
||||
function chachaCore(
|
||||
s: TArg<Uint32Array>, k: TArg<Uint32Array>, n: TArg<Uint32Array>, out: TArg<Uint32Array>, cnt: number, rounds = 20
|
||||
): void {
|
||||
let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], // "expa" "nd 3" "2-by" "te k"
|
||||
y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], // Key Key Key Key
|
||||
y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], // Key Key Key Key
|
||||
y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2]; // Counter Nonce Nonce Nonce
|
||||
// Save state to temporary variables
|
||||
let x00 = y00, x01 = y01, x02 = y02, x03 = y03,
|
||||
x04 = y04, x05 = y05, x06 = y06, x07 = y07,
|
||||
x08 = y08, x09 = y09, x10 = y10, x11 = y11,
|
||||
x12 = y12, x13 = y13, x14 = y14, x15 = y15;
|
||||
for (let r = 0; r < rounds; r += 2) {
|
||||
x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 16);
|
||||
x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 12);
|
||||
x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 8);
|
||||
x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 7);
|
||||
|
||||
x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 16);
|
||||
x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 12);
|
||||
x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 8);
|
||||
x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 7);
|
||||
|
||||
x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 16);
|
||||
x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 12);
|
||||
x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 8);
|
||||
x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 7);
|
||||
|
||||
x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 16);
|
||||
x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 12);
|
||||
x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 8)
|
||||
x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 7);
|
||||
|
||||
x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 16);
|
||||
x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 12);
|
||||
x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 8);
|
||||
x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 7);
|
||||
|
||||
x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 16);
|
||||
x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 12);
|
||||
x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 8);
|
||||
x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 7);
|
||||
|
||||
x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 16);
|
||||
x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 12);
|
||||
x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 8);
|
||||
x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 7);
|
||||
|
||||
x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 16)
|
||||
x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 12);
|
||||
x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 8);
|
||||
x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 7);
|
||||
}
|
||||
// RFC 8439 §2.3 / §2.3.1: add the original state words back in state order.
|
||||
let oi = 0;
|
||||
out[oi++] = (y00 + x00) | 0; out[oi++] = (y01 + x01) | 0;
|
||||
out[oi++] = (y02 + x02) | 0; out[oi++] = (y03 + x03) | 0;
|
||||
out[oi++] = (y04 + x04) | 0; out[oi++] = (y05 + x05) | 0;
|
||||
out[oi++] = (y06 + x06) | 0; out[oi++] = (y07 + x07) | 0;
|
||||
out[oi++] = (y08 + x08) | 0; out[oi++] = (y09 + x09) | 0;
|
||||
out[oi++] = (y10 + x10) | 0; out[oi++] = (y11 + x11) | 0;
|
||||
out[oi++] = (y12 + x12) | 0; out[oi++] = (y13 + x13) | 0;
|
||||
out[oi++] = (y14 + x14) | 0; out[oi++] = (y15 + x15) | 0;
|
||||
}
|
||||
/**
|
||||
* hchacha hashes key and nonce into key' and nonce' for xchacha20.
|
||||
* Algorithmically identical to `hchacha_small`, but this exported path
|
||||
* normalizes word order on big-endian hosts.
|
||||
* Need to find a way to merge it with `chachaCore` without 25% performance hit.
|
||||
* @param s - Sigma constants as 32-bit words.
|
||||
* @param k - Key words.
|
||||
* @param i - Nonce-prefix words.
|
||||
* @param out - Output buffer for the derived subkey.
|
||||
* @example
|
||||
* Derives the XChaCha subkey from sigma, key, and nonce-prefix words.
|
||||
*
|
||||
* ```ts
|
||||
* const sigma = new Uint32Array(4);
|
||||
* const key = new Uint32Array(8);
|
||||
* const nonce = new Uint32Array(4);
|
||||
* const out = new Uint32Array(8);
|
||||
* hchacha(sigma, key, nonce, out);
|
||||
* ```
|
||||
*/
|
||||
// prettier-ignore
|
||||
export function hchacha(
|
||||
s: TArg<Uint32Array>, k: TArg<Uint32Array>, i: TArg<Uint32Array>, out: TArg<Uint32Array>
|
||||
): void {
|
||||
let x00 = swap8IfBE(s[0]), x01 = swap8IfBE(s[1]), x02 = swap8IfBE(s[2]), x03 = swap8IfBE(s[3]),
|
||||
x04 = swap8IfBE(k[0]), x05 = swap8IfBE(k[1]), x06 = swap8IfBE(k[2]), x07 = swap8IfBE(k[3]),
|
||||
x08 = swap8IfBE(k[4]), x09 = swap8IfBE(k[5]), x10 = swap8IfBE(k[6]), x11 = swap8IfBE(k[7]),
|
||||
x12 = swap8IfBE(i[0]), x13 = swap8IfBE(i[1]), x14 = swap8IfBE(i[2]), x15 = swap8IfBE(i[3]);
|
||||
for (let r = 0; r < 20; r += 2) {
|
||||
x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 16);
|
||||
x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 12);
|
||||
x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 8);
|
||||
x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 7);
|
||||
|
||||
x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 16);
|
||||
x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 12);
|
||||
x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 8);
|
||||
x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 7);
|
||||
|
||||
x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 16);
|
||||
x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 12);
|
||||
x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 8);
|
||||
x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 7);
|
||||
|
||||
x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 16);
|
||||
x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 12);
|
||||
x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 8)
|
||||
x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 7);
|
||||
|
||||
x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 16);
|
||||
x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 12);
|
||||
x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 8);
|
||||
x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 7);
|
||||
|
||||
x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 16);
|
||||
x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 12);
|
||||
x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 8);
|
||||
x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 7);
|
||||
|
||||
x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 16);
|
||||
x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 12);
|
||||
x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 8);
|
||||
x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 7);
|
||||
|
||||
x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 16)
|
||||
x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 12);
|
||||
x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 8);
|
||||
x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 7);
|
||||
}
|
||||
// HChaCha derives the subkey from state words 0..3 and 12..15 after 20 rounds.
|
||||
let oi = 0;
|
||||
out[oi++] = x00; out[oi++] = x01;
|
||||
out[oi++] = x02; out[oi++] = x03;
|
||||
out[oi++] = x12; out[oi++] = x13;
|
||||
out[oi++] = x14; out[oi++] = x15;
|
||||
swap32IfBE(out);
|
||||
}
|
||||
|
||||
/**
|
||||
* Original, non-RFC chacha20 from DJB. 8-byte nonce, 8-byte counter.
|
||||
* The nonce/counter layout still reserves 8 counter bytes internally, but the shared public
|
||||
* `counter` argument follows noble's strict non-wrapping 32-bit policy. See `src/_arx.ts`
|
||||
* near `MAX_COUNTER` for the full counter-policy rationale.
|
||||
* @param key - 16-byte or 32-byte key.
|
||||
* @param nonce - 8-byte nonce.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Initial block counter.
|
||||
* @returns Encrypted or decrypted bytes.
|
||||
* @example
|
||||
* Encrypts bytes with the original 8-byte-nonce ChaCha variant and a fresh key/nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { chacha20orig } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(8);
|
||||
* chacha20orig(key, nonce, new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export const chacha20orig: TRet<XorStream> = /* @__PURE__ */ createCipher(chachaCore, {
|
||||
counterRight: false,
|
||||
counterLength: 8,
|
||||
allowShortKeys: true,
|
||||
});
|
||||
/**
|
||||
* ChaCha stream cipher. Conforms to RFC 8439 (IETF, TLS). 12-byte nonce, 4-byte counter.
|
||||
* With smaller nonce, it's not safe to make it random (CSPRNG), due to collision chance.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 12-byte nonce.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Initial block counter.
|
||||
* @returns Encrypted or decrypted bytes.
|
||||
* @example
|
||||
* Encrypts bytes with the RFC 8439 ChaCha20 stream cipher and a fresh key/nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { chacha20 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(12);
|
||||
* chacha20(key, nonce, new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export const chacha20: TRet<XorStream> = /* @__PURE__ */ createCipher(chachaCore, {
|
||||
counterRight: false,
|
||||
counterLength: 4,
|
||||
allowShortKeys: false,
|
||||
});
|
||||
|
||||
/**
|
||||
* XChaCha eXtended-nonce ChaCha. With 24-byte nonce, it's safe to make it random (CSPRNG).
|
||||
* See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | the IRTF draft}.
|
||||
* The nonce/counter layout still reserves 8 counter bytes internally, but the shared public
|
||||
* `counter` argument follows noble's strict non-wrapping 32-bit policy. See `src/_arx.ts`
|
||||
* near `MAX_COUNTER` for the full counter-policy rationale.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 24-byte extended nonce.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Initial block counter.
|
||||
* @returns Encrypted or decrypted bytes.
|
||||
* @example
|
||||
* Encrypts bytes with XChaCha20 using a fresh key and random 24-byte nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { xchacha20 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(24);
|
||||
* xchacha20(key, nonce, new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export const xchacha20: TRet<XorStream> = /* @__PURE__ */ createCipher(chachaCore, {
|
||||
counterRight: false,
|
||||
counterLength: 8,
|
||||
extendNonceFn: hchacha,
|
||||
allowShortKeys: false,
|
||||
});
|
||||
|
||||
/**
|
||||
* Reduced 8-round chacha, described in original paper.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 12-byte nonce.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Initial block counter.
|
||||
* @returns Encrypted or decrypted bytes.
|
||||
* @example
|
||||
* Uses the reduced 8-round variant for non-critical workloads with a fresh key/nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { chacha8 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(12);
|
||||
* chacha8(key, nonce, new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export const chacha8: TRet<XorStream> = /* @__PURE__ */ createCipher(chachaCore, {
|
||||
counterRight: false,
|
||||
counterLength: 4,
|
||||
rounds: 8,
|
||||
});
|
||||
|
||||
/**
|
||||
* Reduced 12-round chacha, described in original paper.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 12-byte nonce.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Initial block counter.
|
||||
* @returns Encrypted or decrypted bytes.
|
||||
* @example
|
||||
* Uses the reduced 12-round variant for non-critical workloads with a fresh key/nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { chacha12 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(12);
|
||||
* chacha12(key, nonce, new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export const chacha12: TRet<XorStream> = /* @__PURE__ */ createCipher(chachaCore, {
|
||||
counterRight: false,
|
||||
counterLength: 4,
|
||||
rounds: 12,
|
||||
});
|
||||
|
||||
// Test-only hooks for keeping the simple/reference core aligned with the unrolled production core.
|
||||
export const __TESTS: {
|
||||
chachaCore_small: typeof chachaCore_small;
|
||||
chachaCore: typeof chachaCore;
|
||||
} = /* @__PURE__ */ Object.freeze({ chachaCore_small, chachaCore });
|
||||
|
||||
// RFC 8439 §2.8.1 pad16(x): shared zero block for AAD/ciphertext padding.
|
||||
const ZEROS16 = /* @__PURE__ */ new Uint8Array(16);
|
||||
// RFC 8439 §2.8 / §2.8.1: aligned inputs add nothing, otherwise append 16-(len%16) zero bytes.
|
||||
const updatePadded = (h: ReturnType<typeof poly1305.create>, msg: TArg<Uint8Array>) => {
|
||||
h.update(msg);
|
||||
const leftover = msg.length % 16;
|
||||
if (leftover) h.update(ZEROS16.subarray(leftover));
|
||||
};
|
||||
|
||||
// RFC 8439 §2.6.1 poly1305_key_gen returns `block[0..31]`, so AEAD key
|
||||
// generation only needs 32 zero bytes.
|
||||
const ZEROS32 = /* @__PURE__ */ new Uint8Array(32);
|
||||
function computeTag(
|
||||
fn: TArg<XorStream>,
|
||||
key: TArg<Uint8Array>,
|
||||
nonce: TArg<Uint8Array>,
|
||||
ciphertext: TArg<Uint8Array>,
|
||||
AAD?: TArg<Uint8Array>
|
||||
): TRet<Uint8Array> {
|
||||
if (AAD !== undefined) abytes(AAD, undefined, 'AAD');
|
||||
// RFC 8439 §2.6 / §2.8: derive the Poly1305 one-time key from counter 0,
|
||||
// then MAC AAD || pad16(AAD) || ciphertext || pad16(ciphertext) || len(AAD) || len(ciphertext).
|
||||
const authKey = fn(
|
||||
key as TRet<Uint8Array>,
|
||||
nonce as TRet<Uint8Array>,
|
||||
ZEROS32 as TRet<Uint8Array>
|
||||
);
|
||||
const lengths = u64Lengths(ciphertext.length, AAD ? AAD.length : 0, true);
|
||||
|
||||
// Methods below can be replaced with
|
||||
// return poly1305_computeTag_small(authKey, lengths, ciphertext, AAD)
|
||||
const h = poly1305.create(authKey);
|
||||
if (AAD) updatePadded(h, AAD);
|
||||
updatePadded(h, ciphertext);
|
||||
h.update(lengths);
|
||||
const res = h.digest();
|
||||
clean(authKey, lengths);
|
||||
return res;
|
||||
}
|
||||
|
||||
/**
|
||||
* AEAD algorithm from RFC 8439.
|
||||
* Salsa20 and chacha (RFC 8439) use poly1305 differently.
|
||||
* We could have composed them, but it's hard because of authKey:
|
||||
* In salsa20, authKey changes position in salsa stream.
|
||||
* In chacha, authKey can't be computed inside computeTag, it modifies the counter.
|
||||
*/
|
||||
export const _poly1305_aead =
|
||||
(xorStream: TArg<XorStream>) =>
|
||||
(key: TArg<Uint8Array>, nonce: TArg<Uint8Array>, AAD?: TArg<Uint8Array>): CipherWithOutput => {
|
||||
// This borrows caller key/nonce/AAD buffers by reference; mutating them after construction
|
||||
// changes future encrypt/decrypt results.
|
||||
const tagLength = 16;
|
||||
return {
|
||||
encrypt(plaintext: TArg<Uint8Array>, output?: TArg<Uint8Array>): TRet<Uint8Array> {
|
||||
const plength = plaintext.length;
|
||||
output = getOutput(plength + tagLength, output, false);
|
||||
output.set(plaintext);
|
||||
const oPlain = output.subarray(0, -tagLength);
|
||||
// RFC 8439 §2.8: payload encryption starts at counter 1 because counter 0 produced the OTK.
|
||||
xorStream(
|
||||
key as TRet<Uint8Array>,
|
||||
nonce as TRet<Uint8Array>,
|
||||
oPlain as TRet<Uint8Array>,
|
||||
oPlain as TRet<Uint8Array>,
|
||||
1
|
||||
);
|
||||
const tag = computeTag(xorStream, key, nonce, oPlain, AAD);
|
||||
output.set(tag, plength); // append tag
|
||||
clean(tag);
|
||||
return output as TRet<Uint8Array>;
|
||||
},
|
||||
decrypt(ciphertext: TArg<Uint8Array>, output?: TArg<Uint8Array>): TRet<Uint8Array> {
|
||||
output = getOutput(ciphertext.length - tagLength, output, false);
|
||||
const data = ciphertext.subarray(0, -tagLength);
|
||||
const passedTag = ciphertext.subarray(-tagLength);
|
||||
const tag = computeTag(xorStream, key, nonce, data, AAD);
|
||||
// RFC 8439 §2.8 / §4: authenticate ciphertext before decrypting it, and compare tags with
|
||||
// the constant-time equalBytes() helper rather than decrypting speculative plaintext first.
|
||||
if (!equalBytes(passedTag, tag)) {
|
||||
clean(tag);
|
||||
throw new Error('invalid tag');
|
||||
}
|
||||
output.set(ciphertext.subarray(0, -tagLength));
|
||||
// Actual decryption
|
||||
xorStream(
|
||||
key as TRet<Uint8Array>,
|
||||
nonce as TRet<Uint8Array>,
|
||||
output as TRet<Uint8Array>,
|
||||
output as TRet<Uint8Array>,
|
||||
1
|
||||
); // start stream with i=1
|
||||
clean(tag);
|
||||
return output as TRet<Uint8Array>;
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* ChaCha20-Poly1305 from RFC 8439.
|
||||
*
|
||||
* Unsafe to use random nonces under the same key, due to collision chance.
|
||||
* Prefer XChaCha instead.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 12-byte nonce.
|
||||
* @param AAD - Additional authenticated data.
|
||||
* @returns AEAD cipher instance.
|
||||
* @example
|
||||
* Encrypts and authenticates plaintext with a fresh key and nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { chacha20poly1305 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(12);
|
||||
* const cipher = chacha20poly1305(key, nonce);
|
||||
* cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export const chacha20poly1305: TRet<ARXCipher> = /* @__PURE__ */ wrapCipher(
|
||||
{ blockSize: 64, nonceLength: 12, tagLength: 16 },
|
||||
/* @__PURE__ */ _poly1305_aead(chacha20)
|
||||
);
|
||||
/**
|
||||
* XChaCha20-Poly1305 extended-nonce chacha.
|
||||
*
|
||||
* Can be safely used with random nonces (CSPRNG).
|
||||
* See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | the IRTF draft}.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 24-byte nonce.
|
||||
* @param AAD - Additional authenticated data.
|
||||
* @returns AEAD cipher instance.
|
||||
* @example
|
||||
* Encrypts and authenticates plaintext with a fresh key and random 24-byte nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(24);
|
||||
* const cipher = xchacha20poly1305(key, nonce);
|
||||
* cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export const xchacha20poly1305: TRet<ARXCipher> = /* @__PURE__ */ wrapCipher(
|
||||
{ blockSize: 64, nonceLength: 24, tagLength: 16 },
|
||||
/* @__PURE__ */ _poly1305_aead(xchacha20)
|
||||
);
|
||||
|
||||
/**
|
||||
* Chacha20 CSPRNG (cryptographically secure pseudorandom number generator).
|
||||
* It's best to limit usage to non-production, non-critical cases: for example, test-only.
|
||||
* Compatible with libtomcrypt. It does not have a specification, so unclear how secure it is.
|
||||
* @param seed - Optional seed bytes mixed into the internal `key || nonce` state. When omitted,
|
||||
* only 32 random bytes are mixed into the 40-byte state.
|
||||
* @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`.
|
||||
* @example
|
||||
* Seeds the test-only ChaCha20 DRBG from fresh entropy.
|
||||
*
|
||||
* ```ts
|
||||
* import { rngChacha20 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const seed = randomBytes(32);
|
||||
* const prg = rngChacha20(seed);
|
||||
* prg.randomBytes(8);
|
||||
* ```
|
||||
*/
|
||||
export const rngChacha20: TRet<XorPRG> = /* @__PURE__ */ createPRG(chacha20orig, 64, 32, 8);
|
||||
/**
|
||||
* Chacha20/8 CSPRNG (cryptographically secure pseudorandom number generator).
|
||||
* It's best to limit usage to non-production, non-critical cases: for example, test-only.
|
||||
* Faster than `rngChacha20`.
|
||||
* @param seed - Optional seed bytes mixed into the internal `key || nonce` state. When omitted,
|
||||
* only 32 random bytes are mixed into the 44-byte state.
|
||||
* @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`.
|
||||
* @example
|
||||
* Seeds the faster test-only ChaCha8 DRBG from fresh entropy.
|
||||
*
|
||||
* ```ts
|
||||
* import { rngChacha8 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const seed = randomBytes(32);
|
||||
* const prg = rngChacha8(seed);
|
||||
* prg.randomBytes(8);
|
||||
* ```
|
||||
*/
|
||||
export const rngChacha8: TRet<XorPRG> = /* @__PURE__ */ createPRG(chacha8, 64, 32, 12);
|
||||
221
node_modules/@noble/ciphers/src/ff1.ts
generated
vendored
Normal file
221
node_modules/@noble/ciphers/src/ff1.ts
generated
vendored
Normal file
@@ -0,0 +1,221 @@
|
||||
/**
|
||||
* FPE-FF1 (Format-preserving encryption algorithm) specified in
|
||||
* {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf | NIST 800-38G}.
|
||||
* @module
|
||||
*/
|
||||
import { unsafe } from './aes.ts';
|
||||
import {
|
||||
abytes,
|
||||
anumber,
|
||||
bytesToNumberBE,
|
||||
clean,
|
||||
numberToBytesBE,
|
||||
type Cipher,
|
||||
type TArg,
|
||||
type TRet,
|
||||
} from './utils.ts';
|
||||
|
||||
// NIST SP 800-38G §4.3 / §5.1 Algorithm 7: FF1's designated CIPH_K here is AES, so this file
|
||||
// reuses the reviewed AES key schedule and single-block encryption helpers.
|
||||
// NOTE: no point in inlining encrypt instead of encryptBlock, since BigInt stuff will be slow
|
||||
const { expandKeyLE, encryptBlock } = unsafe;
|
||||
|
||||
// Format-preserving encryption algorithm (FPE-FF1) specified in
|
||||
// {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf | NIST Special Publication 800-38G}.
|
||||
|
||||
const BLOCK_LEN = 16;
|
||||
|
||||
// FF1 step 6vi needs mathematical modulo in [0, b); JS `%` is remainder, so decrypt rounds must
|
||||
// map negative intermediate values back into that range.
|
||||
function mod(a: number, b: number): number;
|
||||
function mod(a: bigint, b: bigint): bigint;
|
||||
function mod(a: any, b: any): number | bigint {
|
||||
const result = a % b;
|
||||
return result >= 0 ? result : b + result;
|
||||
}
|
||||
|
||||
function NUMradix(radix: number, data: number[]): bigint {
|
||||
let res = BigInt(0);
|
||||
for (let i of data) res = res * BigInt(radix) + BigInt(i);
|
||||
return res;
|
||||
}
|
||||
|
||||
function getRound(radix: number, key: TArg<Uint8Array>, tweak: TArg<Uint8Array>, x: number[]) {
|
||||
if (radix > 2 ** 16 - 1) throw new Error('invalid radix ' + radix);
|
||||
// radix**minlen ≥ 100
|
||||
const minLen = Math.ceil(Math.log(100) / Math.log(radix));
|
||||
const maxLen = 2 ** 32 - 1;
|
||||
// 2 ≤ minlen ≤ maxlen < 2**32
|
||||
if (2 > minLen || minLen > maxLen || maxLen >= 2 ** 32)
|
||||
throw new Error('Invalid radix: 2 ≤ minlen ≤ maxlen < 2**32');
|
||||
if (!Array.isArray(x)) throw new Error('invalid X');
|
||||
if (x.length < minLen || x.length > maxLen) throw new Error('X is outside minLen..maxLen bounds');
|
||||
// SP 800-38G defines FF1 over numeral strings in base `radix`; out-of-range digits must fail
|
||||
// before NUMradix(...) or round splitting can reinterpret them as a different numeral string.
|
||||
for (const i of x) {
|
||||
if (!Number.isSafeInteger(i) || i < 0 || i >= radix)
|
||||
throw new Error('invalid X: digit outside radix');
|
||||
}
|
||||
const u = Math.floor(x.length / 2);
|
||||
const v = x.length - u;
|
||||
const b = Math.ceil(Math.ceil(v * Math.log2(radix)) / 8);
|
||||
const d = 4 * Math.ceil(b / 4) + 4;
|
||||
const padding = mod(-tweak.length - b - 1, 16);
|
||||
// P = [1]1 || [2]1 || [1]1 || [radix]3 || [10]1 || [u mod 256]1 || [n]4 || [t]4.
|
||||
const P = Uint8Array.from([1, 2, 1, 0, 0, 0, 10, u, 0, 0, 0, 0, 0, 0, 0, 0]);
|
||||
const view = new DataView(P.buffer);
|
||||
// NIST SP 800-38G §5.1 bounds radix <= 2^16, so the 24-bit [radix]3 field is encoded here as
|
||||
// 0x00 || uint16_be(radix).
|
||||
view.setUint16(4, radix, false);
|
||||
view.setUint32(8, x.length, false);
|
||||
view.setUint32(12, tweak.length, false);
|
||||
// Q = T || [0](−t−b−1) mod 16 || [i]1 || [NUMradix(B)]b.
|
||||
const PQ = new Uint8Array(P.length + tweak.length + padding + 1 + b);
|
||||
PQ.set(P);
|
||||
clean(P);
|
||||
PQ.set(tweak, P.length);
|
||||
const xk = expandKeyLE(key);
|
||||
const round = (A: number[], B: number[], i: number, decrypt = false) => {
|
||||
// Q = ... || [i]1 || [NUMradix(B)]b.
|
||||
PQ[PQ.length - b - 1] = i;
|
||||
if (b) PQ.set(numberToBytesBE(NUMradix(radix, B), b), PQ.length - b);
|
||||
// NIST SP 800-38G Algorithm 6 PRF: Y_j = CIPH_K(Y_(j-1) xor X_j) starting from Y_0 = 0^128.
|
||||
let r = new Uint8Array(16);
|
||||
for (let j = 0; j < PQ.length / BLOCK_LEN; j++) {
|
||||
for (let i = 0; i < BLOCK_LEN; i++) r[i] ^= PQ[j * BLOCK_LEN + i];
|
||||
encryptBlock(xk, r);
|
||||
}
|
||||
// Let S be the first d bytes of the following string of ⎡d/16⎤ blocks:
|
||||
// R || CIPHK(R ⊕[1]16) || CIPHK(R ⊕[2]16) ...CIPHK(R ⊕[⎡d / 16⎤ – 1]16).
|
||||
let s = Array.from(r);
|
||||
for (let j = 1; s.length < d; j++) {
|
||||
const block = numberToBytesBE(BigInt(j), 16);
|
||||
for (let k = 0; k < BLOCK_LEN; k++) block[k] ^= r[k];
|
||||
s.push(...Array.from(encryptBlock(xk, block)));
|
||||
}
|
||||
let y = bytesToNumberBE(Uint8Array.from(s.slice(0, d)));
|
||||
s.fill(0);
|
||||
if (decrypt) y = -y;
|
||||
const m = i % 2 === 0 ? u : v;
|
||||
let c = mod(NUMradix(radix, A) + y, BigInt(radix) ** BigInt(m));
|
||||
// STR(radix, m, c)
|
||||
const C = Array(m).fill(0);
|
||||
for (let i = 0; i < m; i++, c /= BigInt(radix)) C[m - 1 - i] = Number(c % BigInt(radix));
|
||||
A.fill(0);
|
||||
A = B;
|
||||
B = C;
|
||||
return [A, B];
|
||||
};
|
||||
const destroy = () => {
|
||||
clean(xk, PQ);
|
||||
};
|
||||
return { u, round, destroy };
|
||||
}
|
||||
|
||||
const EMPTY_BUF = /* @__PURE__ */ Uint8Array.of();
|
||||
|
||||
/**
|
||||
* FPE-FF1 format-preserving encryption.
|
||||
* @param radix - Alphabet size for each input digit.
|
||||
* @param key - AES key bytes.
|
||||
* @param tweak - Optional tweak bytes.
|
||||
* @returns Encrypt/decrypt helpers over digit arrays.
|
||||
* @example
|
||||
* Encrypts decimal digits without changing their format, using a fresh AES key.
|
||||
*
|
||||
* ```ts
|
||||
* import { FF1 } from '@noble/ciphers/ff1.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const ff1 = FF1(10, key);
|
||||
* ff1.encrypt([1, 2, 3]);
|
||||
* ```
|
||||
*/
|
||||
export function FF1(
|
||||
radix: number,
|
||||
key: TArg<Uint8Array>,
|
||||
tweak: TArg<Uint8Array> = EMPTY_BUF
|
||||
): { encrypt(x: number[]): number[]; decrypt(x: number[]): number[] } {
|
||||
anumber(radix);
|
||||
abytes(key);
|
||||
abytes(tweak);
|
||||
// This borrows caller key/tweak buffers by reference through the bound closure; mutating them
|
||||
// after construction changes later encrypt/decrypt outputs.
|
||||
const PQ = getRound.bind(null, radix, key, tweak);
|
||||
return {
|
||||
encrypt(x: number[]): number[] {
|
||||
const { u, round, destroy } = PQ(x);
|
||||
let [A, B] = [x.slice(0, u), x.slice(u)];
|
||||
for (let i = 0; i < 10; i++) [A, B] = round(A, B, i);
|
||||
destroy();
|
||||
const res = A.concat(B);
|
||||
A.fill(0);
|
||||
B.fill(0);
|
||||
return res;
|
||||
},
|
||||
decrypt(x: number[]): number[] {
|
||||
const { u, round, destroy } = PQ(x);
|
||||
// The FF1.Decrypt algorithm is similar to the FF1.Encrypt algorithm;
|
||||
// the differences are in Step 6, where:
|
||||
// 1) the order of the indices is reversed,
|
||||
// 2) the roles of A and B are swapped
|
||||
// 3) modular addition is replaced by modular subtraction, in Step 6vi.
|
||||
let [B, A] = [x.slice(0, u), x.slice(u)];
|
||||
for (let i = 9; i >= 0; i--) [A, B] = round(A, B, i, true);
|
||||
destroy();
|
||||
const res = B.concat(A);
|
||||
A.fill(0);
|
||||
B.fill(0);
|
||||
return res;
|
||||
},
|
||||
};
|
||||
}
|
||||
// Binary wrapper uses little-endian bit order within each byte so bit 0 stays
|
||||
// in the first numeral slot for this library-defined byte-array surface.
|
||||
const binLE = {
|
||||
encode(bytes: TArg<Uint8Array>): number[] {
|
||||
const x = [];
|
||||
for (let i = 0; i < bytes.length; i++) {
|
||||
for (let j = 0, tmp = bytes[i]; j < 8; j++, tmp >>= 1) x.push(tmp & 1);
|
||||
}
|
||||
return x;
|
||||
},
|
||||
decode(b: number[]): TRet<Uint8Array> {
|
||||
if (!Array.isArray(b) || b.length % 8) throw new Error('Invalid binary string');
|
||||
const res = new Uint8Array(b.length / 8);
|
||||
for (let i = 0, j = 0; i < res.length; i++) {
|
||||
res[i] = b[j++] | (b[j++] << 1) | (b[j++] << 2) | (b[j++] << 3);
|
||||
res[i] |= (b[j++] << 4) | (b[j++] << 5) | (b[j++] << 6) | (b[j++] << 7);
|
||||
}
|
||||
return res as TRet<Uint8Array>;
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Binary FPE-FF1 wrapper over byte arrays.
|
||||
* @param key - AES key bytes.
|
||||
* @param tweak - Optional tweak bytes.
|
||||
* @returns Encrypt/decrypt helpers over byte arrays.
|
||||
* @example
|
||||
* Encrypts raw bytes through FF1's binary alphabet wrapper with a fresh AES key.
|
||||
*
|
||||
* ```ts
|
||||
* import { BinaryFF1 } from '@noble/ciphers/ff1.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const ff1 = BinaryFF1(key);
|
||||
* ff1.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export function BinaryFF1(
|
||||
key: TArg<Uint8Array>,
|
||||
tweak: TArg<Uint8Array> = EMPTY_BUF
|
||||
): TRet<Cipher> {
|
||||
const ff1 = FF1(2, key, tweak);
|
||||
return {
|
||||
encrypt: (x: TArg<Uint8Array>): TRet<Uint8Array> =>
|
||||
binLE.decode(ff1.encrypt(binLE.encode(x))) as TRet<Uint8Array>,
|
||||
decrypt: (x: TArg<Uint8Array>): TRet<Uint8Array> =>
|
||||
binLE.decode(ff1.decrypt(binLE.encode(x))) as TRet<Uint8Array>,
|
||||
} as TRet<Cipher>;
|
||||
}
|
||||
25
node_modules/@noble/ciphers/src/index.ts
generated
vendored
Normal file
25
node_modules/@noble/ciphers/src/index.ts
generated
vendored
Normal file
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* Audited & minimal JS implementation of Salsa20, ChaCha and AES. Check out individual modules.
|
||||
* @example
|
||||
```js
|
||||
import { gcm, aessiv } from '@noble/ciphers/aes.js';
|
||||
import { xsalsa20poly1305 } from '@noble/ciphers/salsa.js';
|
||||
import { secretbox } from '@noble/ciphers/salsa.js'; // == xsalsa20poly1305
|
||||
import { chacha20poly1305, xchacha20poly1305 } from '@noble/ciphers/chacha.js';
|
||||
|
||||
// Unauthenticated encryption: make sure to use HMAC or similar
|
||||
import { ctr, cfb, cbc, ecb } from '@noble/ciphers/aes.js';
|
||||
import { salsa20, xsalsa20 } from '@noble/ciphers/salsa.js';
|
||||
import { chacha20, xchacha20, chacha8, chacha12 } from '@noble/ciphers/chacha.js';
|
||||
|
||||
// KW
|
||||
import { aeskw, aeskwp } from '@noble/ciphers/aes.js';
|
||||
|
||||
// Utilities
|
||||
import { managedNonce, randomBytes, bytesToHex, hexToBytes } from '@noble/ciphers/utils.js';
|
||||
import { poly1305 } from '@noble/ciphers/_poly1305.js';
|
||||
import { ghash, polyval } from '@noble/ciphers/_polyval.js';
|
||||
```
|
||||
* @module
|
||||
*/
|
||||
throw new Error('root module cannot be imported: import submodules instead. Check out README');
|
||||
374
node_modules/@noble/ciphers/src/salsa.ts
generated
vendored
Normal file
374
node_modules/@noble/ciphers/src/salsa.ts
generated
vendored
Normal file
@@ -0,0 +1,374 @@
|
||||
/**
|
||||
* Salsa20 stream cipher, released in 2005.
|
||||
* Salsa's goal was to implement AES replacement that does not rely on S-Boxes,
|
||||
* which are hard to implement in a constant-time manner.
|
||||
* Salsa20 is usually faster than AES, a big deal on slow, budget mobile phones.
|
||||
*
|
||||
* - {@link https://cr.yp.to/snuffle/xsalsa-20110204.pdf | XSalsa20},
|
||||
* extended-nonce
|
||||
* variant was released in 2008. It extends Salsa20's 64-bit nonce to 192 bits,
|
||||
* and became safe to be picked at random.
|
||||
* - Nacl / Libsodium popularized term "secretbox", - which is just xsalsa20poly1305.
|
||||
* We provide the alias and corresponding seal / open methods.
|
||||
* "crypto_box" and "sealedbox" are available in package
|
||||
* {@link https://github.com/serenity-kit/noble-sodium | noble-sodium}.
|
||||
* - Check out
|
||||
* {@link https://cr.yp.to/snuffle/salsafamily-20071225.pdf | PDF}
|
||||
* and {@link https://cr.yp.to/snuffle.html | website}.
|
||||
* @module
|
||||
*/
|
||||
import { createCipher, rotl } from './_arx.ts';
|
||||
import { poly1305 } from './_poly1305.ts';
|
||||
import {
|
||||
abytes,
|
||||
clean,
|
||||
equalBytes,
|
||||
getOutput,
|
||||
swap32IfBE,
|
||||
swap8IfBE,
|
||||
wrapCipher,
|
||||
type ARXCipher,
|
||||
type CipherWithOutput,
|
||||
type TArg,
|
||||
type TRet,
|
||||
type XorStream,
|
||||
} from './utils.ts';
|
||||
|
||||
/**
|
||||
* Salsa20 core function. It is implemented twice:
|
||||
* 1. Simple loop (salsaCore_small, hsalsa_small)
|
||||
* 2. Unrolled loop (salsaCore, hsalsa) - 4x faster, but larger & harder to read
|
||||
* The specific implementation is selected in `createCipher` below.
|
||||
* Performance numbers for 1MB inputs:
|
||||
* * default x 779 ops/sec @ 1ms/op
|
||||
* * if salsa+hsalsa are merged x 459 ops/sec @ 2ms/op
|
||||
* * small x 132 ops/sec @ 7ms/op
|
||||
*/
|
||||
|
||||
/** RFC 7914 §3 Salsa20/8 core quarter-round on words a, b, c, d. */
|
||||
function salsaQR(x: TArg<Uint32Array>, a: number, b: number, c: number, d: number) {
|
||||
x[b] ^= rotl((x[a] + x[d]) | 0, 7);
|
||||
x[c] ^= rotl((x[b] + x[a]) | 0, 9);
|
||||
x[d] ^= rotl((x[c] + x[b]) | 0, 13);
|
||||
x[a] ^= rotl((x[d] + x[c]) | 0, 18);
|
||||
}
|
||||
|
||||
/** RFC 7914 §3 double-round schedule: four column rounds, then four row rounds. */
|
||||
function salsaRound(x: TArg<Uint32Array>, rounds = 20) {
|
||||
for (let r = 0; r < rounds; r += 2) {
|
||||
salsaQR(x, 0, 4, 8, 12);
|
||||
salsaQR(x, 5, 9, 13, 1);
|
||||
salsaQR(x, 10, 14, 2, 6);
|
||||
salsaQR(x, 15, 3, 7, 11);
|
||||
salsaQR(x, 0, 1, 2, 3);
|
||||
salsaQR(x, 5, 6, 7, 4);
|
||||
salsaQR(x, 10, 11, 8, 9);
|
||||
salsaQR(x, 15, 12, 13, 14);
|
||||
}
|
||||
}
|
||||
|
||||
// Shared scratch for the unused auditability helper below; it would be
|
||||
// non-reentrant under overlapping/nested calls, but current code doesn't invoke it.
|
||||
const stmp = /* @__PURE__ */ new Uint32Array(16);
|
||||
|
||||
/** Small version of salsa without loop unrolling. Unused, provided for auditability. */
|
||||
// prettier-ignore
|
||||
function salsa(
|
||||
s: TArg<Uint32Array>, k: TArg<Uint32Array>, i: TArg<Uint32Array>, out: TArg<Uint32Array>,
|
||||
isHSalsa: boolean = true, rounds: number = 20
|
||||
): void {
|
||||
// Create initial array using common pattern
|
||||
const y = Uint32Array.from([
|
||||
s[0], k[0], k[1], k[2], // "expa" Key Key Key
|
||||
k[3], s[1], i[0], i[1], // Key "nd 3" Nonce Nonce
|
||||
i[2], i[3], s[2], k[4], // Pos. Pos. "2-by" Key
|
||||
k[5], k[6], k[7], s[3], // Key Key Key "te k"
|
||||
]);
|
||||
const x = stmp;
|
||||
x.set(y);
|
||||
// const x = y.slice();
|
||||
salsaRound(x, rounds);
|
||||
|
||||
// hsalsa extracts 8 specific words for the 32-byte subkey; salsa adds the original state.
|
||||
if (isHSalsa) {
|
||||
const xindexes = [0, 5, 10, 15, 6, 7, 8, 9];
|
||||
for (let i = 0; i < 8; i++) out[i] = x[xindexes[i]];
|
||||
} else {
|
||||
for (let i = 0; i < 16; i++) out[i] = (y[i] + x[i]) | 0;
|
||||
}
|
||||
}
|
||||
/** Identical to `salsaCore`. Unused. */
|
||||
// @ts-ignore
|
||||
const salsaCore_small: typeof salsaCore = (s, k, n, out, cnt, rounds) =>
|
||||
salsa(s, k, Uint32Array.from([n[0], n[1], cnt, 0]), out, false, rounds);
|
||||
/** Identical to `hsalsa`. Unused. */
|
||||
// @ts-ignore
|
||||
const hsalsa_small: typeof hsalsa = salsa;
|
||||
|
||||
/** Identical to `salsaCore_small`. Uses only the low 32 bits of Salsa20's 64-bit counter state. */
|
||||
// prettier-ignore
|
||||
function salsaCore(
|
||||
s: TArg<Uint32Array>, k: TArg<Uint32Array>, n: TArg<Uint32Array>, out: TArg<Uint32Array>, cnt: number, rounds = 20
|
||||
): void {
|
||||
// Public wrappers expose only the low 32 bits of Salsa20's 64-bit counter; y09 stays zero.
|
||||
// Based on {@link https://cr.yp.to/salsa20.html | the Salsa20 reference page}.
|
||||
let y00 = s[0], y01 = k[0], y02 = k[1], y03 = k[2], // "expa" Key Key Key
|
||||
y04 = k[3], y05 = s[1], y06 = n[0], y07 = n[1], // Key "nd 3" Nonce Nonce
|
||||
y08 = cnt, y09 = 0, y10 = s[2], y11 = k[4], // Pos. Pos. "2-by" Key
|
||||
y12 = k[5], y13 = k[6], y14 = k[7], y15 = s[3]; // Key Key Key "te k"
|
||||
// Save state to temporary variables
|
||||
let x00 = y00, x01 = y01, x02 = y02, x03 = y03,
|
||||
x04 = y04, x05 = y05, x06 = y06, x07 = y07,
|
||||
x08 = y08, x09 = y09, x10 = y10, x11 = y11,
|
||||
x12 = y12, x13 = y13, x14 = y14, x15 = y15;
|
||||
for (let r = 0; r < rounds; r += 2) {
|
||||
x04 ^= rotl(x00 + x12 | 0, 7); x08 ^= rotl(x04 + x00 | 0, 9);
|
||||
x12 ^= rotl(x08 + x04 | 0, 13); x00 ^= rotl(x12 + x08 | 0, 18);
|
||||
x09 ^= rotl(x05 + x01 | 0, 7); x13 ^= rotl(x09 + x05 | 0, 9);
|
||||
x01 ^= rotl(x13 + x09 | 0, 13); x05 ^= rotl(x01 + x13 | 0, 18);
|
||||
x14 ^= rotl(x10 + x06 | 0, 7); x02 ^= rotl(x14 + x10 | 0, 9);
|
||||
x06 ^= rotl(x02 + x14 | 0, 13); x10 ^= rotl(x06 + x02 | 0, 18);
|
||||
x03 ^= rotl(x15 + x11 | 0, 7); x07 ^= rotl(x03 + x15 | 0, 9);
|
||||
x11 ^= rotl(x07 + x03 | 0, 13); x15 ^= rotl(x11 + x07 | 0, 18);
|
||||
x01 ^= rotl(x00 + x03 | 0, 7); x02 ^= rotl(x01 + x00 | 0, 9);
|
||||
x03 ^= rotl(x02 + x01 | 0, 13); x00 ^= rotl(x03 + x02 | 0, 18);
|
||||
x06 ^= rotl(x05 + x04 | 0, 7); x07 ^= rotl(x06 + x05 | 0, 9);
|
||||
x04 ^= rotl(x07 + x06 | 0, 13); x05 ^= rotl(x04 + x07 | 0, 18);
|
||||
x11 ^= rotl(x10 + x09 | 0, 7); x08 ^= rotl(x11 + x10 | 0, 9);
|
||||
x09 ^= rotl(x08 + x11 | 0, 13); x10 ^= rotl(x09 + x08 | 0, 18);
|
||||
x12 ^= rotl(x15 + x14 | 0, 7); x13 ^= rotl(x12 + x15 | 0, 9);
|
||||
x14 ^= rotl(x13 + x12 | 0, 13); x15 ^= rotl(x14 + x13 | 0, 18);
|
||||
}
|
||||
// Write output
|
||||
let oi = 0;
|
||||
out[oi++] = (y00 + x00) | 0; out[oi++] = (y01 + x01) | 0;
|
||||
out[oi++] = (y02 + x02) | 0; out[oi++] = (y03 + x03) | 0;
|
||||
out[oi++] = (y04 + x04) | 0; out[oi++] = (y05 + x05) | 0;
|
||||
out[oi++] = (y06 + x06) | 0; out[oi++] = (y07 + x07) | 0;
|
||||
out[oi++] = (y08 + x08) | 0; out[oi++] = (y09 + x09) | 0;
|
||||
out[oi++] = (y10 + x10) | 0; out[oi++] = (y11 + x11) | 0;
|
||||
out[oi++] = (y12 + x12) | 0; out[oi++] = (y13 + x13) | 0;
|
||||
out[oi++] = (y14 + x14) | 0; out[oi++] = (y15 + x15) | 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* hsalsa hashes key and nonce-prefix words into the 32-byte subkey used by XSalsa20.
|
||||
* Identical to `hsalsa_small`.
|
||||
* Need to find a way to merge it with `salsaCore` without 25% performance hit.
|
||||
* @param s - Sigma constants as 32-bit words.
|
||||
* @param k - Key words.
|
||||
* @param i - Nonce-prefix words.
|
||||
* @param out - Output buffer for the derived subkey.
|
||||
* @example
|
||||
* Derives the XSalsa20 subkey from sigma, key, and nonce-prefix words.
|
||||
*
|
||||
* ```ts
|
||||
* const sigma = new Uint32Array(4);
|
||||
* const key = new Uint32Array(8);
|
||||
* const nonce = new Uint32Array(4);
|
||||
* const out = new Uint32Array(8);
|
||||
* hsalsa(sigma, key, nonce, out);
|
||||
* ```
|
||||
*/
|
||||
// prettier-ignore
|
||||
export function hsalsa(
|
||||
s: TArg<Uint32Array>, k: TArg<Uint32Array>, i: TArg<Uint32Array>, out: TArg<Uint32Array>
|
||||
): void {
|
||||
let x00 = swap8IfBE(s[0]), x01 = swap8IfBE(k[0]), x02 = swap8IfBE(k[1]), x03 = swap8IfBE(k[2]),
|
||||
x04 = swap8IfBE(k[3]), x05 = swap8IfBE(s[1]), x06 = swap8IfBE(i[0]), x07 = swap8IfBE(i[1]),
|
||||
x08 = swap8IfBE(i[2]), x09 = swap8IfBE(i[3]), x10 = swap8IfBE(s[2]), x11 = swap8IfBE(k[4]),
|
||||
x12 = swap8IfBE(k[5]), x13 = swap8IfBE(k[6]), x14 = swap8IfBE(k[7]), x15 = swap8IfBE(s[3]);
|
||||
for (let r = 0; r < 20; r += 2) {
|
||||
x04 ^= rotl(x00 + x12 | 0, 7); x08 ^= rotl(x04 + x00 | 0, 9);
|
||||
x12 ^= rotl(x08 + x04 | 0, 13); x00 ^= rotl(x12 + x08 | 0, 18);
|
||||
x09 ^= rotl(x05 + x01 | 0, 7); x13 ^= rotl(x09 + x05 | 0, 9);
|
||||
x01 ^= rotl(x13 + x09 | 0, 13); x05 ^= rotl(x01 + x13 | 0, 18);
|
||||
x14 ^= rotl(x10 + x06 | 0, 7); x02 ^= rotl(x14 + x10 | 0, 9);
|
||||
x06 ^= rotl(x02 + x14 | 0, 13); x10 ^= rotl(x06 + x02 | 0, 18);
|
||||
x03 ^= rotl(x15 + x11 | 0, 7); x07 ^= rotl(x03 + x15 | 0, 9);
|
||||
x11 ^= rotl(x07 + x03 | 0, 13); x15 ^= rotl(x11 + x07 | 0, 18);
|
||||
x01 ^= rotl(x00 + x03 | 0, 7); x02 ^= rotl(x01 + x00 | 0, 9);
|
||||
x03 ^= rotl(x02 + x01 | 0, 13); x00 ^= rotl(x03 + x02 | 0, 18);
|
||||
x06 ^= rotl(x05 + x04 | 0, 7); x07 ^= rotl(x06 + x05 | 0, 9);
|
||||
x04 ^= rotl(x07 + x06 | 0, 13); x05 ^= rotl(x04 + x07 | 0, 18);
|
||||
x11 ^= rotl(x10 + x09 | 0, 7); x08 ^= rotl(x11 + x10 | 0, 9);
|
||||
x09 ^= rotl(x08 + x11 | 0, 13); x10 ^= rotl(x09 + x08 | 0, 18);
|
||||
x12 ^= rotl(x15 + x14 | 0, 7); x13 ^= rotl(x12 + x15 | 0, 9);
|
||||
x14 ^= rotl(x13 + x12 | 0, 13); x15 ^= rotl(x14 + x13 | 0, 18);
|
||||
}
|
||||
let oi = 0;
|
||||
// XSalsa20 takes words 0,5,10,15 and 6,7,8,9 as the 32-byte subkey material.
|
||||
out[oi++] = x00; out[oi++] = x05;
|
||||
out[oi++] = x10; out[oi++] = x15;
|
||||
out[oi++] = x06; out[oi++] = x07;
|
||||
out[oi++] = x08; out[oi++] = x09;
|
||||
swap32IfBE(out);
|
||||
}
|
||||
|
||||
/**
|
||||
* Salsa20 from original paper. 8-byte nonce.
|
||||
* With smaller nonce, it's not safe to make it random (CSPRNG), due to collision chance.
|
||||
* @param key - 16-byte or 32-byte key.
|
||||
* @param nonce - 8-byte nonce.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Initial block counter.
|
||||
* Only the low 32 bits of Salsa20's 64-bit counter state are exposed here;
|
||||
* the high word stays zero and the implementation still caps the public
|
||||
* value to 32 bits.
|
||||
* @returns Encrypted or decrypted bytes.
|
||||
* @example
|
||||
* Encrypts bytes with the original 8-byte-nonce Salsa20 stream cipher.
|
||||
*
|
||||
* ```ts
|
||||
* import { salsa20 } from '@noble/ciphers/salsa.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(8);
|
||||
* salsa20(key, nonce, new Uint8Array([1, 2, 3, 4]));
|
||||
* ```
|
||||
*/
|
||||
export const salsa20: TRet<XorStream> = /* @__PURE__ */ createCipher(salsaCore, {
|
||||
allowShortKeys: true,
|
||||
counterRight: true,
|
||||
});
|
||||
|
||||
/**
|
||||
* XSalsa20 extended-nonce salsa.
|
||||
* With 24-byte nonce, it's safe to make it random (CSPRNG).
|
||||
* @param key - 32-byte key.
|
||||
* This XSalsa20 wrapper does not enable Salsa20's 16-byte legacy key mode.
|
||||
* @param nonce - 24-byte nonce.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Initial block counter.
|
||||
* @returns Encrypted or decrypted bytes.
|
||||
* @example
|
||||
* Encrypts bytes with XSalsa20 and a random 24-byte nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { xsalsa20 } from '@noble/ciphers/salsa.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(24);
|
||||
* xsalsa20(key, nonce, new Uint8Array([1, 2, 3, 4]));
|
||||
* ```
|
||||
*/
|
||||
export const xsalsa20: TRet<XorStream> = /* @__PURE__ */ createCipher(salsaCore, {
|
||||
counterRight: true,
|
||||
extendNonceFn: hsalsa,
|
||||
});
|
||||
|
||||
/**
|
||||
* xsalsa20-poly1305 eXtended-nonce (24 bytes) salsa.
|
||||
* With 24-byte nonce, it's safe to make it random (CSPRNG).
|
||||
* Also known as `secretbox` from libsodium / nacl.
|
||||
* No AAD input is supported here. Caller-provided `output` buffers for
|
||||
* `encrypt()` / `decrypt()` must be `input.length + 32` bytes because the
|
||||
* implementation uses a 32-byte leading scratch area before returning `+16`.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 24-byte nonce.
|
||||
* @param AAD - Must be omitted; XSalsa20-Poly1305 secretbox does not support associated data.
|
||||
* @returns AEAD cipher instance.
|
||||
* @example
|
||||
* Encrypts and authenticates plaintext with XSalsa20-Poly1305.
|
||||
*
|
||||
* ```ts
|
||||
* import { xsalsa20poly1305 } from '@noble/ciphers/salsa.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(24);
|
||||
* const cipher = xsalsa20poly1305(key, nonce);
|
||||
* cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export const xsalsa20poly1305: TRet<ARXCipher> = /* @__PURE__ */ wrapCipher(
|
||||
{ blockSize: 64, nonceLength: 24, tagLength: 16 },
|
||||
(key: TArg<Uint8Array>, nonce: TArg<Uint8Array>): TRet<CipherWithOutput> => {
|
||||
// This borrows caller key/nonce buffers by reference; mutating them after construction changes
|
||||
// later encrypt/decrypt outputs.
|
||||
return {
|
||||
encrypt(plaintext: TArg<Uint8Array>, output?: TArg<Uint8Array>): TRet<Uint8Array> {
|
||||
// xsalsa20poly1305 optimizes by calculating auth key during the same call as encryption.
|
||||
// Unfortunately, makes it hard to separate tag calculation & encryption itself,
|
||||
// because 32 bytes is half-block of 64-byte salsa.
|
||||
// Need 32 extra bytes up front for the auth-key scratch area described above.
|
||||
output = getOutput(plaintext.length + 32, output, false);
|
||||
// output[0..32] = Poly1305 auth key, output[32..] = plaintext then ciphertext.
|
||||
const authKey = output.subarray(0, 32);
|
||||
const ciphPlaintext = output.subarray(32);
|
||||
output.set(plaintext, 32);
|
||||
// authKey is produced by xoring the first 32 bytes with zeros.
|
||||
clean(authKey);
|
||||
// output = stream ^ output; authKey = stream ^ zeros(32)
|
||||
xsalsa20(key, nonce, output, output);
|
||||
const tag = poly1305(ciphPlaintext, authKey);
|
||||
output.set(tag, 16);
|
||||
// Clean up auth-key remnants and the temporary tag copy.
|
||||
clean(output.subarray(0, 16), tag);
|
||||
// Return output[16..].
|
||||
return output.subarray(16) as TRet<Uint8Array>;
|
||||
},
|
||||
decrypt(ciphertext: TArg<Uint8Array>, output?: TArg<Uint8Array>): TRet<Uint8Array> {
|
||||
// tmp part passed tag ciphertext
|
||||
// [0..32] [32..48] [48..]
|
||||
// Authenticate the ciphertext before decrypting it; on tag failure the scratch/output
|
||||
// buffer may already contain copied ciphertext and derived auth-key material.
|
||||
abytes(ciphertext);
|
||||
output = getOutput(ciphertext.length + 32, output, false);
|
||||
// output[0..32] is auth-key scratch, output[32..48] is passed tag,
|
||||
// output[48..] is ciphertext then plaintext.
|
||||
const tmp = output.subarray(0, 32);
|
||||
const passedTag = output.subarray(32, 48);
|
||||
const ciphPlaintext = output.subarray(48);
|
||||
output.set(ciphertext, 32);
|
||||
// authKey is produced by xoring the scratch area with zeros.
|
||||
clean(tmp);
|
||||
const authKey = xsalsa20(key, nonce, tmp, tmp);
|
||||
const tag = poly1305(ciphPlaintext, authKey);
|
||||
if (!equalBytes(passedTag, tag)) {
|
||||
clean(output);
|
||||
throw new Error('invalid tag');
|
||||
}
|
||||
// output = stream ^ output[16..]
|
||||
xsalsa20(key, nonce, output.subarray(16), output.subarray(16));
|
||||
clean(tmp, passedTag, tag);
|
||||
// Return output[48..], skipping zeroized output[0..48].
|
||||
return ciphPlaintext as TRet<Uint8Array>;
|
||||
},
|
||||
} as TRet<CipherWithOutput>;
|
||||
}
|
||||
);
|
||||
|
||||
/**
|
||||
* Alias to `xsalsa20poly1305`, for compatibility with libsodium / nacl.
|
||||
* Check out {@link https://github.com/serenity-kit/noble-sodium | noble-sodium}
|
||||
* for `crypto_box`.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 24-byte nonce.
|
||||
* @returns Wrapper with `seal()` and `open()` helpers.
|
||||
* @example
|
||||
* Uses the libsodium-style `seal()` and `open()` wrapper.
|
||||
*
|
||||
* ```ts
|
||||
* import { secretbox } from '@noble/ciphers/salsa.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(24);
|
||||
* const box = secretbox(key, nonce);
|
||||
* box.seal(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export function secretbox(
|
||||
key: TArg<Uint8Array>,
|
||||
nonce: TArg<Uint8Array>
|
||||
): TRet<{
|
||||
seal: (plaintext: TArg<Uint8Array>, output?: TArg<Uint8Array>) => TRet<Uint8Array>;
|
||||
open: (ciphertext: TArg<Uint8Array>, output?: TArg<Uint8Array>) => TRet<Uint8Array>;
|
||||
}> {
|
||||
const xs = xsalsa20poly1305(key, nonce);
|
||||
return { seal: xs.encrypt, open: xs.decrypt } as TRet<{
|
||||
seal: (plaintext: TArg<Uint8Array>, output?: TArg<Uint8Array>) => TRet<Uint8Array>;
|
||||
open: (ciphertext: TArg<Uint8Array>, output?: TArg<Uint8Array>) => TRet<Uint8Array>;
|
||||
}>;
|
||||
}
|
||||
1191
node_modules/@noble/ciphers/src/utils.ts
generated
vendored
Normal file
1191
node_modules/@noble/ciphers/src/utils.ts
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
226
node_modules/@noble/ciphers/src/webcrypto.ts
generated
vendored
Normal file
226
node_modules/@noble/ciphers/src/webcrypto.ts
generated
vendored
Normal file
@@ -0,0 +1,226 @@
|
||||
/**
|
||||
* WebCrypto-based AES gcm/ctr/cbc, `managedNonce` and `randomBytes`.
|
||||
* We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
|
||||
* @module
|
||||
*/
|
||||
import { abytes, anumber, type AsyncCipher, type TArg, type TRet } from './utils.ts';
|
||||
|
||||
function getWebcryptoSubtle(): any {
|
||||
const cr = typeof globalThis !== 'undefined' && (globalThis as any).crypto;
|
||||
if (cr && typeof cr.subtle === 'object' && cr.subtle != null) return cr.subtle;
|
||||
throw new Error('crypto.subtle must be defined');
|
||||
}
|
||||
|
||||
type WebcryptoUtils = {
|
||||
encrypt(
|
||||
key: TArg<Uint8Array>,
|
||||
keyParams: unknown,
|
||||
cryptParams: unknown,
|
||||
plaintext: TArg<Uint8Array>
|
||||
): Promise<TRet<Uint8Array>>;
|
||||
decrypt(
|
||||
key: TArg<Uint8Array>,
|
||||
keyParams: unknown,
|
||||
cryptParams: unknown,
|
||||
ciphertext: TArg<Uint8Array>
|
||||
): Promise<TRet<Uint8Array>>;
|
||||
};
|
||||
/**
|
||||
* Internal webcrypto utils. Can be overridden if crypto.subtle is not present,
|
||||
* for example in React Native.
|
||||
* Raw keys are re-imported on every call; this wrapper intentionally does not
|
||||
* cache `CryptoKey` objects between operations.
|
||||
*/
|
||||
export const utils: TRet<WebcryptoUtils> = {
|
||||
async encrypt(
|
||||
key: TArg<Uint8Array>,
|
||||
keyParams: any,
|
||||
cryptParams: any,
|
||||
plaintext: TArg<Uint8Array>
|
||||
): Promise<TRet<Uint8Array>> {
|
||||
const cr = getWebcryptoSubtle();
|
||||
const iKey = await cr.importKey('raw', key, keyParams, true, ['encrypt']);
|
||||
const ciphertext = await cr.encrypt(cryptParams, iKey, plaintext);
|
||||
return new Uint8Array(ciphertext) as TRet<Uint8Array>;
|
||||
},
|
||||
async decrypt(
|
||||
key: TArg<Uint8Array>,
|
||||
keyParams: any,
|
||||
cryptParams: any,
|
||||
ciphertext: TArg<Uint8Array>
|
||||
): Promise<TRet<Uint8Array>> {
|
||||
const cr = getWebcryptoSubtle();
|
||||
const iKey = await cr.importKey('raw', key, keyParams, true, ['decrypt']);
|
||||
const plaintext = await cr.decrypt(cryptParams, iKey, ciphertext);
|
||||
return new Uint8Array(plaintext) as TRet<Uint8Array>;
|
||||
},
|
||||
};
|
||||
|
||||
const mode = {
|
||||
CBC: 'AES-CBC',
|
||||
CTR: 'AES-CTR',
|
||||
GCM: 'AES-GCM',
|
||||
} as const;
|
||||
type BlockMode = (typeof mode)[keyof typeof mode];
|
||||
|
||||
function getCryptParams(algo: BlockMode, nonce: TArg<Uint8Array>, AAD?: TArg<Uint8Array>) {
|
||||
if (algo === mode.CBC) return { name: mode.CBC, iv: nonce };
|
||||
// WebCrypto allows 1..128 counter bits; use the full block to match sync ctr() / Node CTR wrap.
|
||||
if (algo === mode.CTR) return { name: mode.CTR, counter: nonce, length: 128 };
|
||||
if (algo === mode.GCM) {
|
||||
// Rely on the backend default tag length (128 bits) instead of setting it explicitly.
|
||||
if (AAD) return { name: mode.GCM, iv: nonce, additionalData: AAD };
|
||||
else return { name: mode.GCM, iv: nonce };
|
||||
}
|
||||
|
||||
throw new Error('unknown aes block mode');
|
||||
}
|
||||
|
||||
function generate(
|
||||
algo: BlockMode,
|
||||
nonceLength: number
|
||||
): TRet<
|
||||
((key: TArg<Uint8Array>, nonce: TArg<Uint8Array>, AAD?: TArg<Uint8Array>) => AsyncCipher) & {
|
||||
blockSize: number;
|
||||
nonceLength: number;
|
||||
}
|
||||
> {
|
||||
anumber(nonceLength);
|
||||
const res = (
|
||||
key: TArg<Uint8Array>,
|
||||
nonce: TArg<Uint8Array>,
|
||||
AAD?: TArg<Uint8Array>
|
||||
): TRet<AsyncCipher> => {
|
||||
abytes(key);
|
||||
abytes(nonce);
|
||||
// Reject falsy non-byte AAD locally; otherwise false/0/''/null silently become "no AAD".
|
||||
if (AAD !== undefined) abytes(AAD, undefined, 'AAD');
|
||||
// Exact nonce-length enforcement and WebCrypto-specific AAD normalization are
|
||||
// delegated to the backend; locally we only require byte-array inputs here.
|
||||
// Keep caller key/nonce/AAD by reference; mutating them after
|
||||
// construction changes later operations.
|
||||
const keyParams = { name: algo, length: key.length * 8 };
|
||||
const cryptParams = getCryptParams(algo, nonce, AAD);
|
||||
let consumed = false;
|
||||
return {
|
||||
// keyLength,
|
||||
encrypt(plaintext: TArg<Uint8Array>): Promise<TRet<Uint8Array>> {
|
||||
abytes(plaintext);
|
||||
if (consumed) throw new Error('Cannot encrypt() twice with same key / nonce');
|
||||
consumed = true;
|
||||
return utils.encrypt(key, keyParams, cryptParams, plaintext);
|
||||
},
|
||||
decrypt(ciphertext: TArg<Uint8Array>): Promise<TRet<Uint8Array>> {
|
||||
abytes(ciphertext);
|
||||
return utils.decrypt(key, keyParams, cryptParams, ciphertext);
|
||||
},
|
||||
} as TRet<AsyncCipher>;
|
||||
};
|
||||
res.nonceLength = nonceLength;
|
||||
res.blockSize = 16; // always for AES
|
||||
return res as TRet<
|
||||
((key: TArg<Uint8Array>, nonce: TArg<Uint8Array>, AAD?: TArg<Uint8Array>) => AsyncCipher) & {
|
||||
blockSize: number;
|
||||
nonceLength: number;
|
||||
}
|
||||
>;
|
||||
}
|
||||
|
||||
/**
|
||||
* AES-CBC implemented with WebCrypto.
|
||||
* Uses WebCrypto's built-in PKCS padding behavior; exact IV-length checks are
|
||||
* delegated to the backend instead of local `abytes(..., 16)` validation.
|
||||
* @param key - AES key bytes.
|
||||
* @param iv - 16-byte initialization vector.
|
||||
* @returns Async cipher instance.
|
||||
* @example
|
||||
* Encrypts a block with the browser or Node WebCrypto backend.
|
||||
*
|
||||
* ```ts
|
||||
* import { cbc } from '@noble/ciphers/webcrypto.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const iv = randomBytes(16);
|
||||
* const cipher = cbc(key, iv);
|
||||
* await cipher.encrypt(new Uint8Array(16));
|
||||
* ```
|
||||
*/
|
||||
export const cbc: TRet<
|
||||
((key: TArg<Uint8Array>, iv: TArg<Uint8Array>) => AsyncCipher) & {
|
||||
blockSize: number;
|
||||
nonceLength: number;
|
||||
}
|
||||
> = /* @__PURE__ */ (() => generate(mode.CBC, 16))();
|
||||
/**
|
||||
* AES-CTR implemented with WebCrypto.
|
||||
* Uses WebCrypto's full 128-bit counter-length setting so the whole
|
||||
* 16-byte counter block is incremented, matching sync `aes.ts:ctr`.
|
||||
* @param key - AES key bytes.
|
||||
* @param nonce - 16-byte counter block incremented as a full big-endian AES counter block.
|
||||
* @returns Async cipher instance.
|
||||
* @example
|
||||
* Encrypts a short payload with WebCrypto AES-CTR.
|
||||
*
|
||||
* ```ts
|
||||
* import { ctr } from '@noble/ciphers/webcrypto.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const nonce = randomBytes(16);
|
||||
* const cipher = ctr(key, nonce);
|
||||
* await cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export const ctr: TRet<
|
||||
((key: TArg<Uint8Array>, nonce: TArg<Uint8Array>) => AsyncCipher) & {
|
||||
blockSize: number;
|
||||
nonceLength: number;
|
||||
}
|
||||
> = /* @__PURE__ */ (() => generate(mode.CTR, 16))();
|
||||
/**
|
||||
* AES-GCM implemented with WebCrypto.
|
||||
* AAD type normalization and nonce-shape enforcement beyond raw bytes are left
|
||||
* to the backend WebCrypto implementation.
|
||||
* @param key - AES key bytes.
|
||||
* @param nonce - Nonce bytes.
|
||||
* @param AAD - Additional authenticated data.
|
||||
* @returns Async cipher instance.
|
||||
* @example
|
||||
* Encrypts and authenticates plaintext with WebCrypto AES-GCM.
|
||||
*
|
||||
* ```ts
|
||||
* import { gcm } from '@noble/ciphers/webcrypto.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const nonce = randomBytes(12);
|
||||
* const cipher = gcm(key, nonce);
|
||||
* await cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export const gcm: TRet<
|
||||
((key: TArg<Uint8Array>, nonce: TArg<Uint8Array>, AAD?: TArg<Uint8Array>) => AsyncCipher) & {
|
||||
blockSize: number;
|
||||
nonceLength: number;
|
||||
}
|
||||
> = /* @__PURE__ */ (() => generate(mode.GCM, 12))();
|
||||
|
||||
// // Type tests
|
||||
// import { siv, gcm, ctr, ecb, cbc } from '../aes.ts';
|
||||
// import { xsalsa20poly1305 } from '../salsa.ts';
|
||||
// import { chacha20poly1305, xchacha20poly1305 } from '../chacha.ts';
|
||||
|
||||
// const wsiv = managedNonce(siv);
|
||||
// const wgcm = managedNonce(gcm);
|
||||
// const wctr = managedNonce(ctr);
|
||||
// const wcbc = managedNonce(cbc);
|
||||
// const wsalsapoly = managedNonce(xsalsa20poly1305);
|
||||
// const wchacha = managedNonce(chacha20poly1305);
|
||||
// const wxchacha = managedNonce(xchacha20poly1305);
|
||||
|
||||
// // should fail
|
||||
// const wcbc2 = managedNonce(managedNonce(cbc));
|
||||
// const wctr = managedNonce(ctr);
|
||||
// import { gcm as gcmSync } from '../aes.ts';
|
||||
// const x1 = managedNonce(gcmSync);
|
||||
// // const x1: (key: Uint8Array, AAD?: Uint8Array | undefined) => Cipher
|
||||
// const x2 = managedNonce(gcm);
|
||||
// // const x2: (key: Uint8Array, AAD?: Uint8Array | undefined) => AsyncCipher
|
||||
717
node_modules/@noble/ciphers/utils.d.ts
generated
vendored
Normal file
717
node_modules/@noble/ciphers/utils.d.ts
generated
vendored
Normal file
@@ -0,0 +1,717 @@
|
||||
/**
|
||||
* Utilities for hex, bytes, CSPRNG.
|
||||
* @module
|
||||
*/
|
||||
/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
|
||||
/**
|
||||
* Bytes API type helpers for old + new TypeScript.
|
||||
*
|
||||
* TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array<ArrayBuffer>`.
|
||||
* We can't use specific return type, because TS 5.6 will error.
|
||||
* We can't use generic return type, because most TS 5.9 software will expect specific type.
|
||||
*
|
||||
* Maps typed-array input leaves to broad forms.
|
||||
* These are compatibility adapters, not ownership guarantees.
|
||||
*
|
||||
* - `TArg` keeps byte inputs broad.
|
||||
* - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility.
|
||||
*/
|
||||
export type TypedArg<T> = T extends BigInt64Array ? BigInt64Array : T extends BigUint64Array ? BigUint64Array : T extends Float32Array ? Float32Array : T extends Float64Array ? Float64Array : T extends Int16Array ? Int16Array : T extends Int32Array ? Int32Array : T extends Int8Array ? Int8Array : T extends Uint16Array ? Uint16Array : T extends Uint32Array ? Uint32Array : T extends Uint8ClampedArray ? Uint8ClampedArray : T extends Uint8Array ? Uint8Array : never;
|
||||
/** Maps typed-array output leaves to narrow TS-compatible forms. */
|
||||
export type TypedRet<T> = T extends BigInt64Array ? ReturnType<typeof BigInt64Array.of> : T extends BigUint64Array ? ReturnType<typeof BigUint64Array.of> : T extends Float32Array ? ReturnType<typeof Float32Array.of> : T extends Float64Array ? ReturnType<typeof Float64Array.of> : T extends Int16Array ? ReturnType<typeof Int16Array.of> : T extends Int32Array ? ReturnType<typeof Int32Array.of> : T extends Int8Array ? ReturnType<typeof Int8Array.of> : T extends Uint16Array ? ReturnType<typeof Uint16Array.of> : T extends Uint32Array ? ReturnType<typeof Uint32Array.of> : T extends Uint8ClampedArray ? ReturnType<typeof Uint8ClampedArray.of> : T extends Uint8Array ? ReturnType<typeof Uint8Array.of> : never;
|
||||
/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */
|
||||
export type TArg<T> = T | ([TypedArg<T>] extends [never] ? T extends (...args: infer A) => infer R ? ((...args: {
|
||||
[K in keyof A]: TRet<A[K]>;
|
||||
}) => TArg<R>) & {
|
||||
[K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg<T[K]>;
|
||||
} : T extends [infer A, ...infer R] ? [TArg<A>, ...{
|
||||
[K in keyof R]: TArg<R[K]>;
|
||||
}] : T extends readonly [infer A, ...infer R] ? readonly [TArg<A>, ...{
|
||||
[K in keyof R]: TArg<R[K]>;
|
||||
}] : T extends (infer A)[] ? TArg<A>[] : T extends readonly (infer A)[] ? readonly TArg<A>[] : T extends Promise<infer A> ? Promise<TArg<A>> : T extends object ? {
|
||||
[K in keyof T]: TArg<T[K]>;
|
||||
} : T : TypedArg<T>);
|
||||
/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */
|
||||
export type TRet<T> = T extends unknown ? T & ([TypedRet<T>] extends [never] ? T extends (...args: infer A) => infer R ? ((...args: {
|
||||
[K in keyof A]: TArg<A[K]>;
|
||||
}) => TRet<R>) & {
|
||||
[K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet<T[K]>;
|
||||
} : T extends [infer A, ...infer R] ? [TRet<A>, ...{
|
||||
[K in keyof R]: TRet<R[K]>;
|
||||
}] : T extends readonly [infer A, ...infer R] ? readonly [TRet<A>, ...{
|
||||
[K in keyof R]: TRet<R[K]>;
|
||||
}] : T extends (infer A)[] ? TRet<A>[] : T extends readonly (infer A)[] ? readonly TRet<A>[] : T extends Promise<infer A> ? Promise<TRet<A>> : T extends object ? {
|
||||
[K in keyof T]: TRet<T[K]>;
|
||||
} : T : TypedRet<T>) : never;
|
||||
/**
|
||||
* Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.
|
||||
* @param a - Value to inspect.
|
||||
* @returns `true` when the value is a Uint8Array view, including Node's `Buffer`.
|
||||
* @example
|
||||
* Guards a value before treating it as raw key material.
|
||||
*
|
||||
* ```ts
|
||||
* isBytes(new Uint8Array());
|
||||
* ```
|
||||
*/
|
||||
export declare function isBytes(a: unknown): a is Uint8Array;
|
||||
/**
|
||||
* Asserts something is boolean.
|
||||
* @param b - Value to validate.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @example
|
||||
* Validates a boolean option before branching on it.
|
||||
*
|
||||
* ```ts
|
||||
* abool(true);
|
||||
* ```
|
||||
*/
|
||||
export declare function abool(b: boolean): void;
|
||||
/**
|
||||
* Asserts something is a non-negative safe integer.
|
||||
* @param n - Value to validate.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @throws On wrong argument ranges or values. {@link RangeError}
|
||||
* @example
|
||||
* Validates a non-negative length or counter.
|
||||
*
|
||||
* ```ts
|
||||
* anumber(1);
|
||||
* ```
|
||||
*/
|
||||
export declare function anumber(n: number): void;
|
||||
/**
|
||||
* Asserts something is Uint8Array.
|
||||
* @param value - Value to validate.
|
||||
* @param length - Expected byte length.
|
||||
* @param title - Optional label used in error messages.
|
||||
* @returns The validated byte array.
|
||||
* On Node, `Buffer` is accepted too because it is a Uint8Array view.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @throws On wrong argument lengths. {@link RangeError}
|
||||
* @example
|
||||
* Validates a fixed-length nonce or key buffer.
|
||||
*
|
||||
* ```ts
|
||||
* abytes(new Uint8Array([1, 2]), 2);
|
||||
* ```
|
||||
*/
|
||||
export declare function abytes(value: TArg<Uint8Array>, length?: number, title?: string): TRet<Uint8Array>;
|
||||
/**
|
||||
* Asserts a hash- or MAC-like instance has not been destroyed or finished.
|
||||
* @param instance - Stateful instance to validate.
|
||||
* @param checkFinished - Whether to reject finished instances.
|
||||
* When `false`, only `destroyed` is checked.
|
||||
* @throws If the hash instance has already been destroyed or finalized. {@link Error}
|
||||
* @example
|
||||
* Guards against calling `update()` or `digest()` on a finished hash.
|
||||
*
|
||||
* ```ts
|
||||
* aexists({ destroyed: false, finished: false });
|
||||
* ```
|
||||
*/
|
||||
export declare function aexists(instance: any, checkFinished?: boolean): void;
|
||||
/**
|
||||
* Asserts output is a properly-sized byte array.
|
||||
* @param out - Output buffer to validate.
|
||||
* @param instance - Hash-like instance providing `outputLen`.
|
||||
* This is the relaxed `digestInto()`-style contract: output must be at least `outputLen`,
|
||||
* unlike one-shot cipher helpers elsewhere in the repo that often require exact lengths.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @param onlyAligned - Whether `out` must be 4-byte aligned for zero-allocation word views.
|
||||
* @throws On wrong output buffer lengths. {@link RangeError}
|
||||
* @throws On wrong output buffer alignment. {@link Error}
|
||||
* @example
|
||||
* Verifies that a caller-provided output buffer is large enough.
|
||||
*
|
||||
* ```ts
|
||||
* aoutput(new Uint8Array(16), { outputLen: 16 });
|
||||
* ```
|
||||
*/
|
||||
export declare function aoutput(out: any, instance: any, onlyAligned?: boolean): void;
|
||||
/** One-shot hash helper with `.create()`. */
|
||||
export type IHash = {
|
||||
(data: string | TArg<Uint8Array>): TRet<Uint8Array>;
|
||||
/** Input block size in bytes. */
|
||||
blockLen: number;
|
||||
/** Digest size in bytes. */
|
||||
outputLen: number;
|
||||
/** Creates a fresh incremental hash instance of the same algorithm. */
|
||||
create: any;
|
||||
};
|
||||
/** One-shot MAC helper with `.create()`. */
|
||||
export type CMac<H extends IHash2 = IHash2, A extends any[] = []> = {
|
||||
(msg: TArg<Uint8Array>, key: TArg<Uint8Array>): TRet<Uint8Array>;
|
||||
/** Input block size in bytes. */
|
||||
blockLen: number;
|
||||
/** Digest size in bytes. */
|
||||
outputLen: number;
|
||||
/**
|
||||
* Creates a fresh incremental MAC instance of the same algorithm.
|
||||
* @param key - MAC key bytes.
|
||||
* @param args - Additional constructor arguments, when the MAC wrapper needs them.
|
||||
* @returns Fresh incremental MAC instance.
|
||||
*/
|
||||
create(key: TArg<Uint8Array>, ...args: A): H;
|
||||
};
|
||||
/** Generic type encompassing 8/16/32-bit typed arrays, but not 64-bit. */
|
||||
export type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array | Uint16Array | Int16Array | Uint32Array | Int32Array;
|
||||
/**
|
||||
* Casts a typed-array view to Uint8Array.
|
||||
* @param arr - Typed-array view to reinterpret.
|
||||
* @returns Uint8Array view over the same bytes.
|
||||
* @example
|
||||
* Views 32-bit words as raw bytes without copying.
|
||||
*
|
||||
* ```ts
|
||||
* u8(new Uint32Array([1]));
|
||||
* ```
|
||||
*/
|
||||
export declare function u8(arr: TArg<TypedArray>): TRet<Uint8Array>;
|
||||
/**
|
||||
* Casts a typed-array view to Uint32Array.
|
||||
* @param arr - Typed-array view to reinterpret.
|
||||
* @returns Uint32Array view over the same bytes. Callers are expected to provide a
|
||||
* 4-byte-aligned offset; trailing `1..3` bytes are silently dropped.
|
||||
* @example
|
||||
* Views a byte buffer as 32-bit words for block processing.
|
||||
*
|
||||
* ```ts
|
||||
* u32(new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export declare function u32(arr: TArg<TypedArray>): TRet<Uint32Array>;
|
||||
/**
|
||||
* Zeroizes typed arrays in place.
|
||||
* Warning: JS provides no guarantees.
|
||||
* @param arrays - Arrays to wipe.
|
||||
* @example
|
||||
* Wipes a temporary key buffer after use.
|
||||
*
|
||||
* ```ts
|
||||
* const bytes = new Uint8Array([1]);
|
||||
* clean(bytes);
|
||||
* ```
|
||||
*/
|
||||
export declare function clean(...arrays: TArg<TypedArray[]>): void;
|
||||
/**
|
||||
* Creates a DataView for byte-level manipulation.
|
||||
* @param arr - Typed-array view to wrap.
|
||||
* @returns DataView over the same bytes.
|
||||
* @example
|
||||
* Creates an endian-aware view for length encoding.
|
||||
*
|
||||
* ```ts
|
||||
* createView(new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export declare function createView(arr: TArg<TypedArray>): DataView;
|
||||
/**
|
||||
* Whether the current platform is little-endian.
|
||||
* Most are; some IBM systems are not.
|
||||
*/
|
||||
export declare const isLE: boolean;
|
||||
/**
|
||||
* Reverses byte order of one 32-bit word.
|
||||
* @param word - Unsigned 32-bit word to swap.
|
||||
* @returns The same word with bytes reversed.
|
||||
* @example
|
||||
* Swaps a big-endian word into little-endian byte order.
|
||||
*
|
||||
* ```ts
|
||||
* byteSwap(0x11223344);
|
||||
* ```
|
||||
*/
|
||||
export declare const byteSwap: (word: number) => number;
|
||||
/**
|
||||
* Normalizes one 32-bit word to the little-endian representation expected by cipher cores.
|
||||
* @param n - Unsigned 32-bit word to normalize.
|
||||
* @returns Little-endian normalized word on big-endian hosts, else the input word unchanged.
|
||||
* @example
|
||||
* Normalizes a host-endian word before passing it into an ARX/AES core.
|
||||
*
|
||||
* ```ts
|
||||
* swap8IfBE(0x11223344);
|
||||
* ```
|
||||
*/
|
||||
export declare const swap8IfBE: (n: number) => number;
|
||||
/**
|
||||
* Byte-swaps every word of a Uint32Array in place.
|
||||
* @param arr - Uint32Array whose words should be swapped.
|
||||
* @returns The same array after in-place byte swapping.
|
||||
* @example
|
||||
* Swaps every 32-bit word in a word-view buffer.
|
||||
*
|
||||
* ```ts
|
||||
* byteSwap32(new Uint32Array([0x11223344]));
|
||||
* ```
|
||||
*/
|
||||
export declare const byteSwap32: (arr: TArg<Uint32Array>) => TRet<Uint32Array>;
|
||||
/**
|
||||
* Normalizes a Uint32Array view to the little-endian representation expected by cipher cores.
|
||||
* @param u - Word view to normalize in place.
|
||||
* @returns Little-endian normalized word view.
|
||||
* @example
|
||||
* Normalizes a word-view buffer before block processing.
|
||||
*
|
||||
* ```ts
|
||||
* swap32IfBE(new Uint32Array([0x11223344]));
|
||||
* ```
|
||||
*/
|
||||
export declare const swap32IfBE: (u: TArg<Uint32Array>) => TRet<Uint32Array>;
|
||||
/**
|
||||
* Convert byte array to hex string. Uses built-in function, when available.
|
||||
* @param bytes - Bytes to encode.
|
||||
* @returns Lowercase hexadecimal string.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @example
|
||||
* Formats ciphertext bytes for logs or test vectors.
|
||||
*
|
||||
* ```ts
|
||||
* bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'
|
||||
* ```
|
||||
*/
|
||||
export declare function bytesToHex(bytes: TArg<Uint8Array>): string;
|
||||
/**
|
||||
* Convert hex string to byte array. Uses built-in function, when available.
|
||||
* @param hex - Hexadecimal string to decode.
|
||||
* @returns Decoded bytes.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @throws On malformed hexadecimal input. {@link RangeError}
|
||||
* @example
|
||||
* Parses a hex test vector into bytes.
|
||||
*
|
||||
* ```ts
|
||||
* hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
|
||||
* ```
|
||||
*/
|
||||
export declare function hexToBytes(hex: string): TRet<Uint8Array>;
|
||||
/**
|
||||
* Converts a big-endian hex string into bigint.
|
||||
* @param hex - Hexadecimal string without `0x`.
|
||||
* @returns Parsed bigint value. The empty string is treated as `0n`.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @example
|
||||
* Parses a big-endian field element or counter from hex.
|
||||
*
|
||||
* ```ts
|
||||
* hexToNumber('ff');
|
||||
* ```
|
||||
*/
|
||||
export declare function hexToNumber(hex: string): bigint;
|
||||
/**
|
||||
* Converts big-endian bytes into bigint.
|
||||
* @param bytes - Big-endian bytes.
|
||||
* @returns Parsed bigint value. Empty input is treated as `0n`.
|
||||
* @throws On invalid byte input passed to the internal hex conversion. {@link TypeError}
|
||||
* @example
|
||||
* Reads a big-endian integer from serialized bytes.
|
||||
*
|
||||
* ```ts
|
||||
* bytesToNumberBE(new Uint8Array([1, 0]));
|
||||
* ```
|
||||
*/
|
||||
export declare function bytesToNumberBE(bytes: TArg<Uint8Array>): bigint;
|
||||
/**
|
||||
* Converts a number into big-endian bytes of fixed length.
|
||||
* @param n - Number to encode.
|
||||
* @param len - Output length in bytes.
|
||||
* @returns Big-endian bytes padded to `len`.
|
||||
* Validation is indirect through `hexToBytes(...)`, so negative values, `len = 0`,
|
||||
* and values that do not fit surface through the downstream hex parser instead of a
|
||||
* dedicated range guard here.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @throws If the requested output length cannot represent the encoded value. {@link RangeError}
|
||||
* @example
|
||||
* Encodes a counter as fixed-width big-endian bytes.
|
||||
*
|
||||
* ```ts
|
||||
* numberToBytesBE(1, 2);
|
||||
* ```
|
||||
*/
|
||||
export declare function numberToBytesBE(n: number | bigint, len: number): TRet<Uint8Array>;
|
||||
/**
|
||||
* Converts string to bytes using UTF8 encoding.
|
||||
* @param str - String to encode.
|
||||
* @returns UTF-8 bytes in a detached fresh Uint8Array copy.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @example
|
||||
* Encodes application text before encryption or MACing.
|
||||
*
|
||||
* ```ts
|
||||
* utf8ToBytes('abc'); // new Uint8Array([97, 98, 99])
|
||||
* ```
|
||||
*/
|
||||
export declare function utf8ToBytes(str: string): TRet<Uint8Array>;
|
||||
/**
|
||||
* Converts bytes to string using UTF8 encoding.
|
||||
* @param bytes - UTF-8 bytes.
|
||||
* @returns Decoded string. Input validation is delegated to `TextDecoder`, and malformed
|
||||
* UTF-8 is replacement-decoded instead of rejected.
|
||||
* @example
|
||||
* Decodes UTF-8 plaintext back into a string.
|
||||
*
|
||||
* ```ts
|
||||
* bytesToUtf8(new Uint8Array([97, 98, 99])); // 'abc'
|
||||
* ```
|
||||
*/
|
||||
export declare function bytesToUtf8(bytes: TArg<Uint8Array>): string;
|
||||
/**
|
||||
* Checks if two U8A use same underlying buffer and overlaps.
|
||||
* This is invalid and can corrupt data.
|
||||
* @param a - First byte view.
|
||||
* @param b - Second byte view.
|
||||
* @returns `true` when the views overlap in memory.
|
||||
* @example
|
||||
* Detects whether two slices alias the same backing buffer.
|
||||
*
|
||||
* ```ts
|
||||
* overlapBytes(new Uint8Array(4), new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export declare function overlapBytes(a: TArg<Uint8Array>, b: TArg<Uint8Array>): boolean;
|
||||
/**
|
||||
* If input and output overlap and input starts before output, we will overwrite end of input before
|
||||
* we start processing it, so this is not supported for most ciphers
|
||||
* (except chacha/salsa, which were designed for this)
|
||||
* @param input - Input bytes.
|
||||
* @param output - Output bytes.
|
||||
* @throws If the output view would overwrite unread input bytes. {@link Error}
|
||||
* @example
|
||||
* Rejects an in-place layout that would overwrite unread input bytes.
|
||||
*
|
||||
* ```ts
|
||||
* complexOverlapBytes(new Uint8Array(4), new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export declare function complexOverlapBytes(input: TArg<Uint8Array>, output: TArg<Uint8Array>): void;
|
||||
/**
|
||||
* Copies several Uint8Arrays into one.
|
||||
* @param arrays - Byte arrays to concatenate.
|
||||
* @returns Combined byte array.
|
||||
* @throws On wrong argument types inside the byte-array list. {@link TypeError}
|
||||
* @example
|
||||
* Builds a `nonce || ciphertext` style buffer.
|
||||
*
|
||||
* ```ts
|
||||
* concatBytes(new Uint8Array([1]), new Uint8Array([2]));
|
||||
* ```
|
||||
*/
|
||||
export declare function concatBytes(...arrays: TArg<Uint8Array[]>): TRet<Uint8Array>;
|
||||
type EmptyObj = {};
|
||||
/**
|
||||
* Merges user options into defaults.
|
||||
* @param defaults - Default option values.
|
||||
* @param opts - User-provided overrides.
|
||||
* @returns Combined options object.
|
||||
* The merge mutates `defaults` in place and returns the same object.
|
||||
* @throws If options are missing or not an object. {@link Error}
|
||||
* @example
|
||||
* Applies user overrides to the default cipher options.
|
||||
*
|
||||
* ```ts
|
||||
* checkOpts({ rounds: 20 }, { rounds: 8 });
|
||||
* ```
|
||||
*/
|
||||
export declare function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(defaults: T1, opts: T2): T1 & T2;
|
||||
/**
|
||||
* Compares two byte arrays in kinda constant time once lengths already match.
|
||||
* @param a - First byte array.
|
||||
* @param b - Second byte array.
|
||||
* @returns `true` when the arrays contain the same bytes. Different lengths still return early.
|
||||
* @example
|
||||
* Compares an expected authentication tag with the received one.
|
||||
*
|
||||
* ```ts
|
||||
* equalBytes(new Uint8Array([1]), new Uint8Array([1]));
|
||||
* ```
|
||||
*/
|
||||
export declare function equalBytes(a: TArg<Uint8Array>, b: TArg<Uint8Array>): boolean;
|
||||
/** Incremental hash interface used internally. */
|
||||
export interface IHash2 {
|
||||
/** Bytes processed per compression block. */
|
||||
blockLen: number;
|
||||
/** Bytes produced by the final digest. */
|
||||
outputLen: number;
|
||||
/**
|
||||
* Absorbs one more chunk into the hash state.
|
||||
* @param buf - Data chunk to hash.
|
||||
* @returns The same hash instance for chaining.
|
||||
*/
|
||||
update(buf: string | TArg<Uint8Array>): this;
|
||||
/**
|
||||
* Writes the final digest into a caller-provided buffer.
|
||||
* @param buf - Destination buffer for the digest bytes.
|
||||
* @returns Nothing. Implementations write into `buf` in place.
|
||||
*/
|
||||
digestInto(buf: TArg<Uint8Array>): void;
|
||||
/**
|
||||
* Finalizes the hash and returns a fresh digest buffer.
|
||||
* @returns Digest bytes.
|
||||
*/
|
||||
digest(): TRet<Uint8Array>;
|
||||
/**
|
||||
* Resets internal state. Makes Hash instance unusable.
|
||||
* Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed
|
||||
* by user, they will need to manually call `destroy()` when zeroing is necessary.
|
||||
*/
|
||||
destroy(): void;
|
||||
}
|
||||
/**
|
||||
* Wraps a keyed MAC constructor into a one-shot helper with `.create()`.
|
||||
* @param keyLen - Valid probe-key length used to read static metadata once.
|
||||
* The probe key is only used for `outputLen` / `blockLen`, so callers with several valid key sizes
|
||||
* can pass any representative size as long as those values stay fixed.
|
||||
* @param macCons - Keyed MAC constructor or factory.
|
||||
* @param fromMsg - Optional adapter that derives extra constructor args from the one-shot message.
|
||||
* @returns Callable MAC helper with `.create()`.
|
||||
*/
|
||||
export declare function wrapMacConstructor<H extends IHash2, A extends any[] = []>(keyLen: number, macCons: TArg<(key: Uint8Array, ...args: A) => H>, fromMsg?: TArg<(msg: Uint8Array) => A>): TRet<CMac<H, A>>;
|
||||
/** Sync cipher: takes byte array and returns byte array. */
|
||||
export type Cipher = {
|
||||
/**
|
||||
* Encrypts plaintext bytes.
|
||||
* @param plaintext - Data to encrypt.
|
||||
* @returns Ciphertext bytes.
|
||||
*/
|
||||
encrypt(plaintext: TArg<Uint8Array>): TRet<Uint8Array>;
|
||||
/**
|
||||
* Decrypts ciphertext bytes.
|
||||
* @param ciphertext - Data to decrypt.
|
||||
* @returns Plaintext bytes.
|
||||
*/
|
||||
decrypt(ciphertext: TArg<Uint8Array>): TRet<Uint8Array>;
|
||||
};
|
||||
/** Async cipher e.g. from built-in WebCrypto. */
|
||||
export type AsyncCipher = {
|
||||
/**
|
||||
* Encrypts plaintext bytes.
|
||||
* @param plaintext - Data to encrypt.
|
||||
* @returns Promise resolving to ciphertext bytes.
|
||||
*/
|
||||
encrypt(plaintext: TArg<Uint8Array>): Promise<TRet<Uint8Array>>;
|
||||
/**
|
||||
* Decrypts ciphertext bytes.
|
||||
* @param ciphertext - Data to decrypt.
|
||||
* @returns Promise resolving to plaintext bytes.
|
||||
*/
|
||||
decrypt(ciphertext: TArg<Uint8Array>): Promise<TRet<Uint8Array>>;
|
||||
};
|
||||
/** Cipher with `output` argument which can optimize by doing 1 less allocation. */
|
||||
export type CipherWithOutput = Cipher & {
|
||||
/**
|
||||
* Encrypts plaintext bytes into an optional caller-provided buffer.
|
||||
* @param plaintext - Data to encrypt.
|
||||
* @param output - Optional destination buffer.
|
||||
* @returns Ciphertext bytes.
|
||||
*/
|
||||
encrypt(plaintext: TArg<Uint8Array>, output?: TArg<Uint8Array>): TRet<Uint8Array>;
|
||||
/**
|
||||
* Decrypts ciphertext bytes into an optional caller-provided buffer.
|
||||
* @param ciphertext - Data to decrypt.
|
||||
* @param output - Optional destination buffer.
|
||||
* @returns Plaintext bytes.
|
||||
*/
|
||||
decrypt(ciphertext: TArg<Uint8Array>, output?: TArg<Uint8Array>): TRet<Uint8Array>;
|
||||
};
|
||||
/**
|
||||
* Params are outside of return type, so it is accessible before calling constructor.
|
||||
* If function support multiple nonceLength's, we return the best one.
|
||||
*/
|
||||
export type CipherParams = {
|
||||
/** Cipher block size in bytes. */
|
||||
blockSize: number;
|
||||
/** Nonce length in bytes when the cipher uses a fixed nonce size. */
|
||||
nonceLength?: number;
|
||||
/** Authentication-tag length in bytes for AEAD modes. */
|
||||
tagLength?: number;
|
||||
/** Whether nonce length is variable at runtime. */
|
||||
varSizeNonce?: boolean;
|
||||
};
|
||||
/**
|
||||
* ARX AEAD cipher, like salsa or chacha.
|
||||
* @param key - Secret key bytes.
|
||||
* @param nonce - Nonce bytes.
|
||||
* @param AAD - Optional associated data.
|
||||
* @returns Cipher instance with caller-managed output buffers.
|
||||
*/
|
||||
export type ARXCipher = ((key: TArg<Uint8Array>, nonce: TArg<Uint8Array>, AAD?: TArg<Uint8Array>) => CipherWithOutput) & {
|
||||
blockSize: number;
|
||||
nonceLength: number;
|
||||
tagLength: number;
|
||||
};
|
||||
/**
|
||||
* Cipher constructor signature.
|
||||
* @param key - Secret key bytes.
|
||||
* @param args - Additional constructor arguments, such as nonce or IV.
|
||||
* @returns Cipher instance.
|
||||
*/
|
||||
export type CipherCons<T extends any[]> = (key: TArg<Uint8Array>, ...args: T) => Cipher;
|
||||
/**
|
||||
* Wraps a cipher: validates args, ensures encrypt() can only be called once.
|
||||
* Used internally by the exported cipher constructors.
|
||||
* Output-buffer support is inferred from the wrapped `encrypt` / `decrypt`
|
||||
* arity (`fn.length === 2`), and tag-bearing constructors are expected to use
|
||||
* `args[1]` for optional AAD.
|
||||
* @__NO_SIDE_EFFECTS__
|
||||
* @param params - Static cipher metadata. See {@link CipherParams}.
|
||||
* @param constructor - Cipher constructor.
|
||||
* @returns Wrapped constructor with validation.
|
||||
*/
|
||||
export declare const wrapCipher: <C extends CipherCons<any>, P extends CipherParams>(params: P, constructor: C) => C & P;
|
||||
/**
|
||||
* Represents a Salsa or ChaCha xor stream.
|
||||
* @param key - Secret key bytes.
|
||||
* @param nonce - Nonce bytes.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Optional starting block counter.
|
||||
* @returns Output bytes.
|
||||
*/
|
||||
export type XorStream = (key: TArg<Uint8Array>, nonce: TArg<Uint8Array>, data: TArg<Uint8Array>, output?: TArg<Uint8Array>, counter?: number) => TRet<Uint8Array>;
|
||||
/**
|
||||
* By default, returns u8a of length.
|
||||
* When out is available, it checks it for validity and uses it.
|
||||
* @param expectedLength - Required output length.
|
||||
* @param out - Optional destination buffer.
|
||||
* @param onlyAligned - Whether `out` must be 4-byte aligned.
|
||||
* @returns Output buffer ready for writing.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @throws If the provided output buffer has the wrong size or alignment. {@link Error}
|
||||
* @example
|
||||
* Reuses a caller-provided output buffer when lengths match.
|
||||
*
|
||||
* ```ts
|
||||
* getOutput(16, new Uint8Array(16));
|
||||
* ```
|
||||
*/
|
||||
export declare function getOutput(expectedLength: number, out?: TArg<Uint8Array>, onlyAligned?: boolean): TRet<Uint8Array>;
|
||||
/**
|
||||
* Encodes data and AAD bit lengths into a 16-byte buffer.
|
||||
* @param dataLength - Data length in bits.
|
||||
* @param aadLength - AAD length in bits.
|
||||
* The serialized block is still `aadLength || dataLength`, matching GCM/Poly1305
|
||||
* conventions even though the helper parameter order is `(dataLength, aadLength)`.
|
||||
* @param isLE - Whether to encode lengths as little-endian.
|
||||
* @returns 16-byte length block.
|
||||
* @throws On wrong argument types passed to the endian validator. {@link TypeError}
|
||||
* @throws On wrong argument ranges or values. {@link RangeError}
|
||||
* @example
|
||||
* Builds the length block appended by GCM and Poly1305.
|
||||
*
|
||||
* ```ts
|
||||
* u64Lengths(16, 8, true);
|
||||
* ```
|
||||
*/
|
||||
export declare function u64Lengths(dataLength: number, aadLength: number, isLE: boolean): TRet<Uint8Array>;
|
||||
/**
|
||||
* Checks whether a byte array is aligned to a 4-byte offset.
|
||||
* @param bytes - Byte array to inspect.
|
||||
* @returns `true` when the view is 4-byte aligned.
|
||||
* @example
|
||||
* Checks whether a buffer can be safely viewed as Uint32Array.
|
||||
*
|
||||
* ```ts
|
||||
* isAligned32(new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export declare function isAligned32(bytes: TArg<Uint8Array>): boolean;
|
||||
/**
|
||||
* Copies bytes into a new Uint8Array.
|
||||
* @param bytes - Bytes to copy.
|
||||
* @returns Copied byte array.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @example
|
||||
* Copies input into an aligned Uint8Array before block processing.
|
||||
*
|
||||
* ```ts
|
||||
* copyBytes(new Uint8Array([1, 2]));
|
||||
* ```
|
||||
*/
|
||||
export declare function copyBytes(bytes: TArg<Uint8Array>): TRet<Uint8Array>;
|
||||
/**
|
||||
* Cryptographically secure PRNG.
|
||||
* Uses internal OS-level `crypto.getRandomValues`.
|
||||
* @param bytesLength - Number of bytes to produce.
|
||||
* Validation is delegated to `Uint8Array(bytesLength)` and `getRandomValues`, so
|
||||
* non-integers, negative lengths, and oversize requests surface backend/runtime errors.
|
||||
* @returns Random byte array.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @throws On wrong argument ranges or values. {@link RangeError}
|
||||
* @throws If the runtime does not expose `crypto.getRandomValues`. {@link Error}
|
||||
* @example
|
||||
* Generates a fresh nonce or key.
|
||||
*
|
||||
* ```ts
|
||||
* randomBytes(16);
|
||||
* ```
|
||||
*/
|
||||
export declare function randomBytes(bytesLength?: number): TRet<Uint8Array>;
|
||||
/**
|
||||
* The pseudorandom number generator doesn't wipe current state:
|
||||
* instead, it generates new one based on previous state + entropy.
|
||||
* Not reseed/rekey, since AES CTR DRBG does rekey on each randomBytes,
|
||||
* which is in fact `reseed`, since it changes counter too.
|
||||
*/
|
||||
export interface PRG {
|
||||
/**
|
||||
* Mixes fresh entropy into the current generator state.
|
||||
* @param seed - Entropy bytes to absorb.
|
||||
*/
|
||||
addEntropy(seed: TArg<Uint8Array>): void;
|
||||
/**
|
||||
* Produces a requested number of pseudorandom bytes.
|
||||
* @param bytesLength - Number of bytes to generate.
|
||||
* @returns Random byte array.
|
||||
*/
|
||||
randomBytes(bytesLength: number): TRet<Uint8Array>;
|
||||
/** Destroys the generator state. */
|
||||
clean(): void;
|
||||
}
|
||||
/** Removes the nonce argument from a cipher constructor type. */
|
||||
export type RemoveNonce<T extends (...args: any) => any> = T extends (arg0: any, arg1: any, ...rest: infer R) => infer Ret ? (key: TArg<Uint8Array>, ...args: R) => Ret : never;
|
||||
/**
|
||||
* Cipher constructor that requires a nonce argument.
|
||||
* @param key - Secret key bytes.
|
||||
* @param nonce - Nonce bytes.
|
||||
* @param args - Additional cipher-specific arguments.
|
||||
* @returns Cipher instance.
|
||||
*/
|
||||
export type CipherWithNonce = ((key: TArg<Uint8Array>, nonce: TArg<Uint8Array>, ...args: any[]) => Cipher | AsyncCipher) & {
|
||||
nonceLength: number;
|
||||
};
|
||||
/**
|
||||
* Uses CSPRNG for nonce, nonce injected in ciphertext.
|
||||
* For `encrypt`, a `nonceBytes`-length buffer is fetched from CSPRNG and
|
||||
* prepended to encrypted ciphertext. For `decrypt`, first `nonceBytes` of ciphertext
|
||||
* are treated as nonce. The wrapper always allocates a fresh `nonce || ciphertext`
|
||||
* buffer on encrypt and intentionally does not support caller-provided destination buffers.
|
||||
* Too-short decrypt inputs are split into short/empty nonce views and then delegated
|
||||
* to the wrapped cipher instead of being rejected here first.
|
||||
*
|
||||
* NOTE: Under the same key, using random nonces (e.g. `managedNonce`) with AES-GCM and ChaCha
|
||||
* should be limited to `2**23` (8M) messages to get a collision chance of
|
||||
* `2**-50`. Stretching to `2**32` (4B) messages would raise that chance to
|
||||
* `2**-33`, still negligible but creeping up.
|
||||
* @param fn - Cipher constructor that expects a nonce.
|
||||
* @param randomBytes_ - Random-byte source used for nonce generation.
|
||||
* @returns Cipher constructor that prepends the nonce to ciphertext.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @throws On invalid nonce lengths observed at wrapper construction or use. {@link RangeError}
|
||||
* @example
|
||||
* Prepends a fresh random nonce to every ciphertext.
|
||||
*
|
||||
* ```ts
|
||||
* import { gcm } from '@noble/ciphers/aes.js';
|
||||
* import { managedNonce, randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const wrapped = managedNonce(gcm);
|
||||
* const key = randomBytes(16);
|
||||
* const ciphertext = wrapped(key).encrypt(new Uint8Array([1, 2, 3]));
|
||||
* wrapped(key).decrypt(ciphertext);
|
||||
* ```
|
||||
*/
|
||||
export declare function managedNonce<T extends CipherWithNonce>(fn: T, randomBytes_?: typeof randomBytes): TRet<RemoveNonce<T>>;
|
||||
/** `Uint8Array.of()` return type helper for TS 5.9. */
|
||||
export type Uint8ArrayBuffer = TRet<Uint8Array>;
|
||||
export {};
|
||||
//# sourceMappingURL=utils.d.ts.map
|
||||
1
node_modules/@noble/ciphers/utils.d.ts.map
generated
vendored
Normal file
1
node_modules/@noble/ciphers/utils.d.ts.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
807
node_modules/@noble/ciphers/utils.js
generated
vendored
Normal file
807
node_modules/@noble/ciphers/utils.js
generated
vendored
Normal file
@@ -0,0 +1,807 @@
|
||||
/**
|
||||
* Utilities for hex, bytes, CSPRNG.
|
||||
* @module
|
||||
*/
|
||||
/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
|
||||
/**
|
||||
* Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.
|
||||
* @param a - Value to inspect.
|
||||
* @returns `true` when the value is a Uint8Array view, including Node's `Buffer`.
|
||||
* @example
|
||||
* Guards a value before treating it as raw key material.
|
||||
*
|
||||
* ```ts
|
||||
* isBytes(new Uint8Array());
|
||||
* ```
|
||||
*/
|
||||
export function isBytes(a) {
|
||||
// Plain `instanceof Uint8Array` is too strict for some Buffer / proxy /
|
||||
// cross-realm cases. The fallback still requires a real ArrayBuffer view
|
||||
// so plain JSON-deserialized `{ constructor: ... }`
|
||||
// spoofing is rejected, and `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.
|
||||
return (a instanceof Uint8Array ||
|
||||
(ArrayBuffer.isView(a) &&
|
||||
a.constructor.name === 'Uint8Array' &&
|
||||
'BYTES_PER_ELEMENT' in a &&
|
||||
a.BYTES_PER_ELEMENT === 1));
|
||||
}
|
||||
/**
|
||||
* Asserts something is boolean.
|
||||
* @param b - Value to validate.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @example
|
||||
* Validates a boolean option before branching on it.
|
||||
*
|
||||
* ```ts
|
||||
* abool(true);
|
||||
* ```
|
||||
*/
|
||||
export function abool(b) {
|
||||
if (typeof b !== 'boolean')
|
||||
throw new TypeError(`boolean expected, not ${b}`);
|
||||
}
|
||||
/**
|
||||
* Asserts something is a non-negative safe integer.
|
||||
* @param n - Value to validate.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @throws On wrong argument ranges or values. {@link RangeError}
|
||||
* @example
|
||||
* Validates a non-negative length or counter.
|
||||
*
|
||||
* ```ts
|
||||
* anumber(1);
|
||||
* ```
|
||||
*/
|
||||
export function anumber(n) {
|
||||
if (typeof n !== 'number')
|
||||
throw new TypeError('number expected, got ' + typeof n);
|
||||
if (!Number.isSafeInteger(n) || n < 0)
|
||||
throw new RangeError('positive integer expected, got ' + n);
|
||||
}
|
||||
/**
|
||||
* Asserts something is Uint8Array.
|
||||
* @param value - Value to validate.
|
||||
* @param length - Expected byte length.
|
||||
* @param title - Optional label used in error messages.
|
||||
* @returns The validated byte array.
|
||||
* On Node, `Buffer` is accepted too because it is a Uint8Array view.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @throws On wrong argument lengths. {@link RangeError}
|
||||
* @example
|
||||
* Validates a fixed-length nonce or key buffer.
|
||||
*
|
||||
* ```ts
|
||||
* abytes(new Uint8Array([1, 2]), 2);
|
||||
* ```
|
||||
*/
|
||||
export function abytes(value, length, title = '') {
|
||||
const bytes = isBytes(value);
|
||||
const len = value?.length;
|
||||
const needsLen = length !== undefined;
|
||||
if (!bytes || (needsLen && len !== length)) {
|
||||
const prefix = title && `"${title}" `;
|
||||
const ofLen = needsLen ? ` of length ${length}` : '';
|
||||
const got = bytes ? `length=${len}` : `type=${typeof value}`;
|
||||
const message = prefix + 'expected Uint8Array' + ofLen + ', got ' + got;
|
||||
if (!bytes)
|
||||
throw new TypeError(message);
|
||||
throw new RangeError(message);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
/**
|
||||
* Asserts a hash- or MAC-like instance has not been destroyed or finished.
|
||||
* @param instance - Stateful instance to validate.
|
||||
* @param checkFinished - Whether to reject finished instances.
|
||||
* When `false`, only `destroyed` is checked.
|
||||
* @throws If the hash instance has already been destroyed or finalized. {@link Error}
|
||||
* @example
|
||||
* Guards against calling `update()` or `digest()` on a finished hash.
|
||||
*
|
||||
* ```ts
|
||||
* aexists({ destroyed: false, finished: false });
|
||||
* ```
|
||||
*/
|
||||
export function aexists(instance, checkFinished = true) {
|
||||
if (instance.destroyed)
|
||||
throw new Error('Hash instance has been destroyed');
|
||||
if (checkFinished && instance.finished)
|
||||
throw new Error('Hash#digest() has already been called');
|
||||
}
|
||||
/**
|
||||
* Asserts output is a properly-sized byte array.
|
||||
* @param out - Output buffer to validate.
|
||||
* @param instance - Hash-like instance providing `outputLen`.
|
||||
* This is the relaxed `digestInto()`-style contract: output must be at least `outputLen`,
|
||||
* unlike one-shot cipher helpers elsewhere in the repo that often require exact lengths.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @param onlyAligned - Whether `out` must be 4-byte aligned for zero-allocation word views.
|
||||
* @throws On wrong output buffer lengths. {@link RangeError}
|
||||
* @throws On wrong output buffer alignment. {@link Error}
|
||||
* @example
|
||||
* Verifies that a caller-provided output buffer is large enough.
|
||||
*
|
||||
* ```ts
|
||||
* aoutput(new Uint8Array(16), { outputLen: 16 });
|
||||
* ```
|
||||
*/
|
||||
export function aoutput(out, instance, onlyAligned = false) {
|
||||
abytes(out, undefined, 'output');
|
||||
const min = instance.outputLen;
|
||||
if (out.length < min) {
|
||||
throw new RangeError('digestInto() expects output buffer of length at least ' + min);
|
||||
}
|
||||
if (onlyAligned && !isAligned32(out))
|
||||
throw new Error('invalid output, must be aligned');
|
||||
}
|
||||
/**
|
||||
* Casts a typed-array view to Uint8Array.
|
||||
* @param arr - Typed-array view to reinterpret.
|
||||
* @returns Uint8Array view over the same bytes.
|
||||
* @example
|
||||
* Views 32-bit words as raw bytes without copying.
|
||||
*
|
||||
* ```ts
|
||||
* u8(new Uint32Array([1]));
|
||||
* ```
|
||||
*/
|
||||
export function u8(arr) {
|
||||
return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
|
||||
}
|
||||
/**
|
||||
* Casts a typed-array view to Uint32Array.
|
||||
* @param arr - Typed-array view to reinterpret.
|
||||
* @returns Uint32Array view over the same bytes. Callers are expected to provide a
|
||||
* 4-byte-aligned offset; trailing `1..3` bytes are silently dropped.
|
||||
* @example
|
||||
* Views a byte buffer as 32-bit words for block processing.
|
||||
*
|
||||
* ```ts
|
||||
* u32(new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export function u32(arr) {
|
||||
return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
|
||||
}
|
||||
/**
|
||||
* Zeroizes typed arrays in place.
|
||||
* Warning: JS provides no guarantees.
|
||||
* @param arrays - Arrays to wipe.
|
||||
* @example
|
||||
* Wipes a temporary key buffer after use.
|
||||
*
|
||||
* ```ts
|
||||
* const bytes = new Uint8Array([1]);
|
||||
* clean(bytes);
|
||||
* ```
|
||||
*/
|
||||
export function clean(...arrays) {
|
||||
for (let i = 0; i < arrays.length; i++) {
|
||||
arrays[i].fill(0);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Creates a DataView for byte-level manipulation.
|
||||
* @param arr - Typed-array view to wrap.
|
||||
* @returns DataView over the same bytes.
|
||||
* @example
|
||||
* Creates an endian-aware view for length encoding.
|
||||
*
|
||||
* ```ts
|
||||
* createView(new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export function createView(arr) {
|
||||
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
|
||||
}
|
||||
/**
|
||||
* Whether the current platform is little-endian.
|
||||
* Most are; some IBM systems are not.
|
||||
*/
|
||||
export const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
|
||||
/**
|
||||
* Reverses byte order of one 32-bit word.
|
||||
* @param word - Unsigned 32-bit word to swap.
|
||||
* @returns The same word with bytes reversed.
|
||||
* @example
|
||||
* Swaps a big-endian word into little-endian byte order.
|
||||
*
|
||||
* ```ts
|
||||
* byteSwap(0x11223344);
|
||||
* ```
|
||||
*/
|
||||
export const byteSwap = (word) => ((word << 24) & 0xff000000) |
|
||||
((word << 8) & 0xff0000) |
|
||||
((word >>> 8) & 0xff00) |
|
||||
((word >>> 24) & 0xff);
|
||||
/**
|
||||
* Normalizes one 32-bit word to the little-endian representation expected by cipher cores.
|
||||
* @param n - Unsigned 32-bit word to normalize.
|
||||
* @returns Little-endian normalized word on big-endian hosts, else the input word unchanged.
|
||||
* @example
|
||||
* Normalizes a host-endian word before passing it into an ARX/AES core.
|
||||
*
|
||||
* ```ts
|
||||
* swap8IfBE(0x11223344);
|
||||
* ```
|
||||
*/
|
||||
export const swap8IfBE = isLE
|
||||
? (n) => n
|
||||
: (n) => byteSwap(n) >>> 0;
|
||||
/**
|
||||
* Byte-swaps every word of a Uint32Array in place.
|
||||
* @param arr - Uint32Array whose words should be swapped.
|
||||
* @returns The same array after in-place byte swapping.
|
||||
* @example
|
||||
* Swaps every 32-bit word in a word-view buffer.
|
||||
*
|
||||
* ```ts
|
||||
* byteSwap32(new Uint32Array([0x11223344]));
|
||||
* ```
|
||||
*/
|
||||
export const byteSwap32 = (arr) => {
|
||||
for (let i = 0; i < arr.length; i++)
|
||||
arr[i] = byteSwap(arr[i]);
|
||||
return arr;
|
||||
};
|
||||
/**
|
||||
* Normalizes a Uint32Array view to the little-endian representation expected by cipher cores.
|
||||
* @param u - Word view to normalize in place.
|
||||
* @returns Little-endian normalized word view.
|
||||
* @example
|
||||
* Normalizes a word-view buffer before block processing.
|
||||
*
|
||||
* ```ts
|
||||
* swap32IfBE(new Uint32Array([0x11223344]));
|
||||
* ```
|
||||
*/
|
||||
export const swap32IfBE = isLE
|
||||
? (u) => u
|
||||
: byteSwap32;
|
||||
// Built-in hex conversion:
|
||||
// {@link https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex | caniuse entry}
|
||||
const hasHexBuiltin = /* @__PURE__ */ (() =>
|
||||
// @ts-ignore
|
||||
typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();
|
||||
// Array where index 0xf0 (240) is mapped to string 'f0'
|
||||
const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
|
||||
/**
|
||||
* Convert byte array to hex string. Uses built-in function, when available.
|
||||
* @param bytes - Bytes to encode.
|
||||
* @returns Lowercase hexadecimal string.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @example
|
||||
* Formats ciphertext bytes for logs or test vectors.
|
||||
*
|
||||
* ```ts
|
||||
* bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'
|
||||
* ```
|
||||
*/
|
||||
export function bytesToHex(bytes) {
|
||||
abytes(bytes);
|
||||
// @ts-ignore
|
||||
if (hasHexBuiltin)
|
||||
return bytes.toHex();
|
||||
// pre-caching improves the speed 6x
|
||||
let hex = '';
|
||||
for (let i = 0; i < bytes.length; i++) {
|
||||
hex += hexes[bytes[i]];
|
||||
}
|
||||
return hex;
|
||||
}
|
||||
// We use optimized technique to convert hex string to byte array
|
||||
const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
|
||||
function asciiToBase16(ch) {
|
||||
if (ch >= asciis._0 && ch <= asciis._9)
|
||||
return ch - asciis._0; // '2' => 50-48
|
||||
if (ch >= asciis.A && ch <= asciis.F)
|
||||
return ch - (asciis.A - 10); // 'B' => 66-(65-10)
|
||||
if (ch >= asciis.a && ch <= asciis.f)
|
||||
return ch - (asciis.a - 10); // 'b' => 98-(97-10)
|
||||
return;
|
||||
}
|
||||
/**
|
||||
* Convert hex string to byte array. Uses built-in function, when available.
|
||||
* @param hex - Hexadecimal string to decode.
|
||||
* @returns Decoded bytes.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @throws On malformed hexadecimal input. {@link RangeError}
|
||||
* @example
|
||||
* Parses a hex test vector into bytes.
|
||||
*
|
||||
* ```ts
|
||||
* hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
|
||||
* ```
|
||||
*/
|
||||
export function hexToBytes(hex) {
|
||||
if (typeof hex !== 'string')
|
||||
throw new TypeError('hex string expected, got ' + typeof hex);
|
||||
if (hasHexBuiltin) {
|
||||
try {
|
||||
return Uint8Array.fromHex(hex);
|
||||
}
|
||||
catch (error) {
|
||||
if (error instanceof SyntaxError)
|
||||
throw new RangeError(error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
const hl = hex.length;
|
||||
const al = hl / 2;
|
||||
if (hl % 2)
|
||||
throw new RangeError('hex string expected, got unpadded hex of length ' + hl);
|
||||
const array = new Uint8Array(al);
|
||||
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
|
||||
const n1 = asciiToBase16(hex.charCodeAt(hi));
|
||||
const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
|
||||
if (n1 === undefined || n2 === undefined) {
|
||||
const char = hex[hi] + hex[hi + 1];
|
||||
throw new RangeError('hex string expected, got non-hex character "' + char + '" at index ' + hi);
|
||||
}
|
||||
array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
|
||||
}
|
||||
return array;
|
||||
}
|
||||
// Used in micro
|
||||
/**
|
||||
* Converts a big-endian hex string into bigint.
|
||||
* @param hex - Hexadecimal string without `0x`.
|
||||
* @returns Parsed bigint value. The empty string is treated as `0n`.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @example
|
||||
* Parses a big-endian field element or counter from hex.
|
||||
*
|
||||
* ```ts
|
||||
* hexToNumber('ff');
|
||||
* ```
|
||||
*/
|
||||
export function hexToNumber(hex) {
|
||||
if (typeof hex !== 'string')
|
||||
throw new TypeError('hex string expected, got ' + typeof hex);
|
||||
return BigInt(hex === '' ? '0' : '0x' + hex); // Big Endian
|
||||
}
|
||||
// Used in ff1
|
||||
// BE: Big Endian, LE: Little Endian
|
||||
/**
|
||||
* Converts big-endian bytes into bigint.
|
||||
* @param bytes - Big-endian bytes.
|
||||
* @returns Parsed bigint value. Empty input is treated as `0n`.
|
||||
* @throws On invalid byte input passed to the internal hex conversion. {@link TypeError}
|
||||
* @example
|
||||
* Reads a big-endian integer from serialized bytes.
|
||||
*
|
||||
* ```ts
|
||||
* bytesToNumberBE(new Uint8Array([1, 0]));
|
||||
* ```
|
||||
*/
|
||||
export function bytesToNumberBE(bytes) {
|
||||
return hexToNumber(bytesToHex(bytes));
|
||||
}
|
||||
// Used in micro, ff1
|
||||
/**
|
||||
* Converts a number into big-endian bytes of fixed length.
|
||||
* @param n - Number to encode.
|
||||
* @param len - Output length in bytes.
|
||||
* @returns Big-endian bytes padded to `len`.
|
||||
* Validation is indirect through `hexToBytes(...)`, so negative values, `len = 0`,
|
||||
* and values that do not fit surface through the downstream hex parser instead of a
|
||||
* dedicated range guard here.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @throws If the requested output length cannot represent the encoded value. {@link RangeError}
|
||||
* @example
|
||||
* Encodes a counter as fixed-width big-endian bytes.
|
||||
*
|
||||
* ```ts
|
||||
* numberToBytesBE(1, 2);
|
||||
* ```
|
||||
*/
|
||||
export function numberToBytesBE(n, len) {
|
||||
// Reject coercible non-numeric inputs before string/hex conversion changes behavior.
|
||||
if (typeof n === 'number')
|
||||
anumber(n);
|
||||
else if (typeof n !== 'bigint')
|
||||
throw new TypeError(`number or bigint expected, got ${typeof n}`);
|
||||
anumber(len);
|
||||
return hexToBytes(n.toString(16).padStart(len * 2, '0'));
|
||||
}
|
||||
/**
|
||||
* Converts string to bytes using UTF8 encoding.
|
||||
* @param str - String to encode.
|
||||
* @returns UTF-8 bytes in a detached fresh Uint8Array copy.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @example
|
||||
* Encodes application text before encryption or MACing.
|
||||
*
|
||||
* ```ts
|
||||
* utf8ToBytes('abc'); // new Uint8Array([97, 98, 99])
|
||||
* ```
|
||||
*/
|
||||
export function utf8ToBytes(str) {
|
||||
if (typeof str !== 'string')
|
||||
throw new TypeError('string expected');
|
||||
return new Uint8Array(new TextEncoder().encode(str)); // {@link https://bugzil.la/1681809 | Firefox bug 1681809}
|
||||
}
|
||||
/**
|
||||
* Converts bytes to string using UTF8 encoding.
|
||||
* @param bytes - UTF-8 bytes.
|
||||
* @returns Decoded string. Input validation is delegated to `TextDecoder`, and malformed
|
||||
* UTF-8 is replacement-decoded instead of rejected.
|
||||
* @example
|
||||
* Decodes UTF-8 plaintext back into a string.
|
||||
*
|
||||
* ```ts
|
||||
* bytesToUtf8(new Uint8Array([97, 98, 99])); // 'abc'
|
||||
* ```
|
||||
*/
|
||||
export function bytesToUtf8(bytes) {
|
||||
return new TextDecoder().decode(bytes);
|
||||
}
|
||||
/**
|
||||
* Checks if two U8A use same underlying buffer and overlaps.
|
||||
* This is invalid and can corrupt data.
|
||||
* @param a - First byte view.
|
||||
* @param b - Second byte view.
|
||||
* @returns `true` when the views overlap in memory.
|
||||
* @example
|
||||
* Detects whether two slices alias the same backing buffer.
|
||||
*
|
||||
* ```ts
|
||||
* overlapBytes(new Uint8Array(4), new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export function overlapBytes(a, b) {
|
||||
// Zero-length views cannot overwrite anything, even if their offset sits inside another range.
|
||||
if (!a.byteLength || !b.byteLength)
|
||||
return false;
|
||||
return (a.buffer === b.buffer && // best we can do, may fail with an obscure Proxy
|
||||
a.byteOffset < b.byteOffset + b.byteLength && // a starts before b end
|
||||
b.byteOffset < a.byteOffset + a.byteLength // b starts before a end
|
||||
);
|
||||
}
|
||||
/**
|
||||
* If input and output overlap and input starts before output, we will overwrite end of input before
|
||||
* we start processing it, so this is not supported for most ciphers
|
||||
* (except chacha/salsa, which were designed for this)
|
||||
* @param input - Input bytes.
|
||||
* @param output - Output bytes.
|
||||
* @throws If the output view would overwrite unread input bytes. {@link Error}
|
||||
* @example
|
||||
* Rejects an in-place layout that would overwrite unread input bytes.
|
||||
*
|
||||
* ```ts
|
||||
* complexOverlapBytes(new Uint8Array(4), new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export function complexOverlapBytes(input, output) {
|
||||
// This is very cursed. It works somehow, but I'm completely unsure,
|
||||
// reasoning about overlapping aligned windows is very hard.
|
||||
if (overlapBytes(input, output) && input.byteOffset < output.byteOffset)
|
||||
throw new Error('complex overlap of input and output is not supported');
|
||||
}
|
||||
/**
|
||||
* Copies several Uint8Arrays into one.
|
||||
* @param arrays - Byte arrays to concatenate.
|
||||
* @returns Combined byte array.
|
||||
* @throws On wrong argument types inside the byte-array list. {@link TypeError}
|
||||
* @example
|
||||
* Builds a `nonce || ciphertext` style buffer.
|
||||
*
|
||||
* ```ts
|
||||
* concatBytes(new Uint8Array([1]), new Uint8Array([2]));
|
||||
* ```
|
||||
*/
|
||||
export function concatBytes(...arrays) {
|
||||
let sum = 0;
|
||||
for (let i = 0; i < arrays.length; i++) {
|
||||
const a = arrays[i];
|
||||
abytes(a);
|
||||
sum += a.length;
|
||||
}
|
||||
const res = new Uint8Array(sum);
|
||||
for (let i = 0, pad = 0; i < arrays.length; i++) {
|
||||
const a = arrays[i];
|
||||
res.set(a, pad);
|
||||
pad += a.length;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
/**
|
||||
* Merges user options into defaults.
|
||||
* @param defaults - Default option values.
|
||||
* @param opts - User-provided overrides.
|
||||
* @returns Combined options object.
|
||||
* The merge mutates `defaults` in place and returns the same object.
|
||||
* @throws If options are missing or not an object. {@link Error}
|
||||
* @example
|
||||
* Applies user overrides to the default cipher options.
|
||||
*
|
||||
* ```ts
|
||||
* checkOpts({ rounds: 20 }, { rounds: 8 });
|
||||
* ```
|
||||
*/
|
||||
export function checkOpts(defaults, opts) {
|
||||
if (opts == null || typeof opts !== 'object')
|
||||
throw new Error('options must be defined');
|
||||
const merged = Object.assign(defaults, opts);
|
||||
return merged;
|
||||
}
|
||||
/**
|
||||
* Compares two byte arrays in kinda constant time once lengths already match.
|
||||
* @param a - First byte array.
|
||||
* @param b - Second byte array.
|
||||
* @returns `true` when the arrays contain the same bytes. Different lengths still return early.
|
||||
* @example
|
||||
* Compares an expected authentication tag with the received one.
|
||||
*
|
||||
* ```ts
|
||||
* equalBytes(new Uint8Array([1]), new Uint8Array([1]));
|
||||
* ```
|
||||
*/
|
||||
export function equalBytes(a, b) {
|
||||
if (a.length !== b.length)
|
||||
return false;
|
||||
let diff = 0;
|
||||
for (let i = 0; i < a.length; i++)
|
||||
diff |= a[i] ^ b[i];
|
||||
return diff === 0;
|
||||
}
|
||||
/**
|
||||
* Wraps a keyed MAC constructor into a one-shot helper with `.create()`.
|
||||
* @param keyLen - Valid probe-key length used to read static metadata once.
|
||||
* The probe key is only used for `outputLen` / `blockLen`, so callers with several valid key sizes
|
||||
* can pass any representative size as long as those values stay fixed.
|
||||
* @param macCons - Keyed MAC constructor or factory.
|
||||
* @param fromMsg - Optional adapter that derives extra constructor args from the one-shot message.
|
||||
* @returns Callable MAC helper with `.create()`.
|
||||
*/
|
||||
export function wrapMacConstructor(keyLen, macCons, fromMsg) {
|
||||
const mac = macCons;
|
||||
const getArgs = (fromMsg || (() => []));
|
||||
const macC = (msg, key) => mac(key, ...getArgs(msg))
|
||||
.update(msg)
|
||||
.digest();
|
||||
const tmp = mac(new Uint8Array(keyLen), ...getArgs(new Uint8Array(0)));
|
||||
macC.outputLen = tmp.outputLen;
|
||||
macC.blockLen = tmp.blockLen;
|
||||
macC.create = (key, ...args) => mac(key, ...args);
|
||||
return macC;
|
||||
}
|
||||
/**
|
||||
* Wraps a cipher: validates args, ensures encrypt() can only be called once.
|
||||
* Used internally by the exported cipher constructors.
|
||||
* Output-buffer support is inferred from the wrapped `encrypt` / `decrypt`
|
||||
* arity (`fn.length === 2`), and tag-bearing constructors are expected to use
|
||||
* `args[1]` for optional AAD.
|
||||
* @__NO_SIDE_EFFECTS__
|
||||
* @param params - Static cipher metadata. See {@link CipherParams}.
|
||||
* @param constructor - Cipher constructor.
|
||||
* @returns Wrapped constructor with validation.
|
||||
*/
|
||||
export const wrapCipher = (params, constructor) => {
|
||||
function wrappedCipher(key, ...args) {
|
||||
// Validate key
|
||||
abytes(key, undefined, 'key');
|
||||
// Validate nonce if nonceLength is present
|
||||
if (params.nonceLength !== undefined) {
|
||||
const nonce = args[0];
|
||||
abytes(nonce, params.varSizeNonce ? undefined : params.nonceLength, 'nonce');
|
||||
}
|
||||
// Validate AAD if tagLength present
|
||||
const tagl = params.tagLength;
|
||||
if (tagl && args[1] !== undefined)
|
||||
abytes(args[1], undefined, 'AAD');
|
||||
const cipher = constructor(key, ...args);
|
||||
const checkOutput = (fnLength, output) => {
|
||||
if (output !== undefined) {
|
||||
if (fnLength !== 2)
|
||||
throw new Error('cipher output not supported');
|
||||
abytes(output, undefined, 'output');
|
||||
}
|
||||
};
|
||||
// Create wrapped cipher with validation and single-use encryption
|
||||
let called = false;
|
||||
const wrCipher = {
|
||||
encrypt(data, output) {
|
||||
if (called)
|
||||
throw new Error('cannot encrypt() twice with same key + nonce');
|
||||
called = true;
|
||||
abytes(data);
|
||||
checkOutput(cipher.encrypt.length, output);
|
||||
return cipher.encrypt(data, output);
|
||||
},
|
||||
decrypt(data, output) {
|
||||
abytes(data);
|
||||
if (tagl && data.length < tagl)
|
||||
throw new Error('"ciphertext" expected length bigger than tagLength=' + tagl);
|
||||
checkOutput(cipher.decrypt.length, output);
|
||||
return cipher.decrypt(data, output);
|
||||
},
|
||||
};
|
||||
return wrCipher;
|
||||
}
|
||||
Object.assign(wrappedCipher, params);
|
||||
return wrappedCipher;
|
||||
};
|
||||
/**
|
||||
* By default, returns u8a of length.
|
||||
* When out is available, it checks it for validity and uses it.
|
||||
* @param expectedLength - Required output length.
|
||||
* @param out - Optional destination buffer.
|
||||
* @param onlyAligned - Whether `out` must be 4-byte aligned.
|
||||
* @returns Output buffer ready for writing.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @throws If the provided output buffer has the wrong size or alignment. {@link Error}
|
||||
* @example
|
||||
* Reuses a caller-provided output buffer when lengths match.
|
||||
*
|
||||
* ```ts
|
||||
* getOutput(16, new Uint8Array(16));
|
||||
* ```
|
||||
*/
|
||||
export function getOutput(expectedLength, out, onlyAligned = true) {
|
||||
if (out === undefined)
|
||||
return new Uint8Array(expectedLength);
|
||||
// Keep Buffer/cross-realm Uint8Array support here instead of trusting a shape-compatible object.
|
||||
abytes(out, undefined, 'output');
|
||||
if (out.length !== expectedLength)
|
||||
throw new Error('"output" expected Uint8Array of length ' + expectedLength + ', got: ' + out.length);
|
||||
if (onlyAligned && !isAligned32(out))
|
||||
throw new Error('invalid output, must be aligned');
|
||||
return out;
|
||||
}
|
||||
/**
|
||||
* Encodes data and AAD bit lengths into a 16-byte buffer.
|
||||
* @param dataLength - Data length in bits.
|
||||
* @param aadLength - AAD length in bits.
|
||||
* The serialized block is still `aadLength || dataLength`, matching GCM/Poly1305
|
||||
* conventions even though the helper parameter order is `(dataLength, aadLength)`.
|
||||
* @param isLE - Whether to encode lengths as little-endian.
|
||||
* @returns 16-byte length block.
|
||||
* @throws On wrong argument types passed to the endian validator. {@link TypeError}
|
||||
* @throws On wrong argument ranges or values. {@link RangeError}
|
||||
* @example
|
||||
* Builds the length block appended by GCM and Poly1305.
|
||||
*
|
||||
* ```ts
|
||||
* u64Lengths(16, 8, true);
|
||||
* ```
|
||||
*/
|
||||
export function u64Lengths(dataLength, aadLength, isLE) {
|
||||
// Reject coercible non-number lengths like '10' and true before BigInt(...) accepts them.
|
||||
anumber(dataLength);
|
||||
anumber(aadLength);
|
||||
abool(isLE);
|
||||
const num = new Uint8Array(16);
|
||||
const view = createView(num);
|
||||
view.setBigUint64(0, BigInt(aadLength), isLE);
|
||||
view.setBigUint64(8, BigInt(dataLength), isLE);
|
||||
return num;
|
||||
}
|
||||
/**
|
||||
* Checks whether a byte array is aligned to a 4-byte offset.
|
||||
* @param bytes - Byte array to inspect.
|
||||
* @returns `true` when the view is 4-byte aligned.
|
||||
* @example
|
||||
* Checks whether a buffer can be safely viewed as Uint32Array.
|
||||
*
|
||||
* ```ts
|
||||
* isAligned32(new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export function isAligned32(bytes) {
|
||||
return bytes.byteOffset % 4 === 0;
|
||||
}
|
||||
/**
|
||||
* Copies bytes into a new Uint8Array.
|
||||
* @param bytes - Bytes to copy.
|
||||
* @returns Copied byte array.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @example
|
||||
* Copies input into an aligned Uint8Array before block processing.
|
||||
*
|
||||
* ```ts
|
||||
* copyBytes(new Uint8Array([1, 2]));
|
||||
* ```
|
||||
*/
|
||||
export function copyBytes(bytes) {
|
||||
// `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict
|
||||
// because callers use it at byte-validation boundaries before mutating the detached copy.
|
||||
return Uint8Array.from(abytes(bytes));
|
||||
}
|
||||
/**
|
||||
* Cryptographically secure PRNG.
|
||||
* Uses internal OS-level `crypto.getRandomValues`.
|
||||
* @param bytesLength - Number of bytes to produce.
|
||||
* Validation is delegated to `Uint8Array(bytesLength)` and `getRandomValues`, so
|
||||
* non-integers, negative lengths, and oversize requests surface backend/runtime errors.
|
||||
* @returns Random byte array.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @throws On wrong argument ranges or values. {@link RangeError}
|
||||
* @throws If the runtime does not expose `crypto.getRandomValues`. {@link Error}
|
||||
* @example
|
||||
* Generates a fresh nonce or key.
|
||||
*
|
||||
* ```ts
|
||||
* randomBytes(16);
|
||||
* ```
|
||||
*/
|
||||
export function randomBytes(bytesLength = 32) {
|
||||
// Validate upfront so fractional / coercible lengths do not silently
|
||||
// truncate through Uint8Array().
|
||||
anumber(bytesLength);
|
||||
const cr = typeof globalThis === 'object' ? globalThis.crypto : null;
|
||||
if (typeof cr?.getRandomValues !== 'function')
|
||||
throw new Error('crypto.getRandomValues must be defined');
|
||||
return cr.getRandomValues(new Uint8Array(bytesLength));
|
||||
}
|
||||
/**
|
||||
* Uses CSPRNG for nonce, nonce injected in ciphertext.
|
||||
* For `encrypt`, a `nonceBytes`-length buffer is fetched from CSPRNG and
|
||||
* prepended to encrypted ciphertext. For `decrypt`, first `nonceBytes` of ciphertext
|
||||
* are treated as nonce. The wrapper always allocates a fresh `nonce || ciphertext`
|
||||
* buffer on encrypt and intentionally does not support caller-provided destination buffers.
|
||||
* Too-short decrypt inputs are split into short/empty nonce views and then delegated
|
||||
* to the wrapped cipher instead of being rejected here first.
|
||||
*
|
||||
* NOTE: Under the same key, using random nonces (e.g. `managedNonce`) with AES-GCM and ChaCha
|
||||
* should be limited to `2**23` (8M) messages to get a collision chance of
|
||||
* `2**-50`. Stretching to `2**32` (4B) messages would raise that chance to
|
||||
* `2**-33`, still negligible but creeping up.
|
||||
* @param fn - Cipher constructor that expects a nonce.
|
||||
* @param randomBytes_ - Random-byte source used for nonce generation.
|
||||
* @returns Cipher constructor that prepends the nonce to ciphertext.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @throws On invalid nonce lengths observed at wrapper construction or use. {@link RangeError}
|
||||
* @example
|
||||
* Prepends a fresh random nonce to every ciphertext.
|
||||
*
|
||||
* ```ts
|
||||
* import { gcm } from '@noble/ciphers/aes.js';
|
||||
* import { managedNonce, randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const wrapped = managedNonce(gcm);
|
||||
* const key = randomBytes(16);
|
||||
* const ciphertext = wrapped(key).encrypt(new Uint8Array([1, 2, 3]));
|
||||
* wrapped(key).decrypt(ciphertext);
|
||||
* ```
|
||||
*/
|
||||
export function managedNonce(fn, randomBytes_ = randomBytes) {
|
||||
const { nonceLength } = fn;
|
||||
anumber(nonceLength);
|
||||
const addNonce = (nonce, ciphertext, plaintext) => {
|
||||
const out = concatBytes(nonce, ciphertext);
|
||||
// Wrapped ciphers may alias caller plaintext on encrypt(); never zero
|
||||
// caller-owned buffers here.
|
||||
if (!overlapBytes(plaintext, ciphertext))
|
||||
ciphertext.fill(0);
|
||||
return out;
|
||||
};
|
||||
// NOTE: we cannot support DST here, it would be mistake:
|
||||
// - we don't know how much dst length cipher requires
|
||||
// - nonce may unalign dst and break everything
|
||||
// - we create new u8a anyway (concatBytes)
|
||||
// - previously we passed all args to cipher, but that was mistake!
|
||||
const res = ((key, ...args) => ({
|
||||
encrypt(plaintext) {
|
||||
abytes(plaintext);
|
||||
const nonce = randomBytes_(nonceLength);
|
||||
const encrypted = fn(key, nonce, ...args).encrypt(plaintext);
|
||||
// @ts-ignore
|
||||
if (encrypted instanceof Promise)
|
||||
return encrypted.then((ct) => addNonce(nonce, ct, plaintext));
|
||||
return addNonce(nonce, encrypted, plaintext);
|
||||
},
|
||||
decrypt(ciphertext) {
|
||||
abytes(ciphertext);
|
||||
const nonce = ciphertext.subarray(0, nonceLength);
|
||||
const decrypted = ciphertext.subarray(nonceLength);
|
||||
return fn(key, nonce, ...args).decrypt(decrypted);
|
||||
},
|
||||
}));
|
||||
// Auto-nonce wrappers still preserve the wrapped payload geometry.
|
||||
if ('blockSize' in fn)
|
||||
res.blockSize = fn.blockSize;
|
||||
if ('tagLength' in fn)
|
||||
res.tagLength = fn.tagLength;
|
||||
return res;
|
||||
}
|
||||
//# sourceMappingURL=utils.js.map
|
||||
1
node_modules/@noble/ciphers/utils.js.map
generated
vendored
Normal file
1
node_modules/@noble/ciphers/utils.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
89
node_modules/@noble/ciphers/webcrypto.d.ts
generated
vendored
Normal file
89
node_modules/@noble/ciphers/webcrypto.d.ts
generated
vendored
Normal file
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* WebCrypto-based AES gcm/ctr/cbc, `managedNonce` and `randomBytes`.
|
||||
* We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
|
||||
* @module
|
||||
*/
|
||||
import { type AsyncCipher, type TArg, type TRet } from './utils.ts';
|
||||
type WebcryptoUtils = {
|
||||
encrypt(key: TArg<Uint8Array>, keyParams: unknown, cryptParams: unknown, plaintext: TArg<Uint8Array>): Promise<TRet<Uint8Array>>;
|
||||
decrypt(key: TArg<Uint8Array>, keyParams: unknown, cryptParams: unknown, ciphertext: TArg<Uint8Array>): Promise<TRet<Uint8Array>>;
|
||||
};
|
||||
/**
|
||||
* Internal webcrypto utils. Can be overridden if crypto.subtle is not present,
|
||||
* for example in React Native.
|
||||
* Raw keys are re-imported on every call; this wrapper intentionally does not
|
||||
* cache `CryptoKey` objects between operations.
|
||||
*/
|
||||
export declare const utils: TRet<WebcryptoUtils>;
|
||||
/**
|
||||
* AES-CBC implemented with WebCrypto.
|
||||
* Uses WebCrypto's built-in PKCS padding behavior; exact IV-length checks are
|
||||
* delegated to the backend instead of local `abytes(..., 16)` validation.
|
||||
* @param key - AES key bytes.
|
||||
* @param iv - 16-byte initialization vector.
|
||||
* @returns Async cipher instance.
|
||||
* @example
|
||||
* Encrypts a block with the browser or Node WebCrypto backend.
|
||||
*
|
||||
* ```ts
|
||||
* import { cbc } from '@noble/ciphers/webcrypto.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const iv = randomBytes(16);
|
||||
* const cipher = cbc(key, iv);
|
||||
* await cipher.encrypt(new Uint8Array(16));
|
||||
* ```
|
||||
*/
|
||||
export declare const cbc: TRet<((key: TArg<Uint8Array>, iv: TArg<Uint8Array>) => AsyncCipher) & {
|
||||
blockSize: number;
|
||||
nonceLength: number;
|
||||
}>;
|
||||
/**
|
||||
* AES-CTR implemented with WebCrypto.
|
||||
* Uses WebCrypto's full 128-bit counter-length setting so the whole
|
||||
* 16-byte counter block is incremented, matching sync `aes.ts:ctr`.
|
||||
* @param key - AES key bytes.
|
||||
* @param nonce - 16-byte counter block incremented as a full big-endian AES counter block.
|
||||
* @returns Async cipher instance.
|
||||
* @example
|
||||
* Encrypts a short payload with WebCrypto AES-CTR.
|
||||
*
|
||||
* ```ts
|
||||
* import { ctr } from '@noble/ciphers/webcrypto.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const nonce = randomBytes(16);
|
||||
* const cipher = ctr(key, nonce);
|
||||
* await cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export declare const ctr: TRet<((key: TArg<Uint8Array>, nonce: TArg<Uint8Array>) => AsyncCipher) & {
|
||||
blockSize: number;
|
||||
nonceLength: number;
|
||||
}>;
|
||||
/**
|
||||
* AES-GCM implemented with WebCrypto.
|
||||
* AAD type normalization and nonce-shape enforcement beyond raw bytes are left
|
||||
* to the backend WebCrypto implementation.
|
||||
* @param key - AES key bytes.
|
||||
* @param nonce - Nonce bytes.
|
||||
* @param AAD - Additional authenticated data.
|
||||
* @returns Async cipher instance.
|
||||
* @example
|
||||
* Encrypts and authenticates plaintext with WebCrypto AES-GCM.
|
||||
*
|
||||
* ```ts
|
||||
* import { gcm } from '@noble/ciphers/webcrypto.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const nonce = randomBytes(12);
|
||||
* const cipher = gcm(key, nonce);
|
||||
* await cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export declare const gcm: TRet<((key: TArg<Uint8Array>, nonce: TArg<Uint8Array>, AAD?: TArg<Uint8Array>) => AsyncCipher) & {
|
||||
blockSize: number;
|
||||
nonceLength: number;
|
||||
}>;
|
||||
export {};
|
||||
//# sourceMappingURL=webcrypto.d.ts.map
|
||||
1
node_modules/@noble/ciphers/webcrypto.d.ts.map
generated
vendored
Normal file
1
node_modules/@noble/ciphers/webcrypto.d.ts.map
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"webcrypto.d.ts","sourceRoot":"","sources":["src/webcrypto.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAmB,KAAK,WAAW,EAAE,KAAK,IAAI,EAAE,KAAK,IAAI,EAAE,MAAM,YAAY,CAAC;AAQrF,KAAK,cAAc,GAAG;IACpB,OAAO,CACL,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EACrB,SAAS,EAAE,OAAO,EAClB,WAAW,EAAE,OAAO,EACpB,SAAS,EAAE,IAAI,CAAC,UAAU,CAAC,GAC1B,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC;IAC7B,OAAO,CACL,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EACrB,SAAS,EAAE,OAAO,EAClB,WAAW,EAAE,OAAO,EACpB,UAAU,EAAE,IAAI,CAAC,UAAU,CAAC,GAC3B,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC;CAC9B,CAAC;AACF;;;;;GAKG;AACH,eAAO,MAAM,KAAK,EAAE,IAAI,CAAC,cAAc,CAuBtC,CAAC;AAwEF;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,GAAG,EAAE,IAAI,CACpB,CAAC,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,EAAE,EAAE,IAAI,CAAC,UAAU,CAAC,KAAK,WAAW,CAAC,GAAG;IAC/D,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;CACrB,CACiD,CAAC;AACrD;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,GAAG,EAAE,IAAI,CACpB,CAAC,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,UAAU,CAAC,KAAK,WAAW,CAAC,GAAG;IAClE,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;CACrB,CACiD,CAAC;AACrD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,eAAO,MAAM,GAAG,EAAE,IAAI,CACpB,CAAC,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,GAAG,CAAC,EAAE,IAAI,CAAC,UAAU,CAAC,KAAK,WAAW,CAAC,GAAG;IAC1F,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;CACrB,CACiD,CAAC"}
|
||||
167
node_modules/@noble/ciphers/webcrypto.js
generated
vendored
Normal file
167
node_modules/@noble/ciphers/webcrypto.js
generated
vendored
Normal file
@@ -0,0 +1,167 @@
|
||||
/**
|
||||
* WebCrypto-based AES gcm/ctr/cbc, `managedNonce` and `randomBytes`.
|
||||
* We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
|
||||
* @module
|
||||
*/
|
||||
import { abytes, anumber } from "./utils.js";
|
||||
function getWebcryptoSubtle() {
|
||||
const cr = typeof globalThis !== 'undefined' && globalThis.crypto;
|
||||
if (cr && typeof cr.subtle === 'object' && cr.subtle != null)
|
||||
return cr.subtle;
|
||||
throw new Error('crypto.subtle must be defined');
|
||||
}
|
||||
/**
|
||||
* Internal webcrypto utils. Can be overridden if crypto.subtle is not present,
|
||||
* for example in React Native.
|
||||
* Raw keys are re-imported on every call; this wrapper intentionally does not
|
||||
* cache `CryptoKey` objects between operations.
|
||||
*/
|
||||
export const utils = {
|
||||
async encrypt(key, keyParams, cryptParams, plaintext) {
|
||||
const cr = getWebcryptoSubtle();
|
||||
const iKey = await cr.importKey('raw', key, keyParams, true, ['encrypt']);
|
||||
const ciphertext = await cr.encrypt(cryptParams, iKey, plaintext);
|
||||
return new Uint8Array(ciphertext);
|
||||
},
|
||||
async decrypt(key, keyParams, cryptParams, ciphertext) {
|
||||
const cr = getWebcryptoSubtle();
|
||||
const iKey = await cr.importKey('raw', key, keyParams, true, ['decrypt']);
|
||||
const plaintext = await cr.decrypt(cryptParams, iKey, ciphertext);
|
||||
return new Uint8Array(plaintext);
|
||||
},
|
||||
};
|
||||
const mode = {
|
||||
CBC: 'AES-CBC',
|
||||
CTR: 'AES-CTR',
|
||||
GCM: 'AES-GCM',
|
||||
};
|
||||
function getCryptParams(algo, nonce, AAD) {
|
||||
if (algo === mode.CBC)
|
||||
return { name: mode.CBC, iv: nonce };
|
||||
// WebCrypto allows 1..128 counter bits; use the full block to match sync ctr() / Node CTR wrap.
|
||||
if (algo === mode.CTR)
|
||||
return { name: mode.CTR, counter: nonce, length: 128 };
|
||||
if (algo === mode.GCM) {
|
||||
// Rely on the backend default tag length (128 bits) instead of setting it explicitly.
|
||||
if (AAD)
|
||||
return { name: mode.GCM, iv: nonce, additionalData: AAD };
|
||||
else
|
||||
return { name: mode.GCM, iv: nonce };
|
||||
}
|
||||
throw new Error('unknown aes block mode');
|
||||
}
|
||||
function generate(algo, nonceLength) {
|
||||
anumber(nonceLength);
|
||||
const res = (key, nonce, AAD) => {
|
||||
abytes(key);
|
||||
abytes(nonce);
|
||||
// Reject falsy non-byte AAD locally; otherwise false/0/''/null silently become "no AAD".
|
||||
if (AAD !== undefined)
|
||||
abytes(AAD, undefined, 'AAD');
|
||||
// Exact nonce-length enforcement and WebCrypto-specific AAD normalization are
|
||||
// delegated to the backend; locally we only require byte-array inputs here.
|
||||
// Keep caller key/nonce/AAD by reference; mutating them after
|
||||
// construction changes later operations.
|
||||
const keyParams = { name: algo, length: key.length * 8 };
|
||||
const cryptParams = getCryptParams(algo, nonce, AAD);
|
||||
let consumed = false;
|
||||
return {
|
||||
// keyLength,
|
||||
encrypt(plaintext) {
|
||||
abytes(plaintext);
|
||||
if (consumed)
|
||||
throw new Error('Cannot encrypt() twice with same key / nonce');
|
||||
consumed = true;
|
||||
return utils.encrypt(key, keyParams, cryptParams, plaintext);
|
||||
},
|
||||
decrypt(ciphertext) {
|
||||
abytes(ciphertext);
|
||||
return utils.decrypt(key, keyParams, cryptParams, ciphertext);
|
||||
},
|
||||
};
|
||||
};
|
||||
res.nonceLength = nonceLength;
|
||||
res.blockSize = 16; // always for AES
|
||||
return res;
|
||||
}
|
||||
/**
|
||||
* AES-CBC implemented with WebCrypto.
|
||||
* Uses WebCrypto's built-in PKCS padding behavior; exact IV-length checks are
|
||||
* delegated to the backend instead of local `abytes(..., 16)` validation.
|
||||
* @param key - AES key bytes.
|
||||
* @param iv - 16-byte initialization vector.
|
||||
* @returns Async cipher instance.
|
||||
* @example
|
||||
* Encrypts a block with the browser or Node WebCrypto backend.
|
||||
*
|
||||
* ```ts
|
||||
* import { cbc } from '@noble/ciphers/webcrypto.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const iv = randomBytes(16);
|
||||
* const cipher = cbc(key, iv);
|
||||
* await cipher.encrypt(new Uint8Array(16));
|
||||
* ```
|
||||
*/
|
||||
export const cbc = /* @__PURE__ */ (() => generate(mode.CBC, 16))();
|
||||
/**
|
||||
* AES-CTR implemented with WebCrypto.
|
||||
* Uses WebCrypto's full 128-bit counter-length setting so the whole
|
||||
* 16-byte counter block is incremented, matching sync `aes.ts:ctr`.
|
||||
* @param key - AES key bytes.
|
||||
* @param nonce - 16-byte counter block incremented as a full big-endian AES counter block.
|
||||
* @returns Async cipher instance.
|
||||
* @example
|
||||
* Encrypts a short payload with WebCrypto AES-CTR.
|
||||
*
|
||||
* ```ts
|
||||
* import { ctr } from '@noble/ciphers/webcrypto.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const nonce = randomBytes(16);
|
||||
* const cipher = ctr(key, nonce);
|
||||
* await cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export const ctr = /* @__PURE__ */ (() => generate(mode.CTR, 16))();
|
||||
/**
|
||||
* AES-GCM implemented with WebCrypto.
|
||||
* AAD type normalization and nonce-shape enforcement beyond raw bytes are left
|
||||
* to the backend WebCrypto implementation.
|
||||
* @param key - AES key bytes.
|
||||
* @param nonce - Nonce bytes.
|
||||
* @param AAD - Additional authenticated data.
|
||||
* @returns Async cipher instance.
|
||||
* @example
|
||||
* Encrypts and authenticates plaintext with WebCrypto AES-GCM.
|
||||
*
|
||||
* ```ts
|
||||
* import { gcm } from '@noble/ciphers/webcrypto.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const nonce = randomBytes(12);
|
||||
* const cipher = gcm(key, nonce);
|
||||
* await cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export const gcm = /* @__PURE__ */ (() => generate(mode.GCM, 12))();
|
||||
// // Type tests
|
||||
// import { siv, gcm, ctr, ecb, cbc } from '../aes.ts';
|
||||
// import { xsalsa20poly1305 } from '../salsa.ts';
|
||||
// import { chacha20poly1305, xchacha20poly1305 } from '../chacha.ts';
|
||||
// const wsiv = managedNonce(siv);
|
||||
// const wgcm = managedNonce(gcm);
|
||||
// const wctr = managedNonce(ctr);
|
||||
// const wcbc = managedNonce(cbc);
|
||||
// const wsalsapoly = managedNonce(xsalsa20poly1305);
|
||||
// const wchacha = managedNonce(chacha20poly1305);
|
||||
// const wxchacha = managedNonce(xchacha20poly1305);
|
||||
// // should fail
|
||||
// const wcbc2 = managedNonce(managedNonce(cbc));
|
||||
// const wctr = managedNonce(ctr);
|
||||
// import { gcm as gcmSync } from '../aes.ts';
|
||||
// const x1 = managedNonce(gcmSync);
|
||||
// // const x1: (key: Uint8Array, AAD?: Uint8Array | undefined) => Cipher
|
||||
// const x2 = managedNonce(gcm);
|
||||
// // const x2: (key: Uint8Array, AAD?: Uint8Array | undefined) => AsyncCipher
|
||||
//# sourceMappingURL=webcrypto.js.map
|
||||
1
node_modules/@noble/ciphers/webcrypto.js.map
generated
vendored
Normal file
1
node_modules/@noble/ciphers/webcrypto.js.map
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"webcrypto.js","sourceRoot":"","sources":["src/webcrypto.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,MAAM,EAAE,OAAO,EAA0C,MAAM,YAAY,CAAC;AAErF,SAAS,kBAAkB;IACzB,MAAM,EAAE,GAAG,OAAO,UAAU,KAAK,WAAW,IAAK,UAAkB,CAAC,MAAM,CAAC;IAC3E,IAAI,EAAE,IAAI,OAAO,EAAE,CAAC,MAAM,KAAK,QAAQ,IAAI,EAAE,CAAC,MAAM,IAAI,IAAI;QAAE,OAAO,EAAE,CAAC,MAAM,CAAC;IAC/E,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;AACnD,CAAC;AAgBD;;;;;GAKG;AACH,MAAM,CAAC,MAAM,KAAK,GAAyB;IACzC,KAAK,CAAC,OAAO,CACX,GAAqB,EACrB,SAAc,EACd,WAAgB,EAChB,SAA2B;QAE3B,MAAM,EAAE,GAAG,kBAAkB,EAAE,CAAC;QAChC,MAAM,IAAI,GAAG,MAAM,EAAE,CAAC,SAAS,CAAC,KAAK,EAAE,GAAG,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC;QAC1E,MAAM,UAAU,GAAG,MAAM,EAAE,CAAC,OAAO,CAAC,WAAW,EAAE,IAAI,EAAE,SAAS,CAAC,CAAC;QAClE,OAAO,IAAI,UAAU,CAAC,UAAU,CAAqB,CAAC;IACxD,CAAC;IACD,KAAK,CAAC,OAAO,CACX,GAAqB,EACrB,SAAc,EACd,WAAgB,EAChB,UAA4B;QAE5B,MAAM,EAAE,GAAG,kBAAkB,EAAE,CAAC;QAChC,MAAM,IAAI,GAAG,MAAM,EAAE,CAAC,SAAS,CAAC,KAAK,EAAE,GAAG,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC;QAC1E,MAAM,SAAS,GAAG,MAAM,EAAE,CAAC,OAAO,CAAC,WAAW,EAAE,IAAI,EAAE,UAAU,CAAC,CAAC;QAClE,OAAO,IAAI,UAAU,CAAC,SAAS,CAAqB,CAAC;IACvD,CAAC;CACF,CAAC;AAEF,MAAM,IAAI,GAAG;IACX,GAAG,EAAE,SAAS;IACd,GAAG,EAAE,SAAS;IACd,GAAG,EAAE,SAAS;CACN,CAAC;AAGX,SAAS,cAAc,CAAC,IAAe,EAAE,KAAuB,EAAE,GAAsB;IACtF,IAAI,IAAI,KAAK,IAAI,CAAC,GAAG;QAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC;IAC5D,gGAAgG;IAChG,IAAI,IAAI,KAAK,IAAI,CAAC,GAAG;QAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,GAAG,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC;IAC9E,IAAI,IAAI,KAAK,IAAI,CAAC,GAAG,EAAE,CAAC;QACtB,sFAAsF;QACtF,IAAI,GAAG;YAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE,EAAE,KAAK,EAAE,cAAc,EAAE,GAAG,EAAE,CAAC;;YAC9D,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC;IAC5C,CAAC;IAED,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAC;AAC5C,CAAC;AAED,SAAS,QAAQ,CACf,IAAe,EACf,WAAmB;IAOnB,OAAO,CAAC,WAAW,CAAC,CAAC;IACrB,MAAM,GAAG,GAAG,CACV,GAAqB,EACrB,KAAuB,EACvB,GAAsB,EACH,EAAE;QACrB,MAAM,CAAC,GAAG,CAAC,CAAC;QACZ,MAAM,CAAC,KAAK,CAAC,CAAC;QACd,yFAAyF;QACzF,IAAI,GAAG,KAAK,SAAS;YAAE,MAAM,CAAC,GAAG,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC;QACrD,8EAA8E;QAC9E,4EAA4E;QAC5E,8DAA8D;QAC9D,yCAAyC;QACzC,MAAM,SAAS,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACzD,MAAM,WAAW,GAAG,cAAc,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,CAAC,CAAC;QACrD,IAAI,QAAQ,GAAG,KAAK,CAAC;QACrB,OAAO;YACL,aAAa;YACb,OAAO,CAAC,SAA2B;gBACjC,MAAM,CAAC,SAAS,CAAC,CAAC;gBAClB,IAAI,QAAQ;oBAAE,MAAM,IAAI,KAAK,CAAC,8CAA8C,CAAC,CAAC;gBAC9E,QAAQ,GAAG,IAAI,CAAC;gBAChB,OAAO,KAAK,CAAC,OAAO,CAAC,GAAG,EAAE,SAAS,EAAE,WAAW,EAAE,SAAS,CAAC,CAAC;YAC/D,CAAC;YACD,OAAO,CAAC,UAA4B;gBAClC,MAAM,CAAC,UAAU,CAAC,CAAC;gBACnB,OAAO,KAAK,CAAC,OAAO,CAAC,GAAG,EAAE,SAAS,EAAE,WAAW,EAAE,UAAU,CAAC,CAAC;YAChE,CAAC;SACmB,CAAC;IACzB,CAAC,CAAC;IACF,GAAG,CAAC,WAAW,GAAG,WAAW,CAAC;IAC9B,GAAG,CAAC,SAAS,GAAG,EAAE,CAAC,CAAC,iBAAiB;IACrC,OAAO,GAKN,CAAC;AACJ,CAAC;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,CAAC,MAAM,GAAG,GAKZ,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC;AACrD;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,CAAC,MAAM,GAAG,GAKZ,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC;AACrD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,CAAC,MAAM,GAAG,GAKZ,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC;AAErD,gBAAgB;AAChB,uDAAuD;AACvD,kDAAkD;AAClD,sEAAsE;AAEtE,kCAAkC;AAClC,kCAAkC;AAClC,kCAAkC;AAClC,kCAAkC;AAClC,qDAAqD;AACrD,kDAAkD;AAClD,oDAAoD;AAEpD,iBAAiB;AACjB,iDAAiD;AACjD,kCAAkC;AAClC,8CAA8C;AAC9C,oCAAoC;AACpC,yEAAyE;AACzE,gCAAgC;AAChC,8EAA8E"}
|
||||
21
node_modules/@noble/curves/LICENSE
generated
vendored
Normal file
21
node_modules/@noble/curves/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2022 Paul Miller (https://paulmillr.com)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the “Software”), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
1129
node_modules/@noble/curves/README.md
generated
vendored
Normal file
1129
node_modules/@noble/curves/README.md
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
411
node_modules/@noble/curves/abstract/bls.d.ts
generated
vendored
Normal file
411
node_modules/@noble/curves/abstract/bls.d.ts
generated
vendored
Normal file
@@ -0,0 +1,411 @@
|
||||
/**
|
||||
* BLS != BLS.
|
||||
* The file implements BLS (Boneh-Lynn-Shacham) signatures.
|
||||
* Used in both BLS (Barreto-Lynn-Scott) and BN (Barreto-Naehrig)
|
||||
* families of pairing-friendly curves.
|
||||
* Consists of two curves: G1 and G2:
|
||||
* - G1 is a subgroup of (x, y) E(Fq) over y² = x³ + 4.
|
||||
* - G2 is a subgroup of ((x₁, x₂+i), (y₁, y₂+i)) E(Fq²) over y² = x³ + 4(1 + i) where i is √-1
|
||||
* - Gt, created by bilinear (ate) pairing e(G1, G2), consists of p-th roots of unity in
|
||||
* Fq^k where k is embedding degree. Only degree 12 is currently supported, 24 is not.
|
||||
* Pairing is used to aggregate and verify signatures.
|
||||
* There are two modes of operation:
|
||||
* - Long signatures: X-byte keys + 2X-byte sigs (G1 keys + G2 sigs).
|
||||
* - Short signatures: 2X-byte keys + X-byte sigs (G2 keys + G1 sigs).
|
||||
* @module
|
||||
**/
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
import { type TArg, type TRet } from '../utils.ts';
|
||||
import { type CurveLengths } from './curve.ts';
|
||||
import { type H2CHasher, type H2COpts, type MapToCurve } from './hash-to-curve.ts';
|
||||
import { type IField } from './modular.ts';
|
||||
import type { Fp12, Fp12Bls, Fp2, Fp2Bls, Fp6Bls } from './tower.ts';
|
||||
import { type WeierstrassPoint, type WeierstrassPointCons } from './weierstrass.ts';
|
||||
type Fp = bigint;
|
||||
/**
|
||||
* Twist convention used by the pairing formulas for a concrete curve family.
|
||||
* BLS12-381 uses a multiplicative twist, while BN254 uses a divisive one.
|
||||
*/
|
||||
export type BlsTwistType = 'multiplicative' | 'divisive';
|
||||
/**
|
||||
* Codec exposed as `curve.shortSignatures.Signature`.
|
||||
* Use it to parse or serialize G1 signatures in short-signature mode.
|
||||
* In this mode, public keys live in G2.
|
||||
*/
|
||||
export type BlsShortSignatureCoder<Fp> = {
|
||||
/**
|
||||
* Parse a compressed signature from raw bytes.
|
||||
* @param bytes - Compressed signature bytes.
|
||||
* @returns Parsed signature point.
|
||||
*/
|
||||
fromBytes(bytes: TArg<Uint8Array>): WeierstrassPoint<Fp>;
|
||||
/**
|
||||
* Parse a compressed signature from a hex string.
|
||||
* @param hex - Compressed signature hex string.
|
||||
* @returns Parsed signature point.
|
||||
*/
|
||||
fromHex(hex: string): WeierstrassPoint<Fp>;
|
||||
/**
|
||||
* Encode a signature point into compressed bytes.
|
||||
* @param point - Signature point.
|
||||
* @returns Compressed signature bytes.
|
||||
*/
|
||||
toBytes(point: WeierstrassPoint<Fp>): TRet<Uint8Array>;
|
||||
/**
|
||||
* Encode a signature point into a hex string.
|
||||
* @param point - Signature point.
|
||||
* @returns Compressed signature hex.
|
||||
*/
|
||||
toHex(point: WeierstrassPoint<Fp>): string;
|
||||
};
|
||||
/**
|
||||
* Codec exposed as `curve.longSignatures.Signature`.
|
||||
* Use it to parse or serialize G2 signatures in long-signature mode.
|
||||
* In this mode, public keys live in G1.
|
||||
*/
|
||||
export type BlsLongSignatureCoder<Fp> = {
|
||||
/**
|
||||
* Parse a compressed signature from raw bytes.
|
||||
* @param bytes - Compressed signature bytes.
|
||||
* @returns Parsed signature point.
|
||||
*/
|
||||
fromBytes(bytes: TArg<Uint8Array>): WeierstrassPoint<Fp>;
|
||||
/**
|
||||
* Parse a compressed signature from a hex string.
|
||||
* @param hex - Compressed signature hex string.
|
||||
* @returns Parsed signature point.
|
||||
*/
|
||||
fromHex(hex: string): WeierstrassPoint<Fp>;
|
||||
/**
|
||||
* Encode a signature point into compressed bytes.
|
||||
* @param point - Signature point.
|
||||
* @returns Compressed signature bytes.
|
||||
*/
|
||||
toBytes(point: WeierstrassPoint<Fp>): TRet<Uint8Array>;
|
||||
/**
|
||||
* Encode a signature point into a hex string.
|
||||
* @param point - Signature point.
|
||||
* @returns Compressed signature hex.
|
||||
*/
|
||||
toHex(point: WeierstrassPoint<Fp>): string;
|
||||
};
|
||||
/** Tower fields needed by pairing code, hash-to-curve, and subgroup arithmetic. */
|
||||
export type BlsFields = {
|
||||
/** Base field of G1 coordinates. */
|
||||
Fp: IField<Fp>;
|
||||
/** Scalar field used for secret scalars and subgroup order arithmetic. */
|
||||
Fr: IField<bigint>;
|
||||
/** Quadratic extension field used by G2. */
|
||||
Fp2: Fp2Bls;
|
||||
/** Sextic extension field used inside pairing arithmetic. */
|
||||
Fp6: Fp6Bls;
|
||||
/** Degree-12 extension field that contains the GT target group. */
|
||||
Fp12: Fp12Bls;
|
||||
};
|
||||
/**
|
||||
* Callback used by pairing post-processing hooks to add one more G2 point to the Miller-loop state.
|
||||
* @param Rx - Current projective X coordinate.
|
||||
* @param Ry - Current projective Y coordinate.
|
||||
* @param Rz - Current projective Z coordinate.
|
||||
* @param Qx - G2 affine x coordinate.
|
||||
* @param Qy - G2 affine y coordinate.
|
||||
* @returns Updated projective accumulator coordinates.
|
||||
*/
|
||||
export type BlsPostPrecomputePointAddFn = (Rx: Fp2, Ry: Fp2, Rz: Fp2, Qx: Fp2, Qy: Fp2) => {
|
||||
Rx: Fp2;
|
||||
Ry: Fp2;
|
||||
Rz: Fp2;
|
||||
};
|
||||
/**
|
||||
* Hook for curve-specific pairing cleanup after the Miller loop precomputes are built.
|
||||
* @param Rx - Current projective X coordinate.
|
||||
* @param Ry - Current projective Y coordinate.
|
||||
* @param Rz - Current projective Z coordinate.
|
||||
* @param Qx - G2 affine x coordinate.
|
||||
* @param Qy - G2 affine y coordinate.
|
||||
* @param pointAdd - Callback used to fold one more point into the accumulator.
|
||||
*/
|
||||
export type BlsPostPrecomputeFn = (Rx: Fp2, Ry: Fp2, Rz: Fp2, Qx: Fp2, Qy: Fp2, pointAdd: BlsPostPrecomputePointAddFn) => void;
|
||||
/** Low-level pairing helpers shared by BLS curve bundles. */
|
||||
export type BlsPairing = {
|
||||
/** Byte lengths for keys and signatures exposed by this pairing family. */
|
||||
lengths: CurveLengths;
|
||||
/** Scalar field used by the pairing and signing helpers. */
|
||||
Fr: IField<bigint>;
|
||||
/** Target field used for the GT result of pairings. */
|
||||
Fp12: Fp12Bls;
|
||||
/**
|
||||
* Build Miller-loop precomputes for one G2 point.
|
||||
* @param p - G2 point to precompute.
|
||||
* @returns Pairing precompute table.
|
||||
*/
|
||||
calcPairingPrecomputes: (p: WeierstrassPoint<Fp2>) => Precompute;
|
||||
/**
|
||||
* Evaluate a batch of Miller loops from precomputed line coefficients.
|
||||
* @param pairs - Precomputed Miller-loop inputs.
|
||||
* @returns Accumulated GT value before or after final exponentiation.
|
||||
*/
|
||||
millerLoopBatch: (pairs: [Precompute, Fp, Fp][]) => Fp12;
|
||||
/**
|
||||
* Pair one G1 point with one G2 point.
|
||||
* @param P - G1 point.
|
||||
* @param Q - G2 point.
|
||||
* @param withFinalExponent - Whether to apply the final exponentiation step.
|
||||
* @returns GT pairing result.
|
||||
* @throws If either point is the point at infinity. {@link Error}
|
||||
*/
|
||||
pairing: (P: WeierstrassPoint<Fp>, Q: WeierstrassPoint<Fp2>, withFinalExponent?: boolean) => Fp12;
|
||||
/**
|
||||
* Pair many G1/G2 pairs in one batch.
|
||||
* @param pairs - Point pairs to accumulate.
|
||||
* @param withFinalExponent - Whether to apply the final exponentiation step.
|
||||
* @returns GT pairing result. Empty input returns the multiplicative identity in GT.
|
||||
*/
|
||||
pairingBatch: (pairs: {
|
||||
g1: WeierstrassPoint<Fp>;
|
||||
g2: WeierstrassPoint<Fp2>;
|
||||
}[], withFinalExponent?: boolean) => Fp12;
|
||||
/**
|
||||
* Generate a random secret key for this pairing family.
|
||||
* @param seed - Optional seed material.
|
||||
* @returns Secret key bytes.
|
||||
*/
|
||||
randomSecretKey: (seed?: TArg<Uint8Array>) => TRet<Uint8Array>;
|
||||
};
|
||||
/**
|
||||
* Parameters that define the Miller-loop shape and twist handling
|
||||
* for a concrete pairing family.
|
||||
*/
|
||||
export type BlsPairingParams = {
|
||||
/** Signed loop parameter used by the Miller loop. */
|
||||
ateLoopSize: bigint;
|
||||
/** Whether the signed Miller-loop parameter is negative. */
|
||||
xNegative: boolean;
|
||||
/**
|
||||
* Twist convention used by the pairing formulas.
|
||||
* BLS12-381 is multiplicative; BN254 is divisive.
|
||||
*/
|
||||
twistType: BlsTwistType;
|
||||
/**
|
||||
* Optional RNG override used by helper constructors.
|
||||
* Receives the requested byte length and returns random bytes.
|
||||
*/
|
||||
randomBytes?: (len?: number) => TRet<Uint8Array>;
|
||||
/**
|
||||
* Optional hook for curve-specific untwisting after precomputation.
|
||||
* Used by BN254 after the Miller loop.
|
||||
*/
|
||||
postPrecompute?: BlsPostPrecomputeFn;
|
||||
};
|
||||
/** Hash-to-curve settings shared by the G1 and G2 hashers inside a BLS curve bundle. */
|
||||
export type BlsHasherParams = {
|
||||
/**
|
||||
* Optional map-to-curve override for G1.
|
||||
* Receives the hash-to-field tuple and returns one affine G1 point.
|
||||
*/
|
||||
mapToG1?: MapToCurve<Fp>;
|
||||
/**
|
||||
* Optional map-to-curve override for G2.
|
||||
* Receives the hash-to-field tuple and returns one affine G2 point.
|
||||
*/
|
||||
mapToG2?: MapToCurve<Fp2>;
|
||||
/** Shared baseline hash-to-curve options. */
|
||||
hasherOpts: H2COpts;
|
||||
/** G1-specific hash-to-curve options merged on top of `hasherOpts`. */
|
||||
hasherOptsG1: H2COpts;
|
||||
/** G2-specific hash-to-curve options merged on top of `hasherOpts`. */
|
||||
hasherOptsG2: H2COpts;
|
||||
};
|
||||
type PrecomputeSingle = [Fp2, Fp2, Fp2][];
|
||||
type Precompute = PrecomputeSingle[];
|
||||
/**
|
||||
* BLS consists of two curves: G1 and G2:
|
||||
* - G1 is a subgroup of (x, y) E(Fq) over y² = x³ + 4.
|
||||
* - G2 is a subgroup of ((x₁, x₂+i), (y₁, y₂+i)) E(Fq²) over y² = x³ + 4(1 + i) where i is √-1
|
||||
*/
|
||||
export interface BlsCurvePair {
|
||||
/** Byte lengths for keys and signatures exposed by this curve family. */
|
||||
lengths: CurveLengths;
|
||||
/**
|
||||
* Shared Miller-loop batch evaluator.
|
||||
* @param pairs - Precomputed Miller-loop inputs.
|
||||
* @returns Accumulated GT value.
|
||||
*/
|
||||
millerLoopBatch: BlsPairing['millerLoopBatch'];
|
||||
/**
|
||||
* Pair one G1 point with one G2 point.
|
||||
* @param P - G1 point.
|
||||
* @param Q - G2 point.
|
||||
* @param withFinalExponent - Whether to apply the final exponentiation step.
|
||||
* @returns GT pairing result.
|
||||
* @throws If either point is the point at infinity. {@link Error}
|
||||
*/
|
||||
pairing: BlsPairing['pairing'];
|
||||
/**
|
||||
* Pair many G1/G2 pairs in one batch.
|
||||
* @param pairs - Point pairs to accumulate.
|
||||
* @param withFinalExponent - Whether to apply the final exponentiation step.
|
||||
* @returns GT pairing result. Empty input returns the multiplicative identity in GT.
|
||||
*/
|
||||
pairingBatch: BlsPairing['pairingBatch'];
|
||||
/** G1 point constructor for the base field subgroup. */
|
||||
G1: {
|
||||
Point: WeierstrassPointCons<Fp>;
|
||||
};
|
||||
/** G2 point constructor for the twist subgroup. */
|
||||
G2: {
|
||||
Point: WeierstrassPointCons<Fp2>;
|
||||
};
|
||||
/** Tower fields exposed by the pairing implementation. */
|
||||
fields: {
|
||||
Fp: IField<Fp>;
|
||||
Fp2: Fp2Bls;
|
||||
Fp6: Fp6Bls;
|
||||
Fp12: Fp12Bls;
|
||||
Fr: IField<bigint>;
|
||||
};
|
||||
/** Utility helpers shared by hashers and signers. */
|
||||
utils: {
|
||||
randomSecretKey: (seed?: TArg<Uint8Array>) => TRet<Uint8Array>;
|
||||
calcPairingPrecomputes: BlsPairing['calcPairingPrecomputes'];
|
||||
};
|
||||
/** Public pairing parameters exposed for introspection. */
|
||||
params: {
|
||||
ateLoopSize: bigint;
|
||||
twistType: BlsTwistType;
|
||||
};
|
||||
}
|
||||
/** BLS curve bundle extended with hash-to-curve helpers for G1 and G2. */
|
||||
export interface BlsCurvePairWithHashers extends BlsCurvePair {
|
||||
/** G1 hasher bundle with RFC 9380 helpers. */
|
||||
G1: H2CHasher<WeierstrassPointCons<Fp>>;
|
||||
/** G2 hasher bundle with RFC 9380 helpers. */
|
||||
G2: H2CHasher<WeierstrassPointCons<Fp2>>;
|
||||
}
|
||||
/** BLS curve bundle extended with both hashers and signature helpers. */
|
||||
export interface BlsCurvePairWithSignatures extends BlsCurvePairWithHashers {
|
||||
/** Long-signature mode: G1 public keys and G2 signatures. */
|
||||
longSignatures: BlsSigs<bigint, Fp2>;
|
||||
/** Short-signature mode: G2 public keys and G1 signatures. */
|
||||
shortSignatures: BlsSigs<Fp2, bigint>;
|
||||
}
|
||||
type BLSInput = TArg<Uint8Array>;
|
||||
/** BLS signer helpers for one signature mode. */
|
||||
export interface BlsSigs<P, S> {
|
||||
/** Byte lengths for secret keys, public keys, and signatures. */
|
||||
lengths: CurveLengths;
|
||||
/**
|
||||
* Generate a secret/public key pair for this signature mode.
|
||||
* @param seed - Optional seed material.
|
||||
* @returns Secret and public key pair.
|
||||
*/
|
||||
keygen(seed?: TArg<Uint8Array>): {
|
||||
secretKey: TRet<Uint8Array>;
|
||||
publicKey: WeierstrassPoint<P>;
|
||||
};
|
||||
/**
|
||||
* Derive the public key from a secret key.
|
||||
* @param secretKey - Secret key bytes.
|
||||
* @returns Public-key point.
|
||||
*/
|
||||
getPublicKey(secretKey: TArg<Uint8Array>): WeierstrassPoint<P>;
|
||||
/**
|
||||
* Sign a message already hashed onto the signature subgroup.
|
||||
* @param hashedMessage - Message mapped to the signature subgroup.
|
||||
* @param secretKey - Secret key bytes.
|
||||
* @returns Signature point.
|
||||
*/
|
||||
sign(hashedMessage: WeierstrassPoint<S>, secretKey: TArg<Uint8Array>): WeierstrassPoint<S>;
|
||||
/**
|
||||
* Verify one signature against one public key and hashed message.
|
||||
* @param signature - Signature point or encoded signature.
|
||||
* @param message - Hashed message point.
|
||||
* @param publicKey - Public-key point or encoded key.
|
||||
* @returns Whether the signature is valid.
|
||||
*/
|
||||
verify(signature: WeierstrassPoint<S> | BLSInput, message: WeierstrassPoint<S>, publicKey: WeierstrassPoint<P> | BLSInput): boolean;
|
||||
/**
|
||||
* Verify one aggregated signature against many `(message, publicKey)` pairs.
|
||||
* @param signature - Aggregated signature.
|
||||
* @param items - Message/public-key pairs.
|
||||
* @returns Whether the aggregated signature is valid. Same-message aggregate verification still
|
||||
* requires proof of possession or another rogue-key defense from the caller.
|
||||
*/
|
||||
verifyBatch: (signature: WeierstrassPoint<S> | BLSInput, items: {
|
||||
message: WeierstrassPoint<S>;
|
||||
publicKey: WeierstrassPoint<P> | BLSInput;
|
||||
}[]) => boolean;
|
||||
/**
|
||||
* Add many public keys into one aggregate point.
|
||||
* @param publicKeys - Public keys to aggregate.
|
||||
* @returns Aggregated public-key point. This is raw point addition and does not add proof of
|
||||
* possession or rogue-key protection on its own.
|
||||
*/
|
||||
aggregatePublicKeys(publicKeys: (WeierstrassPoint<P> | BLSInput)[]): WeierstrassPoint<P>;
|
||||
/**
|
||||
* Add many signatures into one aggregate point.
|
||||
* @param signatures - Signatures to aggregate.
|
||||
* @returns Aggregated signature point. This is raw point addition and does not change the proof
|
||||
* of possession requirements of the aggregate-verification scheme.
|
||||
*/
|
||||
aggregateSignatures(signatures: (WeierstrassPoint<S> | BLSInput)[]): WeierstrassPoint<S>;
|
||||
/**
|
||||
* Hash an arbitrary message onto the signature subgroup.
|
||||
* @param message - Message bytes.
|
||||
* @param DST - Optional domain separation tag.
|
||||
* @returns Curve point on the signature subgroup.
|
||||
*/
|
||||
hash(message: TArg<Uint8Array>, DST?: TArg<string | Uint8Array>): WeierstrassPoint<S>;
|
||||
/** Signature codec for this mode. */
|
||||
Signature: BlsLongSignatureCoder<S>;
|
||||
}
|
||||
type BlsSignatureCoders = Partial<{
|
||||
LongSignature: BlsLongSignatureCoder<Fp2>;
|
||||
ShortSignature: BlsShortSignatureCoder<Fp>;
|
||||
}>;
|
||||
/**
|
||||
* @param fields - Tower field implementations.
|
||||
* @param G1_Point - G1 point constructor.
|
||||
* @param G2_Point - G2 point constructor.
|
||||
* @param params - Pairing parameters. See {@link BlsPairingParams}.
|
||||
* @returns Pairing-only BLS helpers. The returned pairing surface rejects infinity inputs, while
|
||||
* empty `pairingBatch(...)` calls return the multiplicative identity in GT. This keeps the
|
||||
* low-level pairing API fail-closed for BLS-style callers, where identity points usually signal
|
||||
* broken hash / wiring instead of an intentionally neutral pairing term. This also eagerly
|
||||
* precomputes the G1 base-point table as a performance side effect.
|
||||
* @throws If the pairing parameters or underlying curve helpers are inconsistent. {@link Error}
|
||||
* @example
|
||||
* ```ts
|
||||
* import { blsBasic } from '@noble/curves/abstract/bls.js';
|
||||
* import { bn254 } from '@noble/curves/bn254.js';
|
||||
* // Pair a G1 point with a G2 point without the higher-level signer helpers.
|
||||
* const gt = bn254.pairing(bn254.G1.Point.BASE, bn254.G2.Point.BASE);
|
||||
* ```
|
||||
*/
|
||||
export declare function blsBasic(fields: TArg<BlsFields>, G1_Point: WeierstrassPointCons<Fp>, G2_Point: WeierstrassPointCons<Fp2>, params: TArg<BlsPairingParams>): BlsCurvePair;
|
||||
/**
|
||||
* @param fields - Tower field implementations.
|
||||
* @param G1_Point - G1 point constructor.
|
||||
* @param G2_Point - G2 point constructor.
|
||||
* @param params - Pairing parameters. See {@link BlsPairingParams}.
|
||||
* @param hasherParams - Hash-to-curve configuration. See {@link BlsHasherParams}.
|
||||
* @param signatureCoders - Signature codecs.
|
||||
* @returns BLS helpers with signers. The inherited pairing surface still rejects infinity inputs,
|
||||
* and empty `pairingBatch(...)` calls still return the multiplicative identity in GT. Aggregate
|
||||
* verification still requires proof of possession or another rogue-key defense from the caller.
|
||||
* @throws If the pairing, hashing, or signature helpers are configured inconsistently. {@link Error}
|
||||
* @example
|
||||
* ```ts
|
||||
* import { bls } from '@noble/curves/abstract/bls.js';
|
||||
* import { bls12_381 } from '@noble/curves/bls12-381.js';
|
||||
* const sigs = bls12_381.longSignatures;
|
||||
* // Use the full BLS helper set when you need hashing, keygen, signing, and verification.
|
||||
* const { secretKey, publicKey } = sigs.keygen();
|
||||
* const msg = sigs.hash(new TextEncoder().encode('hello noble'));
|
||||
* const sig = sigs.sign(msg, secretKey);
|
||||
* const isValid = sigs.verify(sig, msg, publicKey);
|
||||
* ```
|
||||
*/
|
||||
export declare function bls(fields: TArg<BlsFields>, G1_Point: WeierstrassPointCons<Fp>, G2_Point: WeierstrassPointCons<Fp2>, params: TArg<BlsPairingParams>, hasherParams: TArg<BlsHasherParams>, signatureCoders: BlsSignatureCoders): BlsCurvePairWithSignatures;
|
||||
export {};
|
||||
//# sourceMappingURL=bls.d.ts.map
|
||||
1
node_modules/@noble/curves/abstract/bls.d.ts.map
generated
vendored
Normal file
1
node_modules/@noble/curves/abstract/bls.d.ts.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
432
node_modules/@noble/curves/abstract/bls.js
generated
vendored
Normal file
432
node_modules/@noble/curves/abstract/bls.js
generated
vendored
Normal file
@@ -0,0 +1,432 @@
|
||||
/**
|
||||
* BLS != BLS.
|
||||
* The file implements BLS (Boneh-Lynn-Shacham) signatures.
|
||||
* Used in both BLS (Barreto-Lynn-Scott) and BN (Barreto-Naehrig)
|
||||
* families of pairing-friendly curves.
|
||||
* Consists of two curves: G1 and G2:
|
||||
* - G1 is a subgroup of (x, y) E(Fq) over y² = x³ + 4.
|
||||
* - G2 is a subgroup of ((x₁, x₂+i), (y₁, y₂+i)) E(Fq²) over y² = x³ + 4(1 + i) where i is √-1
|
||||
* - Gt, created by bilinear (ate) pairing e(G1, G2), consists of p-th roots of unity in
|
||||
* Fq^k where k is embedding degree. Only degree 12 is currently supported, 24 is not.
|
||||
* Pairing is used to aggregate and verify signatures.
|
||||
* There are two modes of operation:
|
||||
* - Long signatures: X-byte keys + 2X-byte sigs (G1 keys + G2 sigs).
|
||||
* - Short signatures: 2X-byte keys + X-byte sigs (G2 keys + G1 sigs).
|
||||
* @module
|
||||
**/
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
import { abytes, notImplemented, randomBytes } from "../utils.js";
|
||||
import {} from "./curve.js";
|
||||
import { createHasher, } from "./hash-to-curve.js";
|
||||
import { getMinHashLength, mapHashToField } from "./modular.js";
|
||||
import {} from "./weierstrass.js";
|
||||
// prettier-ignore
|
||||
const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);
|
||||
// Signed non-adjacent decomposition of the spec-defined Miller-loop parameter.
|
||||
// BN254 benefits most because `6x+2` has multiple adjacent `11` runs, but BLS12-381's
|
||||
// stored `|x|` still starts with `11`, so the Miller loop must also handle one `-1` digit there.
|
||||
function NAfDecomposition(a) {
|
||||
const res = [];
|
||||
// a>1 because of marker bit
|
||||
for (; a > _1n; a >>= _1n) {
|
||||
if ((a & _1n) === _0n)
|
||||
res.unshift(0);
|
||||
else if ((a & _3n) === _3n) {
|
||||
res.unshift(-1);
|
||||
a += _1n;
|
||||
}
|
||||
else
|
||||
res.unshift(1);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
function aNonEmpty(arr) {
|
||||
// Aggregate helpers use this to reject empty variable-length inputs consistently.
|
||||
// Without the guard, each caller would fall through into a different empty-input / identity
|
||||
// case and hide missing inputs behind outputs that still look structurally valid.
|
||||
if (!Array.isArray(arr) || arr.length === 0)
|
||||
throw new Error('expected non-empty array');
|
||||
}
|
||||
// This should be enough for bn254, no need to export full stuff?
|
||||
function createBlsPairing(fields, G1, G2, params) {
|
||||
const { Fr, Fp2, Fp12 } = fields;
|
||||
const { twistType, ateLoopSize, xNegative, postPrecompute } = params;
|
||||
// Applies sparse multiplication as line function
|
||||
let lineFunction;
|
||||
if (twistType === 'multiplicative') {
|
||||
lineFunction = (c0, c1, c2, f, Px, Py) => Fp12.mul014(f, c0, Fp2.mul(c1, Px), Fp2.mul(c2, Py));
|
||||
}
|
||||
else if (twistType === 'divisive') {
|
||||
// NOTE: it should be [c0, c1, c2], but we use different order here to reduce complexity of
|
||||
// precompute calculations.
|
||||
lineFunction = (c0, c1, c2, f, Px, Py) => Fp12.mul034(f, Fp2.mul(c2, Py), Fp2.mul(c1, Px), c0);
|
||||
}
|
||||
else
|
||||
throw new Error('bls: unknown twist type');
|
||||
const Fp2div2 = Fp2.div(Fp2.ONE, Fp2.mul(Fp2.ONE, _2n));
|
||||
function pointDouble(ell, Rx, Ry, Rz) {
|
||||
const t0 = Fp2.sqr(Ry); // Ry²
|
||||
const t1 = Fp2.sqr(Rz); // Rz²
|
||||
const t2 = Fp2.mulByB(Fp2.mul(t1, _3n)); // 3 * T1 * B
|
||||
const t3 = Fp2.mul(t2, _3n); // 3 * T2
|
||||
const t4 = Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(Ry, Rz)), t1), t0); // (Ry + Rz)² - T1 - T0
|
||||
const c0 = Fp2.sub(t2, t0); // T2 - T0 (i)
|
||||
const c1 = Fp2.mul(Fp2.sqr(Rx), _3n); // 3 * Rx²
|
||||
const c2 = Fp2.neg(t4); // -T4 (-h)
|
||||
ell.push([c0, c1, c2]);
|
||||
Rx = Fp2.mul(Fp2.mul(Fp2.mul(Fp2.sub(t0, t3), Rx), Ry), Fp2div2); // ((T0 - T3) * Rx * Ry) / 2
|
||||
// ((T0 + T3) / 2)² - 3 * T2²
|
||||
Ry = Fp2.sub(Fp2.sqr(Fp2.mul(Fp2.add(t0, t3), Fp2div2)), Fp2.mul(Fp2.sqr(t2), _3n));
|
||||
Rz = Fp2.mul(t0, t4); // T0 * T4
|
||||
return { Rx, Ry, Rz };
|
||||
}
|
||||
function pointAdd(ell, Rx, Ry, Rz, Qx, Qy) {
|
||||
// Addition
|
||||
const t0 = Fp2.sub(Ry, Fp2.mul(Qy, Rz)); // Ry - Qy * Rz
|
||||
const t1 = Fp2.sub(Rx, Fp2.mul(Qx, Rz)); // Rx - Qx * Rz
|
||||
const c0 = Fp2.sub(Fp2.mul(t0, Qx), Fp2.mul(t1, Qy)); // T0 * Qx - T1 * Qy == Ry * Qx - Rx * Qy
|
||||
const c1 = Fp2.neg(t0); // -T0 == Qy * Rz - Ry
|
||||
const c2 = t1; // == Rx - Qx * Rz
|
||||
ell.push([c0, c1, c2]);
|
||||
const t2 = Fp2.sqr(t1); // T1²
|
||||
const t3 = Fp2.mul(t2, t1); // T2 * T1
|
||||
const t4 = Fp2.mul(t2, Rx); // T2 * Rx
|
||||
// T3 - 2 * T4 + T0² * Rz
|
||||
const t5 = Fp2.add(Fp2.sub(t3, Fp2.mul(t4, _2n)), Fp2.mul(Fp2.sqr(t0), Rz));
|
||||
Rx = Fp2.mul(t1, t5); // T1 * T5
|
||||
Ry = Fp2.sub(Fp2.mul(Fp2.sub(t4, t5), t0), Fp2.mul(t3, Ry)); // (T4 - T5) * T0 - T3 * Ry
|
||||
Rz = Fp2.mul(Rz, t3); // Rz * T3
|
||||
return { Rx, Ry, Rz };
|
||||
}
|
||||
// Pre-compute coefficients for sparse multiplication
|
||||
// Point addition and point double calculations is reused for coefficients
|
||||
// pointAdd happens only if bit set, so wNAF is reasonable. Unfortunately we cannot combine
|
||||
// add + double in windowed precomputes here, otherwise it would be single op (since X is static)
|
||||
const ATE_NAF = NAfDecomposition(ateLoopSize);
|
||||
const calcPairingPrecomputes = (point) => {
|
||||
const p = point;
|
||||
const { x, y } = p.toAffine();
|
||||
// prettier-ignore
|
||||
const Qx = x, Qy = y, negQy = Fp2.neg(y);
|
||||
// prettier-ignore
|
||||
let Rx = Qx, Ry = Qy, Rz = Fp2.ONE;
|
||||
const ell = [];
|
||||
for (const bit of ATE_NAF) {
|
||||
const cur = [];
|
||||
({ Rx, Ry, Rz } = pointDouble(cur, Rx, Ry, Rz));
|
||||
if (bit)
|
||||
({ Rx, Ry, Rz } = pointAdd(cur, Rx, Ry, Rz, Qx, bit === -1 ? negQy : Qy));
|
||||
ell.push(cur);
|
||||
}
|
||||
if (postPrecompute) {
|
||||
const last = ell[ell.length - 1];
|
||||
postPrecompute(Rx, Ry, Rz, Qx, Qy, pointAdd.bind(null, last));
|
||||
}
|
||||
return ell;
|
||||
};
|
||||
function millerLoopBatch(pairs, withFinalExponent = false) {
|
||||
let f12 = Fp12.ONE;
|
||||
if (pairs.length) {
|
||||
const ellLen = pairs[0][0].length;
|
||||
for (let i = 0; i < ellLen; i++) {
|
||||
f12 = Fp12.sqr(f12); // This allows us to do sqr only one time for all pairings
|
||||
// NOTE: we apply multiple pairings in parallel here
|
||||
for (const [ell, Px, Py] of pairs) {
|
||||
for (const [c0, c1, c2] of ell[i])
|
||||
f12 = lineFunction(c0, c1, c2, f12, Px, Py);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (xNegative)
|
||||
f12 = Fp12.conjugate(f12);
|
||||
return withFinalExponent ? Fp12.finalExponentiate(f12) : f12;
|
||||
}
|
||||
// Calculates product of multiple pairings
|
||||
// This up to x2 faster than just `map(({g1, g2})=>pairing({g1,g2}))`
|
||||
function pairingBatch(pairs, withFinalExponent = true) {
|
||||
const res = [];
|
||||
for (const { g1, g2 } of pairs) {
|
||||
// Mathematically, a zero pairing term contributes GT.ONE. We still reject it here because
|
||||
// this API mainly backs BLS verification, where ZERO inputs usually mean broken hash /
|
||||
// wiring. Silently skipping them would turn those failures into a neutral pairing product.
|
||||
// Callers that want the algebraic neutral-element behavior can filter ZERO terms first.
|
||||
if (g1.is0() || g2.is0())
|
||||
throw new Error('pairing is not available for ZERO point');
|
||||
// This uses toAffine inside
|
||||
g1.assertValidity();
|
||||
g2.assertValidity();
|
||||
const Qa = g1.toAffine();
|
||||
res.push([calcPairingPrecomputes(g2), Qa.x, Qa.y]);
|
||||
}
|
||||
return millerLoopBatch(res, withFinalExponent);
|
||||
}
|
||||
// Calculates bilinear pairing
|
||||
function pairing(Q, P, withFinalExponent = true) {
|
||||
return pairingBatch([{ g1: Q, g2: P }], withFinalExponent);
|
||||
}
|
||||
const lengths = {
|
||||
seed: getMinHashLength(Fr.ORDER),
|
||||
};
|
||||
const rand = params.randomBytes === undefined ? randomBytes : params.randomBytes;
|
||||
// Seeded calls deterministically reduce exactly `lengths.seed` bytes into `1..Fr.ORDER-1`;
|
||||
// omitting `seed` just fills that input buffer from the configured RNG first.
|
||||
const randomSecretKey = (seed) => {
|
||||
seed = seed === undefined ? rand(lengths.seed) : seed;
|
||||
abytes(seed, lengths.seed, 'seed');
|
||||
return mapHashToField(seed, Fr.ORDER);
|
||||
};
|
||||
Object.freeze(lengths);
|
||||
return {
|
||||
lengths,
|
||||
Fr,
|
||||
Fp12, // NOTE: we re-export Fp12 here because pairing results are Fp12!
|
||||
millerLoopBatch,
|
||||
pairing,
|
||||
pairingBatch,
|
||||
calcPairingPrecomputes,
|
||||
randomSecretKey,
|
||||
};
|
||||
}
|
||||
function createBlsSig(blsPairing, PubPoint, SigPoint, isSigG1, hashToSigCurve, SignatureCoder) {
|
||||
const { Fr, Fp12, pairingBatch, randomSecretKey, lengths } = blsPairing;
|
||||
if (!SignatureCoder) {
|
||||
SignatureCoder = {
|
||||
fromBytes: notImplemented,
|
||||
fromHex: notImplemented,
|
||||
toBytes: notImplemented,
|
||||
toHex: notImplemented,
|
||||
};
|
||||
}
|
||||
function normPub(point) {
|
||||
return point instanceof PubPoint ? point : PubPoint.fromBytes(point);
|
||||
}
|
||||
function normSig(point) {
|
||||
return point instanceof SigPoint ? point : SigPoint.fromBytes(point);
|
||||
}
|
||||
// Sign/verify here take points already hashed onto the signature subgroup.
|
||||
// Raw bytes and points from the other subgroup must fail this constructor-brand
|
||||
// check before later validity checks run.
|
||||
function amsg(m) {
|
||||
if (!(m instanceof SigPoint))
|
||||
throw new Error(`expected valid message hashed to ${!isSigG1 ? 'G2' : 'G1'} curve`);
|
||||
return m;
|
||||
}
|
||||
// What matters here is what point pairing API accepts as G1 or G2, not actual size or names
|
||||
const pair = !isSigG1
|
||||
? (a, b) => ({ g1: a, g2: b })
|
||||
: (a, b) => ({ g1: b, g2: a });
|
||||
return Object.freeze({
|
||||
lengths: Object.freeze({ ...lengths, secretKey: Fr.BYTES }),
|
||||
keygen(seed) {
|
||||
const secretKey = randomSecretKey(seed);
|
||||
const publicKey = this.getPublicKey(secretKey);
|
||||
return { secretKey, publicKey };
|
||||
},
|
||||
// P = pk x G
|
||||
getPublicKey(secretKey) {
|
||||
let sec;
|
||||
try {
|
||||
sec = PubPoint.Fn.fromBytes(secretKey);
|
||||
}
|
||||
catch (error) {
|
||||
// @ts-ignore
|
||||
throw new Error('invalid private key: ' + typeof secretKey, { cause: error });
|
||||
}
|
||||
return PubPoint.BASE.multiply(sec);
|
||||
},
|
||||
// S = pk x H(m)
|
||||
sign(message, secretKey, unusedArg) {
|
||||
if (unusedArg != null)
|
||||
throw new Error('sign() expects 2 arguments');
|
||||
const sec = PubPoint.Fn.fromBytes(secretKey);
|
||||
amsg(message).assertValidity();
|
||||
return message.multiply(sec);
|
||||
},
|
||||
// Checks if pairing of public key & hash is equal to pairing of generator & signature.
|
||||
// e(P, H(m)) == e(G, S)
|
||||
// e(S, G) == e(H(m), P)
|
||||
verify(signature, message, publicKey, unusedArg) {
|
||||
if (unusedArg != null)
|
||||
throw new Error('verify() expects 3 arguments');
|
||||
signature = normSig(signature);
|
||||
publicKey = normPub(publicKey);
|
||||
const P = publicKey.negate();
|
||||
const G = PubPoint.BASE;
|
||||
const Hm = amsg(message);
|
||||
const S = signature;
|
||||
// This code was changed in 1.9.x:
|
||||
// Before it was G.negate() in G2, now it's always pubKey.negate
|
||||
// e(P, -Q)===e(-P, Q)==e(P, Q)^-1. Negate can be done anywhere (as long it is done once per pair).
|
||||
// We just moving sign, but since pairing is multiplicative, we doing X * X^-1 = 1
|
||||
try {
|
||||
const exp = pairingBatch([pair(P, Hm), pair(G, S)]);
|
||||
return Fp12.eql(exp, Fp12.ONE);
|
||||
}
|
||||
catch {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
// https://ethresear.ch/t/fast-verification-of-multiple-bls-signatures/5407
|
||||
// e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si))
|
||||
// TODO: maybe `{message: G2Hex, publicKey: G1Hex}[]` instead?
|
||||
verifyBatch(signature, items) {
|
||||
aNonEmpty(items);
|
||||
const sig = normSig(signature);
|
||||
const nMessages = items.map((i) => i.message);
|
||||
const nPublicKeys = items.map((i) => normPub(i.publicKey));
|
||||
// NOTE: this works only for exact same object
|
||||
const messagePubKeyMap = new Map();
|
||||
for (let i = 0; i < nPublicKeys.length; i++) {
|
||||
const pub = nPublicKeys[i];
|
||||
const msg = nMessages[i];
|
||||
let keys = messagePubKeyMap.get(msg);
|
||||
if (keys === undefined) {
|
||||
keys = [];
|
||||
messagePubKeyMap.set(msg, keys);
|
||||
}
|
||||
keys.push(pub);
|
||||
}
|
||||
const paired = [];
|
||||
const G = PubPoint.BASE;
|
||||
try {
|
||||
for (const [msg, keys] of messagePubKeyMap) {
|
||||
const groupPublicKey = keys.reduce((acc, msg) => acc.add(msg));
|
||||
paired.push(pair(groupPublicKey, msg));
|
||||
}
|
||||
paired.push(pair(G.negate(), sig));
|
||||
return Fp12.eql(pairingBatch(paired), Fp12.ONE);
|
||||
}
|
||||
catch {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
// Adds a bunch of public key points together.
|
||||
// pk1 + pk2 + pk3 = pkA
|
||||
aggregatePublicKeys(publicKeys) {
|
||||
aNonEmpty(publicKeys);
|
||||
publicKeys = publicKeys.map((pub) => normPub(pub));
|
||||
const agg = publicKeys.reduce((sum, p) => sum.add(p), PubPoint.ZERO);
|
||||
agg.assertValidity();
|
||||
return agg;
|
||||
},
|
||||
// Adds a bunch of signature points together.
|
||||
// pk1 + pk2 + pk3 = pkA
|
||||
aggregateSignatures(signatures) {
|
||||
aNonEmpty(signatures);
|
||||
signatures = signatures.map((sig) => normSig(sig));
|
||||
const agg = signatures.reduce((sum, s) => sum.add(s), SigPoint.ZERO);
|
||||
agg.assertValidity();
|
||||
return agg;
|
||||
},
|
||||
hash(messageBytes, DST) {
|
||||
abytes(messageBytes);
|
||||
const opts = DST ? { DST } : undefined;
|
||||
return hashToSigCurve(messageBytes, opts);
|
||||
},
|
||||
Signature: Object.freeze({ ...SignatureCoder }),
|
||||
}) /*satisfies Signer */;
|
||||
}
|
||||
// NOTE: separate function instead of function override, so we don't depend on hasher in bn254.
|
||||
/**
|
||||
* @param fields - Tower field implementations.
|
||||
* @param G1_Point - G1 point constructor.
|
||||
* @param G2_Point - G2 point constructor.
|
||||
* @param params - Pairing parameters. See {@link BlsPairingParams}.
|
||||
* @returns Pairing-only BLS helpers. The returned pairing surface rejects infinity inputs, while
|
||||
* empty `pairingBatch(...)` calls return the multiplicative identity in GT. This keeps the
|
||||
* low-level pairing API fail-closed for BLS-style callers, where identity points usually signal
|
||||
* broken hash / wiring instead of an intentionally neutral pairing term. This also eagerly
|
||||
* precomputes the G1 base-point table as a performance side effect.
|
||||
* @throws If the pairing parameters or underlying curve helpers are inconsistent. {@link Error}
|
||||
* @example
|
||||
* ```ts
|
||||
* import { blsBasic } from '@noble/curves/abstract/bls.js';
|
||||
* import { bn254 } from '@noble/curves/bn254.js';
|
||||
* // Pair a G1 point with a G2 point without the higher-level signer helpers.
|
||||
* const gt = bn254.pairing(bn254.G1.Point.BASE, bn254.G2.Point.BASE);
|
||||
* ```
|
||||
*/
|
||||
export function blsBasic(fields, G1_Point, G2_Point, params) {
|
||||
// Fields are specific for curve, so for now we'll need to pass them with opts
|
||||
const { Fp, Fr, Fp2, Fp6, Fp12 } = fields;
|
||||
// Point on G1 curve: (x, y)
|
||||
// const G1_Point = weierstrass(CURVE.G1, { Fn: Fr });
|
||||
const G1 = { Point: G1_Point };
|
||||
// Point on G2 curve (complex numbers): (x₁, x₂+i), (y₁, y₂+i)
|
||||
const G2 = { Point: G2_Point };
|
||||
const pairingRes = createBlsPairing(fields, G1_Point, G2_Point, params);
|
||||
const { millerLoopBatch, pairing, pairingBatch, calcPairingPrecomputes, randomSecretKey, lengths, } = pairingRes;
|
||||
G1.Point.BASE.precompute(4);
|
||||
Object.freeze(G1);
|
||||
Object.freeze(G2);
|
||||
return Object.freeze({
|
||||
lengths: Object.freeze(lengths),
|
||||
millerLoopBatch,
|
||||
pairing,
|
||||
pairingBatch,
|
||||
G1,
|
||||
G2,
|
||||
fields: Object.freeze({ Fr, Fp, Fp2, Fp6, Fp12 }),
|
||||
params: Object.freeze({
|
||||
ateLoopSize: params.ateLoopSize,
|
||||
twistType: params.twistType,
|
||||
}),
|
||||
utils: Object.freeze({
|
||||
randomSecretKey,
|
||||
calcPairingPrecomputes,
|
||||
}),
|
||||
});
|
||||
}
|
||||
// We can export this too, but seems there is not much reasons for now? If user wants hasher, they can just create hasher.
|
||||
function blsHashers(fields, G1_Point, G2_Point, params, hasherParams) {
|
||||
const base = blsBasic(fields, G1_Point, G2_Point, params);
|
||||
// Missing map hooks intentionally fail closed via notImplemented on first hash use.
|
||||
const G1Hasher = createHasher(G1_Point, hasherParams.mapToG1 === undefined ? notImplemented : hasherParams.mapToG1, {
|
||||
...hasherParams.hasherOpts,
|
||||
...hasherParams.hasherOptsG1,
|
||||
});
|
||||
const G2Hasher = createHasher(G2_Point, hasherParams.mapToG2 === undefined ? notImplemented : hasherParams.mapToG2, {
|
||||
...hasherParams.hasherOpts,
|
||||
...hasherParams.hasherOptsG2,
|
||||
});
|
||||
return Object.freeze({ ...base, G1: G1Hasher, G2: G2Hasher });
|
||||
}
|
||||
// G1_Point: ProjConstructor<bigint>, G2_Point: ProjConstructor<Fp2>,
|
||||
// Rename to blsSignatures?
|
||||
/**
|
||||
* @param fields - Tower field implementations.
|
||||
* @param G1_Point - G1 point constructor.
|
||||
* @param G2_Point - G2 point constructor.
|
||||
* @param params - Pairing parameters. See {@link BlsPairingParams}.
|
||||
* @param hasherParams - Hash-to-curve configuration. See {@link BlsHasherParams}.
|
||||
* @param signatureCoders - Signature codecs.
|
||||
* @returns BLS helpers with signers. The inherited pairing surface still rejects infinity inputs,
|
||||
* and empty `pairingBatch(...)` calls still return the multiplicative identity in GT. Aggregate
|
||||
* verification still requires proof of possession or another rogue-key defense from the caller.
|
||||
* @throws If the pairing, hashing, or signature helpers are configured inconsistently. {@link Error}
|
||||
* @example
|
||||
* ```ts
|
||||
* import { bls } from '@noble/curves/abstract/bls.js';
|
||||
* import { bls12_381 } from '@noble/curves/bls12-381.js';
|
||||
* const sigs = bls12_381.longSignatures;
|
||||
* // Use the full BLS helper set when you need hashing, keygen, signing, and verification.
|
||||
* const { secretKey, publicKey } = sigs.keygen();
|
||||
* const msg = sigs.hash(new TextEncoder().encode('hello noble'));
|
||||
* const sig = sigs.sign(msg, secretKey);
|
||||
* const isValid = sigs.verify(sig, msg, publicKey);
|
||||
* ```
|
||||
*/
|
||||
export function bls(fields, G1_Point, G2_Point, params, hasherParams, signatureCoders) {
|
||||
const base = blsHashers(fields, G1_Point, G2_Point, params, hasherParams);
|
||||
const pairingRes = {
|
||||
...base,
|
||||
Fr: base.fields.Fr,
|
||||
Fp12: base.fields.Fp12,
|
||||
calcPairingPrecomputes: base.utils.calcPairingPrecomputes,
|
||||
randomSecretKey: base.utils.randomSecretKey,
|
||||
};
|
||||
const longSignatures = createBlsSig(pairingRes, G1_Point, G2_Point, false, base.G2.hashToCurve, signatureCoders?.LongSignature);
|
||||
const shortSignatures = createBlsSig(pairingRes, G2_Point, G1_Point, true, base.G1.hashToCurve, signatureCoders?.ShortSignature);
|
||||
return Object.freeze({ ...base, longSignatures, shortSignatures });
|
||||
}
|
||||
//# sourceMappingURL=bls.js.map
|
||||
1
node_modules/@noble/curves/abstract/bls.js.map
generated
vendored
Normal file
1
node_modules/@noble/curves/abstract/bls.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
442
node_modules/@noble/curves/abstract/curve.d.ts
generated
vendored
Normal file
442
node_modules/@noble/curves/abstract/curve.d.ts
generated
vendored
Normal file
@@ -0,0 +1,442 @@
|
||||
/**
|
||||
* Methods for elliptic curve multiplication by scalars.
|
||||
* Contains wNAF, pippenger.
|
||||
* @module
|
||||
*/
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
import { type Signer, type TArg, type TRet } from '../utils.ts';
|
||||
import { type IField } from './modular.ts';
|
||||
/** Affine point coordinates without projective fields. */
|
||||
export type AffinePoint<T> = {
|
||||
/** Affine x coordinate. */
|
||||
x: T;
|
||||
/** Affine y coordinate. */
|
||||
y: T;
|
||||
} & {
|
||||
Z?: never;
|
||||
};
|
||||
/** Base interface for all elliptic-curve point instances. */
|
||||
export interface CurvePoint<F, P extends CurvePoint<F, P>> {
|
||||
/** Affine x coordinate. Different from projective / extended X coordinate. */
|
||||
x: F;
|
||||
/** Affine y coordinate. Different from projective / extended Y coordinate. */
|
||||
y: F;
|
||||
/** Projective Z coordinate when the point keeps projective state. */
|
||||
Z?: F;
|
||||
/**
|
||||
* Double the point.
|
||||
* @returns Doubled point.
|
||||
*/
|
||||
double(): P;
|
||||
/**
|
||||
* Negate the point.
|
||||
* @returns Negated point.
|
||||
*/
|
||||
negate(): P;
|
||||
/**
|
||||
* Add another point from the same curve.
|
||||
* @param other - Point to add.
|
||||
* @returns Sum point.
|
||||
*/
|
||||
add(other: P): P;
|
||||
/**
|
||||
* Subtract another point from the same curve.
|
||||
* @param other - Point to subtract.
|
||||
* @returns Difference point.
|
||||
*/
|
||||
subtract(other: P): P;
|
||||
/**
|
||||
* Compare two points for equality.
|
||||
* @param other - Point to compare.
|
||||
* @returns Whether the points are equal.
|
||||
*/
|
||||
equals(other: P): boolean;
|
||||
/**
|
||||
* Multiply the point by a scalar in constant time.
|
||||
* Implementations keep the subgroup-scalar contract strict and may reject
|
||||
* `0` instead of returning the identity point.
|
||||
* @param scalar - Scalar multiplier.
|
||||
* @returns Product point.
|
||||
*/
|
||||
multiply(scalar: bigint): P;
|
||||
/** Assert that the point satisfies the curve equation and subgroup checks. */
|
||||
assertValidity(): void;
|
||||
/**
|
||||
* Map the point into the prime-order subgroup when the curve requires it.
|
||||
* @returns Prime-order point.
|
||||
*/
|
||||
clearCofactor(): P;
|
||||
/**
|
||||
* Check whether the point is the point at infinity.
|
||||
* @returns Whether the point is zero.
|
||||
*/
|
||||
is0(): boolean;
|
||||
/**
|
||||
* Check whether the point belongs to the prime-order subgroup.
|
||||
* @returns Whether the point is torsion-free.
|
||||
*/
|
||||
isTorsionFree(): boolean;
|
||||
/**
|
||||
* Check whether the point lies in a small torsion subgroup.
|
||||
* @returns Whether the point has small order.
|
||||
*/
|
||||
isSmallOrder(): boolean;
|
||||
/**
|
||||
* Multiply the point by a scalar without constant-time guarantees.
|
||||
* Public-scalar callers that need `0` should use this method instead of
|
||||
* relying on `multiply(...)` to return the identity point.
|
||||
* @param scalar - Scalar multiplier.
|
||||
* @returns Product point.
|
||||
*/
|
||||
multiplyUnsafe(scalar: bigint): P;
|
||||
/**
|
||||
* Massively speeds up `p.multiply(n)` by using precompute tables (caching). See {@link wNAF}.
|
||||
* Cache state lives in internal WeakMaps keyed by point identity, not on the point object.
|
||||
* Repeating `precompute(...)` for the same point identity replaces the remembered window size
|
||||
* and forces table regeneration for that point.
|
||||
* @param windowSize - Precompute window size.
|
||||
* @param isLazy - calculate cache now. Default (true) ensures it's deferred to first `multiply()`
|
||||
* @returns Same point instance with precompute tables attached.
|
||||
*/
|
||||
precompute(windowSize?: number, isLazy?: boolean): P;
|
||||
/**
|
||||
* Converts point to 2D xy affine coordinates.
|
||||
* @param invertedZ - Optional inverted Z coordinate for batch normalization.
|
||||
* @returns Affine x/y coordinates.
|
||||
*/
|
||||
toAffine(invertedZ?: F): AffinePoint<F>;
|
||||
/**
|
||||
* Encode the point into the curve's canonical byte form.
|
||||
* @returns Encoded point bytes.
|
||||
*/
|
||||
toBytes(): Uint8Array;
|
||||
/**
|
||||
* Encode the point into the curve's canonical hex form.
|
||||
* @returns Encoded point hex.
|
||||
*/
|
||||
toHex(): string;
|
||||
}
|
||||
/** Base interface for elliptic-curve point constructors. */
|
||||
export interface CurvePointCons<P extends CurvePoint<any, P>> {
|
||||
/**
|
||||
* Runtime brand check for points created by this constructor.
|
||||
* @param item - Value to test.
|
||||
* @returns Whether the value is a point from this constructor.
|
||||
*/
|
||||
[Symbol.hasInstance]: (item: unknown) => boolean;
|
||||
/** Canonical subgroup generator. */
|
||||
BASE: P;
|
||||
/** Point at infinity. */
|
||||
ZERO: P;
|
||||
/** Field for basic curve math */
|
||||
Fp: IField<P_F<P>>;
|
||||
/** Scalar field, for scalars in multiply and others */
|
||||
Fn: IField<bigint>;
|
||||
/**
|
||||
* Create one point from affine coordinates.
|
||||
* Does NOT validate curve, subgroup, or wrapper invariants.
|
||||
* Use `.assertValidity()` on adversarial inputs.
|
||||
* @param p - Affine point coordinates.
|
||||
* @returns Point instance.
|
||||
*/
|
||||
fromAffine(p: AffinePoint<P_F<P>>): P;
|
||||
/**
|
||||
* Decode a point from the canonical byte encoding.
|
||||
* @param bytes - Encoded point bytes.
|
||||
* Implementations MUST treat `bytes` as read-only.
|
||||
* @returns Point instance.
|
||||
*/
|
||||
fromBytes(bytes: Uint8Array): P;
|
||||
/**
|
||||
* Decode a point from the canonical hex encoding.
|
||||
* @param hex - Encoded point hex.
|
||||
* @returns Point instance.
|
||||
*/
|
||||
fromHex(hex: string): P;
|
||||
}
|
||||
/** Returns the affine field type for a point instance (`P_F<P> == P.F`). */
|
||||
export type P_F<P extends CurvePoint<any, P>> = P extends CurvePoint<infer F, P> ? F : never;
|
||||
/** Returns the affine field type for a point constructor (`PC_F<PC> == PC.P.F`). */
|
||||
export type PC_F<PC extends CurvePointCons<CurvePoint<any, any>>> = PC['Fp']['ZERO'];
|
||||
/** Returns the point instance type for a point constructor (`PC_P<PC> == PC.P`). */
|
||||
export type PC_P<PC extends CurvePointCons<CurvePoint<any, any>>> = PC['ZERO'];
|
||||
/** Wide point-constructor type used when the concrete curve is not important. */
|
||||
export type PC_ANY = CurvePointCons<CurvePoint<any, CurvePoint<any, CurvePoint<any, CurvePoint<any, CurvePoint<any, CurvePoint<any, CurvePoint<any, CurvePoint<any, CurvePoint<any, CurvePoint<any, any>>>>>>>>>>>;
|
||||
/**
|
||||
* Validates the static surface of a point constructor.
|
||||
* This is only a cheap sanity check for the constructor hooks and fields consumed by generic
|
||||
* factories; it does not certify `BASE`/`ZERO` semantics or prove the curve implementation itself.
|
||||
* @param Point - Runtime point constructor.
|
||||
* @throws On missing constructor hooks or malformed field metadata. {@link TypeError}
|
||||
* @example
|
||||
* Check that one point constructor exposes the static hooks generic helpers need.
|
||||
*
|
||||
* ```ts
|
||||
* import { ed25519 } from '@noble/curves/ed25519.js';
|
||||
* import { validatePointCons } from '@noble/curves/abstract/curve.js';
|
||||
* validatePointCons(ed25519.Point);
|
||||
* ```
|
||||
*/
|
||||
export declare function validatePointCons<P extends CurvePoint<any, P>>(Point: CurvePointCons<P>): void;
|
||||
/** Byte lengths used by one curve implementation. */
|
||||
export interface CurveLengths {
|
||||
/** Secret-key length in bytes. */
|
||||
secretKey?: number;
|
||||
/** Compressed public-key length in bytes. */
|
||||
publicKey?: number;
|
||||
/** Uncompressed public-key length in bytes. */
|
||||
publicKeyUncompressed?: number;
|
||||
/** Whether public-key encodings include a format prefix byte. */
|
||||
publicKeyHasPrefix?: boolean;
|
||||
/** Signature length in bytes. */
|
||||
signature?: number;
|
||||
/** Seed length in bytes when the curve exposes deterministic keygen from seed. */
|
||||
seed?: number;
|
||||
}
|
||||
/** Reorders or otherwise remaps a batch while preserving its element type. */
|
||||
export type Mapper<T> = (i: T[]) => T[];
|
||||
/**
|
||||
* Computes both candidates first, but the final selection still branches on `condition`, so this
|
||||
* is not a strict constant-time CMOV primitive.
|
||||
* @param condition - Whether to negate the point.
|
||||
* @param item - Point-like value.
|
||||
* @returns Original or negated value.
|
||||
* @example
|
||||
* Keep the point or return its negation based on one boolean branch.
|
||||
*
|
||||
* ```ts
|
||||
* import { negateCt } from '@noble/curves/abstract/curve.js';
|
||||
* import { p256 } from '@noble/curves/nist.js';
|
||||
* const maybeNegated = negateCt(true, p256.Point.BASE);
|
||||
* ```
|
||||
*/
|
||||
export declare function negateCt<T extends {
|
||||
negate: () => T;
|
||||
}>(condition: boolean, item: T): T;
|
||||
/**
|
||||
* Takes a bunch of Projective Points but executes only one
|
||||
* inversion on all of them. Inversion is very slow operation,
|
||||
* so this improves performance massively.
|
||||
* Optimization: converts a list of projective points to a list of identical points with Z=1.
|
||||
* Input points are left unchanged; the normalized points are returned as fresh instances.
|
||||
* @param c - Point constructor.
|
||||
* @param points - Projective points.
|
||||
* @returns Fresh projective points reconstructed from normalized affine coordinates.
|
||||
* @example
|
||||
* Batch-normalize projective points with a single shared inversion.
|
||||
*
|
||||
* ```ts
|
||||
* import { normalizeZ } from '@noble/curves/abstract/curve.js';
|
||||
* import { p256 } from '@noble/curves/nist.js';
|
||||
* const points = normalizeZ(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()]);
|
||||
* ```
|
||||
*/
|
||||
export declare function normalizeZ<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(c: PC, points: P[]): P[];
|
||||
/**
|
||||
* Elliptic curve multiplication of Point by scalar. Fragile.
|
||||
* Table generation takes **30MB of ram and 10ms on high-end CPU**,
|
||||
* but may take much longer on slow devices. Actual generation will happen on
|
||||
* first call of `multiply()`. By default, `BASE` point is precomputed.
|
||||
*
|
||||
* Scalars should always be less than curve order: this should be checked inside of a curve itself.
|
||||
* Creates precomputation tables for fast multiplication:
|
||||
* - private scalar is split by fixed size windows of W bits
|
||||
* - every window point is collected from window's table & added to accumulator
|
||||
* - since windows are different, same point inside tables won't be accessed more than once per calc
|
||||
* - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
|
||||
* - +1 window is neccessary for wNAF
|
||||
* - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
|
||||
*
|
||||
* TODO: research returning a 2d JS array of windows instead of a single window.
|
||||
* This would allow windows to be in different memory locations.
|
||||
* @param Point - Point constructor.
|
||||
* @param bits - Scalar bit length.
|
||||
* @example
|
||||
* Elliptic curve multiplication of Point by scalar.
|
||||
*
|
||||
* ```ts
|
||||
* import { wNAF } from '@noble/curves/abstract/curve.js';
|
||||
* import { p256 } from '@noble/curves/nist.js';
|
||||
* const ladder = new wNAF(p256.Point, p256.Point.Fn.BITS);
|
||||
* ```
|
||||
*/
|
||||
export declare class wNAF<PC extends PC_ANY> {
|
||||
private readonly BASE;
|
||||
private readonly ZERO;
|
||||
private readonly Fn;
|
||||
readonly bits: number;
|
||||
constructor(Point: PC, bits: number);
|
||||
_unsafeLadder(elm: PC_P<PC>, n: bigint, p?: PC_P<PC>): PC_P<PC>;
|
||||
/**
|
||||
* Creates a wNAF precomputation window. Used for caching.
|
||||
* Default window size is set by `utils.precompute()` and is equal to 8.
|
||||
* Number of precomputed points depends on the curve size:
|
||||
* 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
|
||||
* - 𝑊 is the window size
|
||||
* - 𝑛 is the bitlength of the curve order.
|
||||
* For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
|
||||
* @param point - Point instance
|
||||
* @param W - window size
|
||||
* @returns precomputed point tables flattened to a single array
|
||||
*/
|
||||
private precomputeWindow;
|
||||
/**
|
||||
* Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
|
||||
* More compact implementation:
|
||||
* https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
|
||||
* @returns real and fake (for const-time) points
|
||||
*/
|
||||
private wNAF;
|
||||
/**
|
||||
* Implements unsafe EC multiplication using precomputed tables
|
||||
* and w-ary non-adjacent form.
|
||||
* @param acc - accumulator point to add result of multiplication
|
||||
* @returns point
|
||||
*/
|
||||
private wNAFUnsafe;
|
||||
private getPrecomputes;
|
||||
cached(point: PC_P<PC>, scalar: bigint, transform?: Mapper<PC_P<PC>>): {
|
||||
p: PC_P<PC>;
|
||||
f: PC_P<PC>;
|
||||
};
|
||||
unsafe(point: PC_P<PC>, scalar: bigint, transform?: Mapper<PC_P<PC>>, prev?: PC_P<PC>): PC_P<PC>;
|
||||
createCache(P: PC_P<PC>, W: number): void;
|
||||
hasCache(elm: PC_P<PC>): boolean;
|
||||
}
|
||||
/**
|
||||
* Endomorphism-specific multiplication for Koblitz curves.
|
||||
* Cost: 128 dbl, 0-256 adds.
|
||||
* @param Point - Point constructor.
|
||||
* @param point - Input point.
|
||||
* @param k1 - First non-negative absolute scalar chunk.
|
||||
* @param k2 - Second non-negative absolute scalar chunk.
|
||||
* @returns Partial multiplication results.
|
||||
* @example
|
||||
* Endomorphism-specific multiplication for Koblitz curves.
|
||||
*
|
||||
* ```ts
|
||||
* import { mulEndoUnsafe } from '@noble/curves/abstract/curve.js';
|
||||
* import { secp256k1 } from '@noble/curves/secp256k1.js';
|
||||
* const parts = mulEndoUnsafe(secp256k1.Point, secp256k1.Point.BASE, 3n, 5n);
|
||||
* ```
|
||||
*/
|
||||
export declare function mulEndoUnsafe<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(Point: PC, point: P, k1: bigint, k2: bigint): {
|
||||
p1: P;
|
||||
p2: P;
|
||||
};
|
||||
/**
|
||||
* Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
|
||||
* 30x faster vs naive addition on L=4096, 10x faster than precomputes.
|
||||
* For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.
|
||||
* Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.
|
||||
* @param c - Curve Point constructor
|
||||
* @param points - array of L curve points
|
||||
* @param scalars - array of L scalars (aka secret keys / bigints)
|
||||
* @returns MSM result point. Empty input is accepted and returns the identity.
|
||||
* @throws If the point set, scalar set, or MSM sizing is invalid. {@link Error}
|
||||
* @example
|
||||
* Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
|
||||
*
|
||||
* ```ts
|
||||
* import { pippenger } from '@noble/curves/abstract/curve.js';
|
||||
* import { p256 } from '@noble/curves/nist.js';
|
||||
* const point = pippenger(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()], [2n, 3n]);
|
||||
* ```
|
||||
*/
|
||||
export declare function pippenger<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(c: PC, points: P[], scalars: bigint[]): P;
|
||||
/**
|
||||
* Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
|
||||
* @param c - Curve Point constructor
|
||||
* @param points - array of L curve points
|
||||
* @param windowSize - Precompute window size.
|
||||
* @returns Function which multiplies points with scalars. The closure accepts
|
||||
* `scalars.length <= points.length`, and omitted trailing scalars are treated as zero.
|
||||
* @throws If the point set or precompute window is invalid. {@link Error}
|
||||
* @example
|
||||
* Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
|
||||
*
|
||||
* ```ts
|
||||
* import { precomputeMSMUnsafe } from '@noble/curves/abstract/curve.js';
|
||||
* import { p256 } from '@noble/curves/nist.js';
|
||||
* const msm = precomputeMSMUnsafe(p256.Point, [p256.Point.BASE], 4);
|
||||
* const point = msm([3n]);
|
||||
* ```
|
||||
*/
|
||||
export declare function precomputeMSMUnsafe<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(c: PC, points: P[], windowSize: number): (scalars: bigint[]) => P;
|
||||
/** Minimal curve parameters needed to construct a Weierstrass or Edwards curve. */
|
||||
export type ValidCurveParams<T> = {
|
||||
/** Base-field modulus. */
|
||||
p: bigint;
|
||||
/** Prime subgroup order. */
|
||||
n: bigint;
|
||||
/** Cofactor. */
|
||||
h: bigint;
|
||||
/** Curve parameter `a`. */
|
||||
a: T;
|
||||
/** Weierstrass curve parameter `b`. */
|
||||
b?: T;
|
||||
/** Edwards curve parameter `d`. */
|
||||
d?: T;
|
||||
/** Generator x coordinate. */
|
||||
Gx: T;
|
||||
/** Generator y coordinate. */
|
||||
Gy: T;
|
||||
};
|
||||
/** Pair of fields used by curve constructors. */
|
||||
export type FpFn<T> = {
|
||||
/** Base field used for curve coordinates. */
|
||||
Fp: IField<T>;
|
||||
/** Scalar field used for secret scalars and subgroup arithmetic. */
|
||||
Fn: IField<bigint>;
|
||||
};
|
||||
/**
|
||||
* Validates basic CURVE shape and field membership, then creates fields.
|
||||
* This does not prove that the generator is on-curve, that subgroup/order data are consistent, or
|
||||
* that the curve equation itself is otherwise sane.
|
||||
* @param type - Curve family.
|
||||
* @param CURVE - Curve parameters.
|
||||
* @param curveOpts - Optional field overrides:
|
||||
* - `Fp` (optional): Optional base-field override.
|
||||
* - `Fn` (optional): Optional scalar-field override.
|
||||
* @param FpFnLE - Whether field encoding is little-endian.
|
||||
* @returns Frozen curve parameters and fields.
|
||||
* @throws If the curve parameters or field overrides are invalid. {@link Error}
|
||||
* @example
|
||||
* Build curve fields from raw constants before constructing a curve instance.
|
||||
*
|
||||
* ```ts
|
||||
* const curve = createCurveFields('weierstrass', {
|
||||
* p: 17n,
|
||||
* n: 19n,
|
||||
* h: 1n,
|
||||
* a: 2n,
|
||||
* b: 2n,
|
||||
* Gx: 5n,
|
||||
* Gy: 1n,
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export declare function createCurveFields<T>(type: 'weierstrass' | 'edwards', CURVE: ValidCurveParams<T>, curveOpts?: TArg<Partial<FpFn<T>>>, FpFnLE?: boolean): TRet<FpFn<T> & {
|
||||
CURVE: ValidCurveParams<T>;
|
||||
}>;
|
||||
type KeygenFn = (seed?: Uint8Array, isCompressed?: boolean) => {
|
||||
secretKey: Uint8Array;
|
||||
publicKey: Uint8Array;
|
||||
};
|
||||
/**
|
||||
* @param randomSecretKey - Secret-key generator.
|
||||
* @param getPublicKey - Public-key derivation helper.
|
||||
* @returns Keypair generator.
|
||||
* @example
|
||||
* Build a `keygen()` helper from existing secret-key and public-key primitives.
|
||||
*
|
||||
* ```ts
|
||||
* import { createKeygen } from '@noble/curves/abstract/curve.js';
|
||||
* import { p256 } from '@noble/curves/nist.js';
|
||||
* const keygen = createKeygen(p256.utils.randomSecretKey, p256.getPublicKey);
|
||||
* const pair = keygen();
|
||||
* ```
|
||||
*/
|
||||
export declare function createKeygen(randomSecretKey: Function, getPublicKey: TArg<Signer['getPublicKey']>): TRet<KeygenFn>;
|
||||
export {};
|
||||
//# sourceMappingURL=curve.d.ts.map
|
||||
1
node_modules/@noble/curves/abstract/curve.d.ts.map
generated
vendored
Normal file
1
node_modules/@noble/curves/abstract/curve.d.ts.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
611
node_modules/@noble/curves/abstract/curve.js
generated
vendored
Normal file
611
node_modules/@noble/curves/abstract/curve.js
generated
vendored
Normal file
@@ -0,0 +1,611 @@
|
||||
/**
|
||||
* Methods for elliptic curve multiplication by scalars.
|
||||
* Contains wNAF, pippenger.
|
||||
* @module
|
||||
*/
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
import { bitLen, bitMask, validateObject } from "../utils.js";
|
||||
import { Field, FpInvertBatch, validateField } from "./modular.js";
|
||||
const _0n = /* @__PURE__ */ BigInt(0);
|
||||
const _1n = /* @__PURE__ */ BigInt(1);
|
||||
/**
|
||||
* Validates the static surface of a point constructor.
|
||||
* This is only a cheap sanity check for the constructor hooks and fields consumed by generic
|
||||
* factories; it does not certify `BASE`/`ZERO` semantics or prove the curve implementation itself.
|
||||
* @param Point - Runtime point constructor.
|
||||
* @throws On missing constructor hooks or malformed field metadata. {@link TypeError}
|
||||
* @example
|
||||
* Check that one point constructor exposes the static hooks generic helpers need.
|
||||
*
|
||||
* ```ts
|
||||
* import { ed25519 } from '@noble/curves/ed25519.js';
|
||||
* import { validatePointCons } from '@noble/curves/abstract/curve.js';
|
||||
* validatePointCons(ed25519.Point);
|
||||
* ```
|
||||
*/
|
||||
export function validatePointCons(Point) {
|
||||
const pc = Point;
|
||||
if (typeof pc !== 'function')
|
||||
throw new TypeError('Point must be a constructor');
|
||||
// validateObject only accepts plain objects, so copy the constructor statics into one bag first.
|
||||
validateObject({
|
||||
Fp: pc.Fp,
|
||||
Fn: pc.Fn,
|
||||
fromAffine: pc.fromAffine,
|
||||
fromBytes: pc.fromBytes,
|
||||
fromHex: pc.fromHex,
|
||||
}, {
|
||||
Fp: 'object',
|
||||
Fn: 'object',
|
||||
fromAffine: 'function',
|
||||
fromBytes: 'function',
|
||||
fromHex: 'function',
|
||||
});
|
||||
validateField(pc.Fp);
|
||||
validateField(pc.Fn);
|
||||
}
|
||||
/**
|
||||
* Computes both candidates first, but the final selection still branches on `condition`, so this
|
||||
* is not a strict constant-time CMOV primitive.
|
||||
* @param condition - Whether to negate the point.
|
||||
* @param item - Point-like value.
|
||||
* @returns Original or negated value.
|
||||
* @example
|
||||
* Keep the point or return its negation based on one boolean branch.
|
||||
*
|
||||
* ```ts
|
||||
* import { negateCt } from '@noble/curves/abstract/curve.js';
|
||||
* import { p256 } from '@noble/curves/nist.js';
|
||||
* const maybeNegated = negateCt(true, p256.Point.BASE);
|
||||
* ```
|
||||
*/
|
||||
export function negateCt(condition, item) {
|
||||
const neg = item.negate();
|
||||
return condition ? neg : item;
|
||||
}
|
||||
/**
|
||||
* Takes a bunch of Projective Points but executes only one
|
||||
* inversion on all of them. Inversion is very slow operation,
|
||||
* so this improves performance massively.
|
||||
* Optimization: converts a list of projective points to a list of identical points with Z=1.
|
||||
* Input points are left unchanged; the normalized points are returned as fresh instances.
|
||||
* @param c - Point constructor.
|
||||
* @param points - Projective points.
|
||||
* @returns Fresh projective points reconstructed from normalized affine coordinates.
|
||||
* @example
|
||||
* Batch-normalize projective points with a single shared inversion.
|
||||
*
|
||||
* ```ts
|
||||
* import { normalizeZ } from '@noble/curves/abstract/curve.js';
|
||||
* import { p256 } from '@noble/curves/nist.js';
|
||||
* const points = normalizeZ(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()]);
|
||||
* ```
|
||||
*/
|
||||
export function normalizeZ(c, points) {
|
||||
const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
|
||||
return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
|
||||
}
|
||||
function validateW(W, bits) {
|
||||
if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
|
||||
throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);
|
||||
}
|
||||
function calcWOpts(W, scalarBits) {
|
||||
validateW(W, scalarBits);
|
||||
const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero
|
||||
const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero
|
||||
const maxNumber = 2 ** W; // W=8 256
|
||||
const mask = bitMask(W); // W=8 255 == mask 0b11111111
|
||||
const shiftBy = BigInt(W); // W=8 8
|
||||
return { windows, windowSize, mask, maxNumber, shiftBy };
|
||||
}
|
||||
function calcOffsets(n, window, wOpts) {
|
||||
const { windowSize, mask, maxNumber, shiftBy } = wOpts;
|
||||
let wbits = Number(n & mask); // extract W bits.
|
||||
let nextN = n >> shiftBy; // shift number by W bits.
|
||||
// What actually happens here:
|
||||
// const highestBit = Number(mask ^ (mask >> 1n));
|
||||
// let wbits2 = wbits - 1; // skip zero
|
||||
// if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);
|
||||
// split if bits > max: +224 => 256-32
|
||||
if (wbits > windowSize) {
|
||||
// we skip zero, which means instead of `>= size-1`, we do `> size`
|
||||
wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.
|
||||
nextN += _1n; // +256 (carry)
|
||||
}
|
||||
const offsetStart = window * windowSize;
|
||||
const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero; ignore when isZero
|
||||
const isZero = wbits === 0; // is current window slice a 0?
|
||||
const isNeg = wbits < 0; // is current window slice negative?
|
||||
const isNegF = window % 2 !== 0; // fake branch noise only
|
||||
const offsetF = offsetStart; // fake branch noise only
|
||||
return { nextN, offset, isZero, isNeg, isNegF, offsetF };
|
||||
}
|
||||
function validateMSMPoints(points, c) {
|
||||
if (!Array.isArray(points))
|
||||
throw new Error('array expected');
|
||||
points.forEach((p, i) => {
|
||||
if (!(p instanceof c))
|
||||
throw new Error('invalid point at index ' + i);
|
||||
});
|
||||
}
|
||||
function validateMSMScalars(scalars, field) {
|
||||
if (!Array.isArray(scalars))
|
||||
throw new Error('array of scalars expected');
|
||||
scalars.forEach((s, i) => {
|
||||
if (!field.isValid(s))
|
||||
throw new Error('invalid scalar at index ' + i);
|
||||
});
|
||||
}
|
||||
// Since points in different groups cannot be equal (different object constructor),
|
||||
// we can have single place to store precomputes.
|
||||
// Allows to make points frozen / immutable.
|
||||
const pointPrecomputes = new WeakMap();
|
||||
const pointWindowSizes = new WeakMap();
|
||||
function getW(P) {
|
||||
// To disable precomputes:
|
||||
// return 1;
|
||||
// `1` is also the uncached sentinel: use the ladder / non-precomputed path.
|
||||
return pointWindowSizes.get(P) || 1;
|
||||
}
|
||||
function assert0(n) {
|
||||
// Internal invariant: a non-zero remainder here means the wNAF window decomposition or loop
|
||||
// count is inconsistent, not that the original caller provided a bad scalar.
|
||||
if (n !== _0n)
|
||||
throw new Error('invalid wNAF');
|
||||
}
|
||||
/**
|
||||
* Elliptic curve multiplication of Point by scalar. Fragile.
|
||||
* Table generation takes **30MB of ram and 10ms on high-end CPU**,
|
||||
* but may take much longer on slow devices. Actual generation will happen on
|
||||
* first call of `multiply()`. By default, `BASE` point is precomputed.
|
||||
*
|
||||
* Scalars should always be less than curve order: this should be checked inside of a curve itself.
|
||||
* Creates precomputation tables for fast multiplication:
|
||||
* - private scalar is split by fixed size windows of W bits
|
||||
* - every window point is collected from window's table & added to accumulator
|
||||
* - since windows are different, same point inside tables won't be accessed more than once per calc
|
||||
* - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
|
||||
* - +1 window is neccessary for wNAF
|
||||
* - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
|
||||
*
|
||||
* TODO: research returning a 2d JS array of windows instead of a single window.
|
||||
* This would allow windows to be in different memory locations.
|
||||
* @param Point - Point constructor.
|
||||
* @param bits - Scalar bit length.
|
||||
* @example
|
||||
* Elliptic curve multiplication of Point by scalar.
|
||||
*
|
||||
* ```ts
|
||||
* import { wNAF } from '@noble/curves/abstract/curve.js';
|
||||
* import { p256 } from '@noble/curves/nist.js';
|
||||
* const ladder = new wNAF(p256.Point, p256.Point.Fn.BITS);
|
||||
* ```
|
||||
*/
|
||||
export class wNAF {
|
||||
BASE;
|
||||
ZERO;
|
||||
Fn;
|
||||
bits;
|
||||
// Parametrized with a given Point class (not individual point)
|
||||
constructor(Point, bits) {
|
||||
this.BASE = Point.BASE;
|
||||
this.ZERO = Point.ZERO;
|
||||
this.Fn = Point.Fn;
|
||||
this.bits = bits;
|
||||
}
|
||||
// non-const time multiplication ladder
|
||||
_unsafeLadder(elm, n, p = this.ZERO) {
|
||||
let d = elm;
|
||||
while (n > _0n) {
|
||||
if (n & _1n)
|
||||
p = p.add(d);
|
||||
d = d.double();
|
||||
n >>= _1n;
|
||||
}
|
||||
return p;
|
||||
}
|
||||
/**
|
||||
* Creates a wNAF precomputation window. Used for caching.
|
||||
* Default window size is set by `utils.precompute()` and is equal to 8.
|
||||
* Number of precomputed points depends on the curve size:
|
||||
* 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
|
||||
* - 𝑊 is the window size
|
||||
* - 𝑛 is the bitlength of the curve order.
|
||||
* For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
|
||||
* @param point - Point instance
|
||||
* @param W - window size
|
||||
* @returns precomputed point tables flattened to a single array
|
||||
*/
|
||||
precomputeWindow(point, W) {
|
||||
const { windows, windowSize } = calcWOpts(W, this.bits);
|
||||
const points = [];
|
||||
let p = point;
|
||||
let base = p;
|
||||
for (let window = 0; window < windows; window++) {
|
||||
base = p;
|
||||
points.push(base);
|
||||
// i=1, bc we skip 0
|
||||
for (let i = 1; i < windowSize; i++) {
|
||||
base = base.add(p);
|
||||
points.push(base);
|
||||
}
|
||||
p = base.double();
|
||||
}
|
||||
return points;
|
||||
}
|
||||
/**
|
||||
* Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
|
||||
* More compact implementation:
|
||||
* https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
|
||||
* @returns real and fake (for const-time) points
|
||||
*/
|
||||
wNAF(W, precomputes, n) {
|
||||
// Scalar should be smaller than field order
|
||||
if (!this.Fn.isValid(n))
|
||||
throw new Error('invalid scalar');
|
||||
// Accumulators
|
||||
let p = this.ZERO;
|
||||
let f = this.BASE;
|
||||
// This code was first written with assumption that 'f' and 'p' will never be infinity point:
|
||||
// since each addition is multiplied by 2 ** W, it cannot cancel each other. However,
|
||||
// there is negate now: it is possible that negated element from low value
|
||||
// would be the same as high element, which will create carry into next window.
|
||||
// It's not obvious how this can fail, but still worth investigating later.
|
||||
const wo = calcWOpts(W, this.bits);
|
||||
for (let window = 0; window < wo.windows; window++) {
|
||||
// (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise
|
||||
const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
|
||||
n = nextN;
|
||||
if (isZero) {
|
||||
// bits are 0: add garbage to fake point
|
||||
// Important part for const-time getPublicKey: add random "noise" point to f.
|
||||
f = f.add(negateCt(isNegF, precomputes[offsetF]));
|
||||
}
|
||||
else {
|
||||
// bits are 1: add to result point
|
||||
p = p.add(negateCt(isNeg, precomputes[offset]));
|
||||
}
|
||||
}
|
||||
assert0(n);
|
||||
// Return both real and fake points so JIT keeps the noise path alive.
|
||||
// Known caveat: negate/carry interactions can still drive `f` to infinity even when `p` is not,
|
||||
// which weakens the noise path and leaves this only "less const-time" by about one bigint mul.
|
||||
return { p, f };
|
||||
}
|
||||
/**
|
||||
* Implements unsafe EC multiplication using precomputed tables
|
||||
* and w-ary non-adjacent form.
|
||||
* @param acc - accumulator point to add result of multiplication
|
||||
* @returns point
|
||||
*/
|
||||
wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
|
||||
const wo = calcWOpts(W, this.bits);
|
||||
for (let window = 0; window < wo.windows; window++) {
|
||||
if (n === _0n)
|
||||
break; // Early-exit, skip 0 value
|
||||
const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
|
||||
n = nextN;
|
||||
if (isZero) {
|
||||
// Window bits are 0: skip processing.
|
||||
// Move to next window.
|
||||
continue;
|
||||
}
|
||||
else {
|
||||
const item = precomputes[offset];
|
||||
acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM
|
||||
}
|
||||
}
|
||||
assert0(n);
|
||||
return acc;
|
||||
}
|
||||
getPrecomputes(W, point, transform) {
|
||||
// Cache key is only point identity plus the remembered window size; callers must not reuse the
|
||||
// same point with incompatible `transform(...)` layouts and expect a separate cache entry.
|
||||
let comp = pointPrecomputes.get(point);
|
||||
if (!comp) {
|
||||
comp = this.precomputeWindow(point, W);
|
||||
if (W !== 1) {
|
||||
// Doing transform outside of if brings 15% perf hit
|
||||
if (typeof transform === 'function')
|
||||
comp = transform(comp);
|
||||
pointPrecomputes.set(point, comp);
|
||||
}
|
||||
}
|
||||
return comp;
|
||||
}
|
||||
cached(point, scalar, transform) {
|
||||
const W = getW(point);
|
||||
return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
|
||||
}
|
||||
unsafe(point, scalar, transform, prev) {
|
||||
const W = getW(point);
|
||||
if (W === 1)
|
||||
return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster
|
||||
return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
|
||||
}
|
||||
// We calculate precomputes for elliptic curve point multiplication
|
||||
// using windowed method. This specifies window size and
|
||||
// stores precomputed values. Usually only base point would be precomputed.
|
||||
createCache(P, W) {
|
||||
validateW(W, this.bits);
|
||||
pointWindowSizes.set(P, W);
|
||||
pointPrecomputes.delete(P);
|
||||
}
|
||||
hasCache(elm) {
|
||||
return getW(elm) !== 1;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Endomorphism-specific multiplication for Koblitz curves.
|
||||
* Cost: 128 dbl, 0-256 adds.
|
||||
* @param Point - Point constructor.
|
||||
* @param point - Input point.
|
||||
* @param k1 - First non-negative absolute scalar chunk.
|
||||
* @param k2 - Second non-negative absolute scalar chunk.
|
||||
* @returns Partial multiplication results.
|
||||
* @example
|
||||
* Endomorphism-specific multiplication for Koblitz curves.
|
||||
*
|
||||
* ```ts
|
||||
* import { mulEndoUnsafe } from '@noble/curves/abstract/curve.js';
|
||||
* import { secp256k1 } from '@noble/curves/secp256k1.js';
|
||||
* const parts = mulEndoUnsafe(secp256k1.Point, secp256k1.Point.BASE, 3n, 5n);
|
||||
* ```
|
||||
*/
|
||||
export function mulEndoUnsafe(Point, point, k1, k2) {
|
||||
let acc = point;
|
||||
let p1 = Point.ZERO;
|
||||
let p2 = Point.ZERO;
|
||||
while (k1 > _0n || k2 > _0n) {
|
||||
if (k1 & _1n)
|
||||
p1 = p1.add(acc);
|
||||
if (k2 & _1n)
|
||||
p2 = p2.add(acc);
|
||||
acc = acc.double();
|
||||
k1 >>= _1n;
|
||||
k2 >>= _1n;
|
||||
}
|
||||
return { p1, p2 };
|
||||
}
|
||||
/**
|
||||
* Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
|
||||
* 30x faster vs naive addition on L=4096, 10x faster than precomputes.
|
||||
* For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.
|
||||
* Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.
|
||||
* @param c - Curve Point constructor
|
||||
* @param points - array of L curve points
|
||||
* @param scalars - array of L scalars (aka secret keys / bigints)
|
||||
* @returns MSM result point. Empty input is accepted and returns the identity.
|
||||
* @throws If the point set, scalar set, or MSM sizing is invalid. {@link Error}
|
||||
* @example
|
||||
* Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
|
||||
*
|
||||
* ```ts
|
||||
* import { pippenger } from '@noble/curves/abstract/curve.js';
|
||||
* import { p256 } from '@noble/curves/nist.js';
|
||||
* const point = pippenger(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()], [2n, 3n]);
|
||||
* ```
|
||||
*/
|
||||
export function pippenger(c, points, scalars) {
|
||||
// If we split scalars by some window (let's say 8 bits), every chunk will only
|
||||
// take 256 buckets even if there are 4096 scalars, also re-uses double.
|
||||
// TODO:
|
||||
// - https://eprint.iacr.org/2024/750.pdf
|
||||
// - https://tches.iacr.org/index.php/TCHES/article/view/10287
|
||||
// 0 is accepted in scalars
|
||||
const fieldN = c.Fn;
|
||||
validateMSMPoints(points, c);
|
||||
validateMSMScalars(scalars, fieldN);
|
||||
const plength = points.length;
|
||||
const slength = scalars.length;
|
||||
if (plength !== slength)
|
||||
throw new Error('arrays of points and scalars must have equal length');
|
||||
// if (plength === 0) throw new Error('array must be of length >= 2');
|
||||
const zero = c.ZERO;
|
||||
const wbits = bitLen(BigInt(plength));
|
||||
let windowSize = 1; // bits
|
||||
if (wbits > 12)
|
||||
windowSize = wbits - 3;
|
||||
else if (wbits > 4)
|
||||
windowSize = wbits - 2;
|
||||
else if (wbits > 0)
|
||||
windowSize = 2;
|
||||
const MASK = bitMask(windowSize);
|
||||
const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array
|
||||
const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
|
||||
let sum = zero;
|
||||
for (let i = lastBits; i >= 0; i -= windowSize) {
|
||||
buckets.fill(zero);
|
||||
for (let j = 0; j < slength; j++) {
|
||||
const scalar = scalars[j];
|
||||
const wbits = Number((scalar >> BigInt(i)) & MASK);
|
||||
buckets[wbits] = buckets[wbits].add(points[j]);
|
||||
}
|
||||
let resI = zero; // not using this will do small speed-up, but will lose ct
|
||||
// Skip first bucket, because it is zero
|
||||
for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
|
||||
sumI = sumI.add(buckets[j]);
|
||||
resI = resI.add(sumI);
|
||||
}
|
||||
sum = sum.add(resI);
|
||||
if (i !== 0)
|
||||
for (let j = 0; j < windowSize; j++)
|
||||
sum = sum.double();
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
/**
|
||||
* Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
|
||||
* @param c - Curve Point constructor
|
||||
* @param points - array of L curve points
|
||||
* @param windowSize - Precompute window size.
|
||||
* @returns Function which multiplies points with scalars. The closure accepts
|
||||
* `scalars.length <= points.length`, and omitted trailing scalars are treated as zero.
|
||||
* @throws If the point set or precompute window is invalid. {@link Error}
|
||||
* @example
|
||||
* Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
|
||||
*
|
||||
* ```ts
|
||||
* import { precomputeMSMUnsafe } from '@noble/curves/abstract/curve.js';
|
||||
* import { p256 } from '@noble/curves/nist.js';
|
||||
* const msm = precomputeMSMUnsafe(p256.Point, [p256.Point.BASE], 4);
|
||||
* const point = msm([3n]);
|
||||
* ```
|
||||
*/
|
||||
export function precomputeMSMUnsafe(c, points, windowSize) {
|
||||
/**
|
||||
* Performance Analysis of Window-based Precomputation
|
||||
*
|
||||
* Base Case (256-bit scalar, 8-bit window):
|
||||
* - Standard precomputation requires:
|
||||
* - 31 additions per scalar × 256 scalars = 7,936 ops
|
||||
* - Plus 255 summary additions = 8,191 total ops
|
||||
* Note: Summary additions can be optimized via accumulator
|
||||
*
|
||||
* Chunked Precomputation Analysis:
|
||||
* - Using 32 chunks requires:
|
||||
* - 255 additions per chunk
|
||||
* - 256 doublings
|
||||
* - Total: (255 × 32) + 256 = 8,416 ops
|
||||
*
|
||||
* Memory Usage Comparison:
|
||||
* Window Size | Standard Points | Chunked Points
|
||||
* ------------|-----------------|---------------
|
||||
* 4-bit | 520 | 15
|
||||
* 8-bit | 4,224 | 255
|
||||
* 10-bit | 13,824 | 1,023
|
||||
* 16-bit | 557,056 | 65,535
|
||||
*
|
||||
* Key Advantages:
|
||||
* 1. Enables larger window sizes due to reduced memory overhead
|
||||
* 2. More efficient for smaller scalar counts:
|
||||
* - 16 chunks: (16 × 255) + 256 = 4,336 ops
|
||||
* - ~2x faster than standard 8,191 ops
|
||||
*
|
||||
* Limitations:
|
||||
* - Not suitable for plain precomputes (requires 256 constant doublings)
|
||||
* - Performance degrades with larger scalar counts:
|
||||
* - Optimal for ~256 scalars
|
||||
* - Less efficient for 4096+ scalars (Pippenger preferred)
|
||||
*/
|
||||
const fieldN = c.Fn;
|
||||
validateW(windowSize, fieldN.BITS);
|
||||
validateMSMPoints(points, c);
|
||||
const zero = c.ZERO;
|
||||
const tableSize = 2 ** windowSize - 1; // table size (without zero)
|
||||
const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item
|
||||
const MASK = bitMask(windowSize);
|
||||
const tables = points.map((p) => {
|
||||
const res = [];
|
||||
for (let i = 0, acc = p; i < tableSize; i++) {
|
||||
res.push(acc);
|
||||
acc = acc.add(p);
|
||||
}
|
||||
return res;
|
||||
});
|
||||
return (scalars) => {
|
||||
validateMSMScalars(scalars, fieldN);
|
||||
if (scalars.length > points.length)
|
||||
throw new Error('array of scalars must be smaller than array of points');
|
||||
let res = zero;
|
||||
for (let i = 0; i < chunks; i++) {
|
||||
// No need to double if accumulator is still zero.
|
||||
if (res !== zero)
|
||||
for (let j = 0; j < windowSize; j++)
|
||||
res = res.double();
|
||||
const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);
|
||||
for (let j = 0; j < scalars.length; j++) {
|
||||
const n = scalars[j];
|
||||
const curr = Number((n >> shiftBy) & MASK);
|
||||
if (!curr)
|
||||
continue; // skip zero scalars chunks
|
||||
res = res.add(tables[j][curr - 1]);
|
||||
}
|
||||
}
|
||||
return res;
|
||||
};
|
||||
}
|
||||
function createField(order, field, isLE) {
|
||||
if (field) {
|
||||
// Reuse supplied field overrides as-is; `isLE` only affects freshly constructed fallback
|
||||
// fields, and validateField() below only checks the arithmetic subset, not full byte/cmov
|
||||
// behavior.
|
||||
if (field.ORDER !== order)
|
||||
throw new Error('Field.ORDER must match order: Fp == p, Fn == n');
|
||||
validateField(field);
|
||||
return field;
|
||||
}
|
||||
else {
|
||||
return Field(order, { isLE });
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Validates basic CURVE shape and field membership, then creates fields.
|
||||
* This does not prove that the generator is on-curve, that subgroup/order data are consistent, or
|
||||
* that the curve equation itself is otherwise sane.
|
||||
* @param type - Curve family.
|
||||
* @param CURVE - Curve parameters.
|
||||
* @param curveOpts - Optional field overrides:
|
||||
* - `Fp` (optional): Optional base-field override.
|
||||
* - `Fn` (optional): Optional scalar-field override.
|
||||
* @param FpFnLE - Whether field encoding is little-endian.
|
||||
* @returns Frozen curve parameters and fields.
|
||||
* @throws If the curve parameters or field overrides are invalid. {@link Error}
|
||||
* @example
|
||||
* Build curve fields from raw constants before constructing a curve instance.
|
||||
*
|
||||
* ```ts
|
||||
* const curve = createCurveFields('weierstrass', {
|
||||
* p: 17n,
|
||||
* n: 19n,
|
||||
* h: 1n,
|
||||
* a: 2n,
|
||||
* b: 2n,
|
||||
* Gx: 5n,
|
||||
* Gy: 1n,
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
|
||||
if (FpFnLE === undefined)
|
||||
FpFnLE = type === 'edwards';
|
||||
if (!CURVE || typeof CURVE !== 'object')
|
||||
throw new Error(`expected valid ${type} CURVE object`);
|
||||
for (const p of ['p', 'n', 'h']) {
|
||||
const val = CURVE[p];
|
||||
if (!(typeof val === 'bigint' && val > _0n))
|
||||
throw new Error(`CURVE.${p} must be positive bigint`);
|
||||
}
|
||||
const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
|
||||
const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
|
||||
const _b = type === 'weierstrass' ? 'b' : 'd';
|
||||
const params = ['Gx', 'Gy', 'a', _b];
|
||||
for (const p of params) {
|
||||
// @ts-ignore
|
||||
if (!Fp.isValid(CURVE[p]))
|
||||
throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
|
||||
}
|
||||
CURVE = Object.freeze(Object.assign({}, CURVE));
|
||||
return { CURVE, Fp, Fn };
|
||||
}
|
||||
/**
|
||||
* @param randomSecretKey - Secret-key generator.
|
||||
* @param getPublicKey - Public-key derivation helper.
|
||||
* @returns Keypair generator.
|
||||
* @example
|
||||
* Build a `keygen()` helper from existing secret-key and public-key primitives.
|
||||
*
|
||||
* ```ts
|
||||
* import { createKeygen } from '@noble/curves/abstract/curve.js';
|
||||
* import { p256 } from '@noble/curves/nist.js';
|
||||
* const keygen = createKeygen(p256.utils.randomSecretKey, p256.getPublicKey);
|
||||
* const pair = keygen();
|
||||
* ```
|
||||
*/
|
||||
export function createKeygen(randomSecretKey, getPublicKey) {
|
||||
return function keygen(seed) {
|
||||
const secretKey = randomSecretKey(seed);
|
||||
return { secretKey, publicKey: getPublicKey(secretKey) };
|
||||
};
|
||||
}
|
||||
//# sourceMappingURL=curve.js.map
|
||||
1
node_modules/@noble/curves/abstract/curve.js.map
generated
vendored
Normal file
1
node_modules/@noble/curves/abstract/curve.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
320
node_modules/@noble/curves/abstract/edwards.d.ts
generated
vendored
Normal file
320
node_modules/@noble/curves/abstract/edwards.d.ts
generated
vendored
Normal file
@@ -0,0 +1,320 @@
|
||||
/**
|
||||
* Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y².
|
||||
* For design rationale of types / exports, see weierstrass module documentation.
|
||||
* Untwisted Edwards curves exist, but they aren't used in real-world protocols.
|
||||
* @module
|
||||
*/
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
import { type FHash, type TArg, type TRet } from '../utils.ts';
|
||||
import { type AffinePoint, type CurveLengths, type CurvePoint, type CurvePointCons } from './curve.ts';
|
||||
import { type IField } from './modular.ts';
|
||||
/** Extended Edwards point with X/Y/Z/T coordinates. */
|
||||
export interface EdwardsPoint extends CurvePoint<bigint, EdwardsPoint> {
|
||||
/** extended X coordinate. Different from affine x. */
|
||||
readonly X: bigint;
|
||||
/** extended Y coordinate. Different from affine y. */
|
||||
readonly Y: bigint;
|
||||
/** extended Z coordinate */
|
||||
readonly Z: bigint;
|
||||
/** extended T coordinate */
|
||||
readonly T: bigint;
|
||||
}
|
||||
/** Constructor and decoding helpers for extended Edwards points. */
|
||||
export interface EdwardsPointCons extends CurvePointCons<EdwardsPoint> {
|
||||
/** Create a point from extended X/Y/Z/T coordinates without validation. */
|
||||
new (X: bigint, Y: bigint, Z: bigint, T: bigint): EdwardsPoint;
|
||||
/**
|
||||
* Return the curve parameters used by this point constructor.
|
||||
* @returns Curve parameters.
|
||||
*/
|
||||
CURVE(): EdwardsOpts;
|
||||
/**
|
||||
* Decode a point from bytes, optionally using ZIP-215 rules.
|
||||
* @param bytes - Encoded point bytes.
|
||||
* @param zip215 - Whether to accept ZIP-215 encodings.
|
||||
* @returns Decoded Edwards point.
|
||||
*/
|
||||
fromBytes(bytes: Uint8Array, zip215?: boolean): EdwardsPoint;
|
||||
/**
|
||||
* Decode a point from hex, optionally using ZIP-215 rules.
|
||||
* @param hex - Encoded point hex.
|
||||
* @param zip215 - Whether to accept ZIP-215 encodings.
|
||||
* @returns Decoded Edwards point.
|
||||
*/
|
||||
fromHex(hex: string, zip215?: boolean): EdwardsPoint;
|
||||
}
|
||||
/**
|
||||
* Twisted Edwards curve options.
|
||||
*
|
||||
* * a: formula param
|
||||
* * d: formula param
|
||||
* * p: prime characteristic (order) of finite field, in which arithmetics is done
|
||||
* * n: order of prime subgroup a.k.a total amount of valid curve points
|
||||
* * h: cofactor. h*n is group order; n is subgroup order
|
||||
* * Gx: x coordinate of generator point a.k.a. base point
|
||||
* * Gy: y coordinate of generator point
|
||||
*/
|
||||
export type EdwardsOpts = Readonly<{
|
||||
/** Base-field modulus. */
|
||||
p: bigint;
|
||||
/** Prime subgroup order. */
|
||||
n: bigint;
|
||||
/** Curve cofactor. */
|
||||
h: bigint;
|
||||
/** Edwards curve parameter `a`. */
|
||||
a: bigint;
|
||||
/** Edwards curve parameter `d`. */
|
||||
d: bigint;
|
||||
/** Generator x coordinate. */
|
||||
Gx: bigint;
|
||||
/** Generator y coordinate. */
|
||||
Gy: bigint;
|
||||
}>;
|
||||
/**
|
||||
* Extra curve options for Twisted Edwards.
|
||||
*
|
||||
* * Fp: redefined Field over curve.p
|
||||
* * Fn: redefined Field over curve.n
|
||||
* * uvRatio: helper function for decompression, calculating √(u/v)
|
||||
*/
|
||||
export type EdwardsExtraOpts = Partial<{
|
||||
/** Optional base-field override. */
|
||||
Fp: IField<bigint>;
|
||||
/** Optional scalar-field override. */
|
||||
Fn: IField<bigint>;
|
||||
/** Whether field encodings are little-endian. */
|
||||
FpFnLE: boolean;
|
||||
/** Square-root ratio helper used during point decompression. */
|
||||
uvRatio: (u: bigint, v: bigint) => {
|
||||
isValid: boolean;
|
||||
value: bigint;
|
||||
};
|
||||
}>;
|
||||
/**
|
||||
* EdDSA (Edwards Digital Signature algorithm) options.
|
||||
*
|
||||
* * hash: hash function used to hash secret keys and messages
|
||||
* * adjustScalarBytes: clears bits to get valid field element
|
||||
* * domain: Used for hashing
|
||||
* * mapToCurve: for hash-to-curve standard
|
||||
* * prehash: RFC 8032 pre-hashing of messages to sign() / verify()
|
||||
* * randomBytes: function generating random bytes, used for randomSecretKey
|
||||
*/
|
||||
export type EdDSAOpts = Partial<{
|
||||
/** Clamp or otherwise normalize secret-scalar bytes before reducing mod `n`. */
|
||||
adjustScalarBytes: (bytes: TArg<Uint8Array>) => TRet<Uint8Array>;
|
||||
/** Domain-separation helper for contexts and prehash mode. */
|
||||
domain: (data: TArg<Uint8Array>, ctx: TArg<Uint8Array>, phflag: boolean) => TRet<Uint8Array>;
|
||||
/** Optional hash-to-curve mapper for protocols like Ristretto hash-to-group. */
|
||||
mapToCurve: (scalar: bigint[]) => AffinePoint<bigint>;
|
||||
/** Optional prehash function used before signing or verifying messages. */
|
||||
prehash: FHash;
|
||||
/** Default verification decoding policy. ZIP-215 is more permissive than RFC 8032 / NIST. */
|
||||
zip215: boolean;
|
||||
/** RNG override used by helper constructors. */
|
||||
randomBytes: (bytesLength?: number) => TRet<Uint8Array>;
|
||||
}>;
|
||||
/**
|
||||
* EdDSA (Edwards Digital Signature algorithm) helper namespace.
|
||||
* Allows creating and verifying signatures, and deriving public keys.
|
||||
*/
|
||||
export interface EdDSA {
|
||||
/**
|
||||
* Generate a secret/public key pair.
|
||||
* @param seed - Optional seed material.
|
||||
* @returns Secret/public key pair.
|
||||
*/
|
||||
keygen: (seed?: TArg<Uint8Array>) => {
|
||||
secretKey: TRet<Uint8Array>;
|
||||
publicKey: TRet<Uint8Array>;
|
||||
};
|
||||
/**
|
||||
* Derive the public key from a secret key.
|
||||
* @param secretKey - Secret key bytes.
|
||||
* @returns Encoded public key.
|
||||
*/
|
||||
getPublicKey: (secretKey: TArg<Uint8Array>) => TRet<Uint8Array>;
|
||||
/**
|
||||
* Sign a message with an EdDSA secret key.
|
||||
* @param message - Message bytes.
|
||||
* @param secretKey - Secret key bytes.
|
||||
* @param options - Optional signature tweaks:
|
||||
* - `context` (optional): Domain-separation context for Ed25519ctx/Ed448.
|
||||
* @returns Encoded signature bytes.
|
||||
*/
|
||||
sign: (message: TArg<Uint8Array>, secretKey: TArg<Uint8Array>, options?: TArg<{
|
||||
context?: Uint8Array;
|
||||
}>) => TRet<Uint8Array>;
|
||||
/**
|
||||
* Verify a signature against a message and public key.
|
||||
* @param sig - Encoded signature bytes.
|
||||
* @param message - Message bytes.
|
||||
* @param publicKey - Encoded public key.
|
||||
* @param options - Optional verification tweaks:
|
||||
* - `context` (optional): Domain-separation context for Ed25519ctx/Ed448.
|
||||
* - `zip215` (optional): Whether to accept ZIP-215 encodings.
|
||||
* @returns Whether the signature is valid.
|
||||
*/
|
||||
verify: (sig: TArg<Uint8Array>, message: TArg<Uint8Array>, publicKey: TArg<Uint8Array>, options?: TArg<{
|
||||
context?: Uint8Array;
|
||||
zip215?: boolean;
|
||||
}>) => boolean;
|
||||
/** Point constructor used by this signature scheme. */
|
||||
Point: EdwardsPointCons;
|
||||
/** Helper utilities for key validation and Montgomery conversion. */
|
||||
utils: {
|
||||
/**
|
||||
* Generate a valid random secret key.
|
||||
* Optional seed bytes are only length-checked and returned unchanged.
|
||||
*/
|
||||
randomSecretKey: (seed?: TArg<Uint8Array>) => TRet<Uint8Array>;
|
||||
/** Check whether a secret key has the expected encoding. */
|
||||
isValidSecretKey: (secretKey: TArg<Uint8Array>) => boolean;
|
||||
/** Check whether a public key decodes to a valid point. */
|
||||
isValidPublicKey: (publicKey: TArg<Uint8Array>, zip215?: boolean) => boolean;
|
||||
/**
|
||||
* Converts ed public key to x public key.
|
||||
*
|
||||
* There is NO `fromMontgomery`:
|
||||
* - There are 2 valid ed25519 points for every x25519, with flipped coordinate
|
||||
* - Sometimes there are 0 valid ed25519 points, because x25519 *additionally*
|
||||
* accepts inputs on the quadratic twist, which can't be moved to ed25519
|
||||
*
|
||||
* @example
|
||||
* Converts ed public key to x public key.
|
||||
*
|
||||
* ```js
|
||||
* const someonesPub_ed = ed25519.getPublicKey(ed25519.utils.randomSecretKey());
|
||||
* const someonesPub = ed25519.utils.toMontgomery(someonesPub);
|
||||
* const aPriv = x25519.utils.randomSecretKey();
|
||||
* const shared = x25519.getSharedSecret(aPriv, someonesPub)
|
||||
* ```
|
||||
*/
|
||||
toMontgomery: (publicKey: TArg<Uint8Array>) => TRet<Uint8Array>;
|
||||
/**
|
||||
* Converts ed secret key to x secret key.
|
||||
* @example
|
||||
* Converts ed secret key to x secret key.
|
||||
*
|
||||
* ```js
|
||||
* const someonesPub = x25519.getPublicKey(x25519.utils.randomSecretKey());
|
||||
* const aPriv_ed = ed25519.utils.randomSecretKey();
|
||||
* const aPriv = ed25519.utils.toMontgomerySecret(aPriv_ed);
|
||||
* const shared = x25519.getSharedSecret(aPriv, someonesPub)
|
||||
* ```
|
||||
*/
|
||||
toMontgomerySecret: (secretKey: TArg<Uint8Array>) => TRet<Uint8Array>;
|
||||
/** Return the expanded private key components used by RFC8032 signing. */
|
||||
getExtendedPublicKey: (key: TArg<Uint8Array>) => {
|
||||
head: TRet<Uint8Array>;
|
||||
prefix: TRet<Uint8Array>;
|
||||
scalar: bigint;
|
||||
point: EdwardsPoint;
|
||||
pointBytes: TRet<Uint8Array>;
|
||||
};
|
||||
};
|
||||
/** Byte lengths for keys and signatures exposed by this scheme. */
|
||||
lengths: CurveLengths;
|
||||
}
|
||||
/**
|
||||
* @param params - Curve parameters. See {@link EdwardsOpts}.
|
||||
* @param extraOpts - Optional helpers and overrides. See {@link EdwardsExtraOpts}.
|
||||
* @returns Edwards point constructor. Generator validation here only checks
|
||||
* that `(Gx, Gy)` satisfies the affine Edwards equation.
|
||||
* RFC 8032 base-point constraints like `B != (0,1)` and `[L]B = 0`
|
||||
* are left to the caller's chosen parameters, since eager subgroup
|
||||
* validation here adds about 10-15ms to heavyweight imports like ed448.
|
||||
* The returned constructor also eagerly marks `Point.BASE` for W=8
|
||||
* precompute caching. Some code paths still assume
|
||||
* `Fp.BYTES === Fn.BYTES`, so mismatched byte lengths are not fully audited here.
|
||||
* @throws If the curve parameters or Edwards overrides are invalid. {@link Error}
|
||||
* @example
|
||||
* ```ts
|
||||
* import { edwards } from '@noble/curves/abstract/edwards.js';
|
||||
* import { jubjub } from '@noble/curves/misc.js';
|
||||
* // Build a point constructor from explicit curve parameters, then use its base point.
|
||||
* const Point = edwards(jubjub.Point.CURVE());
|
||||
* Point.BASE.toHex();
|
||||
* ```
|
||||
*/
|
||||
export declare function edwards(params: TArg<EdwardsOpts>, extraOpts?: TArg<EdwardsExtraOpts>): EdwardsPointCons;
|
||||
/**
|
||||
* Base class for prime-order points like Ristretto255 and Decaf448.
|
||||
* These points eliminate cofactor issues by representing equivalence classes
|
||||
* of Edwards curve points. Multiple Edwards representatives can describe the
|
||||
* same abstract wrapper element, so wrapper validity is not the same thing as
|
||||
* the hidden representative being torsion-free.
|
||||
* @param ep - Backing Edwards point.
|
||||
* @example
|
||||
* Base class for prime-order points like Ristretto255 and Decaf448.
|
||||
*
|
||||
* ```ts
|
||||
* import { ristretto255 } from '@noble/curves/ed25519.js';
|
||||
* const point = ristretto255.Point.BASE.multiply(2n);
|
||||
* ```
|
||||
*/
|
||||
export declare abstract class PrimeEdwardsPoint<T extends PrimeEdwardsPoint<T>> implements CurvePoint<bigint, T> {
|
||||
static BASE: PrimeEdwardsPoint<any>;
|
||||
static ZERO: PrimeEdwardsPoint<any>;
|
||||
static Fp: IField<bigint>;
|
||||
static Fn: IField<bigint>;
|
||||
protected readonly ep: EdwardsPoint;
|
||||
/**
|
||||
* Wrap one internal Edwards representative directly.
|
||||
* This is not a canonical encoding boundary: alternate Edwards
|
||||
* representatives may still describe the same abstract wrapper element.
|
||||
*/
|
||||
constructor(ep: EdwardsPoint);
|
||||
abstract toBytes(): Uint8Array;
|
||||
abstract equals(other: T): boolean;
|
||||
static fromBytes(_bytes: Uint8Array): any;
|
||||
static fromHex(_hex: string): any;
|
||||
get x(): bigint;
|
||||
get y(): bigint;
|
||||
clearCofactor(): T;
|
||||
assertValidity(): void;
|
||||
/**
|
||||
* Return affine coordinates of the current internal Edwards representative.
|
||||
* This is a convenience helper, not a canonical Ristretto/Decaf encoding.
|
||||
* Equal abstract elements may expose different `x` / `y`; use
|
||||
* `toBytes()` / `fromBytes()` for canonical roundtrips.
|
||||
*/
|
||||
toAffine(invertedZ?: bigint): AffinePoint<bigint>;
|
||||
toHex(): string;
|
||||
toString(): string;
|
||||
isTorsionFree(): boolean;
|
||||
isSmallOrder(): boolean;
|
||||
add(other: T): T;
|
||||
subtract(other: T): T;
|
||||
multiply(scalar: bigint): T;
|
||||
multiplyUnsafe(scalar: bigint): T;
|
||||
double(): T;
|
||||
negate(): T;
|
||||
precompute(windowSize?: number, isLazy?: boolean): T;
|
||||
abstract is0(): boolean;
|
||||
protected abstract assertSame(other: T): void;
|
||||
protected abstract init(ep: EdwardsPoint): T;
|
||||
}
|
||||
/**
|
||||
* Initializes EdDSA signatures over given Edwards curve.
|
||||
* @param Point - Edwards point constructor.
|
||||
* @param cHash - Hash function.
|
||||
* @param eddsaOpts - Optional signature helpers. See {@link EdDSAOpts}.
|
||||
* @returns EdDSA helper namespace.
|
||||
* @throws If the hash function, options, or derived point operations are invalid. {@link Error}
|
||||
* @example
|
||||
* Initializes EdDSA signatures over given Edwards curve.
|
||||
*
|
||||
* ```ts
|
||||
* import { eddsa } from '@noble/curves/abstract/edwards.js';
|
||||
* import { jubjub } from '@noble/curves/misc.js';
|
||||
* import { sha512 } from '@noble/hashes/sha2.js';
|
||||
* const sigs = eddsa(jubjub.Point, sha512);
|
||||
* const { secretKey, publicKey } = sigs.keygen();
|
||||
* const msg = new TextEncoder().encode('hello noble');
|
||||
* const sig = sigs.sign(msg, secretKey);
|
||||
* const isValid = sigs.verify(sig, msg, publicKey);
|
||||
* ```
|
||||
*/
|
||||
export declare function eddsa(Point: EdwardsPointCons, cHash: TArg<FHash>, eddsaOpts?: TArg<EdDSAOpts>): EdDSA;
|
||||
//# sourceMappingURL=edwards.d.ts.map
|
||||
1
node_modules/@noble/curves/abstract/edwards.d.ts.map
generated
vendored
Normal file
1
node_modules/@noble/curves/abstract/edwards.d.ts.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
693
node_modules/@noble/curves/abstract/edwards.js
generated
vendored
Normal file
693
node_modules/@noble/curves/abstract/edwards.js
generated
vendored
Normal file
@@ -0,0 +1,693 @@
|
||||
/**
|
||||
* Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y².
|
||||
* For design rationale of types / exports, see weierstrass module documentation.
|
||||
* Untwisted Edwards curves exist, but they aren't used in real-world protocols.
|
||||
* @module
|
||||
*/
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
import { abool, abytes, aInRange, asafenumber, bytesToHex, bytesToNumberLE, concatBytes, copyBytes, hexToBytes, isBytes, notImplemented, validateObject, randomBytes as wcRandomBytes, } from "../utils.js";
|
||||
import { createCurveFields, createKeygen, normalizeZ, wNAF, } from "./curve.js";
|
||||
import {} from "./modular.js";
|
||||
// Be friendly to bad ECMAScript parsers by not using bigint literals
|
||||
// prettier-ignore
|
||||
const _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _8n = /* @__PURE__ */ BigInt(8);
|
||||
// Affine Edwards-equation check only; this does not prove subgroup membership, canonical
|
||||
// encoding, prime-order base-point requirements, or identity exclusion.
|
||||
function isEdValidXY(Fp, CURVE, x, y) {
|
||||
const x2 = Fp.sqr(x);
|
||||
const y2 = Fp.sqr(y);
|
||||
const left = Fp.add(Fp.mul(CURVE.a, x2), y2);
|
||||
const right = Fp.add(Fp.ONE, Fp.mul(CURVE.d, Fp.mul(x2, y2)));
|
||||
return Fp.eql(left, right);
|
||||
}
|
||||
/**
|
||||
* @param params - Curve parameters. See {@link EdwardsOpts}.
|
||||
* @param extraOpts - Optional helpers and overrides. See {@link EdwardsExtraOpts}.
|
||||
* @returns Edwards point constructor. Generator validation here only checks
|
||||
* that `(Gx, Gy)` satisfies the affine Edwards equation.
|
||||
* RFC 8032 base-point constraints like `B != (0,1)` and `[L]B = 0`
|
||||
* are left to the caller's chosen parameters, since eager subgroup
|
||||
* validation here adds about 10-15ms to heavyweight imports like ed448.
|
||||
* The returned constructor also eagerly marks `Point.BASE` for W=8
|
||||
* precompute caching. Some code paths still assume
|
||||
* `Fp.BYTES === Fn.BYTES`, so mismatched byte lengths are not fully audited here.
|
||||
* @throws If the curve parameters or Edwards overrides are invalid. {@link Error}
|
||||
* @example
|
||||
* ```ts
|
||||
* import { edwards } from '@noble/curves/abstract/edwards.js';
|
||||
* import { jubjub } from '@noble/curves/misc.js';
|
||||
* // Build a point constructor from explicit curve parameters, then use its base point.
|
||||
* const Point = edwards(jubjub.Point.CURVE());
|
||||
* Point.BASE.toHex();
|
||||
* ```
|
||||
*/
|
||||
export function edwards(params, extraOpts = {}) {
|
||||
const opts = extraOpts;
|
||||
const validated = createCurveFields('edwards', params, opts, opts.FpFnLE);
|
||||
const { Fp, Fn } = validated;
|
||||
let CURVE = validated.CURVE;
|
||||
const { h: cofactor } = CURVE;
|
||||
validateObject(opts, {}, { uvRatio: 'function' });
|
||||
// Important:
|
||||
// There are some places where Fp.BYTES is used instead of nByteLength.
|
||||
// So far, everything has been tested with curves of Fp.BYTES == nByteLength.
|
||||
// TODO: test and find curves which behave otherwise.
|
||||
const MASK = _2n << (BigInt(Fn.BYTES * 8) - _1n);
|
||||
const modP = (n) => Fp.create(n); // Function overrides
|
||||
// sqrt(u/v)
|
||||
const uvRatio = opts.uvRatio === undefined
|
||||
? (u, v) => {
|
||||
try {
|
||||
return { isValid: true, value: Fp.sqrt(Fp.div(u, v)) };
|
||||
}
|
||||
catch (e) {
|
||||
return { isValid: false, value: _0n };
|
||||
}
|
||||
}
|
||||
: opts.uvRatio;
|
||||
// Validate whether the passed curve params are valid.
|
||||
// equation ax² + y² = 1 + dx²y² should work for generator point.
|
||||
if (!isEdValidXY(Fp, CURVE, CURVE.Gx, CURVE.Gy))
|
||||
throw new Error('bad curve params: generator point');
|
||||
/**
|
||||
* Asserts coordinate is valid: 0 <= n < MASK.
|
||||
* Coordinates >= Fp.ORDER are allowed for zip215.
|
||||
*/
|
||||
function acoord(title, n, banZero = false) {
|
||||
const min = banZero ? _1n : _0n;
|
||||
aInRange('coordinate ' + title, n, min, MASK);
|
||||
return n;
|
||||
}
|
||||
function aedpoint(other) {
|
||||
if (!(other instanceof Point))
|
||||
throw new Error('EdwardsPoint expected');
|
||||
}
|
||||
// Extended Point works in extended coordinates: (X, Y, Z, T) ∋ (x=X/Z, y=Y/Z, T=xy).
|
||||
// https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates
|
||||
class Point {
|
||||
// base / generator point
|
||||
static BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));
|
||||
// zero / infinity / identity point
|
||||
static ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0
|
||||
// math field
|
||||
static Fp = Fp;
|
||||
// scalar field
|
||||
static Fn = Fn;
|
||||
X;
|
||||
Y;
|
||||
Z;
|
||||
T;
|
||||
constructor(X, Y, Z, T) {
|
||||
this.X = acoord('x', X);
|
||||
this.Y = acoord('y', Y);
|
||||
this.Z = acoord('z', Z, true);
|
||||
this.T = acoord('t', T);
|
||||
Object.freeze(this);
|
||||
}
|
||||
static CURVE() {
|
||||
return CURVE;
|
||||
}
|
||||
/**
|
||||
* Create one extended Edwards point from affine coordinates.
|
||||
* Does NOT validate that the point is on-curve or torsion-free.
|
||||
* Use `.assertValidity()` on adversarial inputs.
|
||||
*/
|
||||
static fromAffine(p) {
|
||||
if (p instanceof Point)
|
||||
throw new Error('extended point not allowed');
|
||||
const { x, y } = p || {};
|
||||
acoord('x', x);
|
||||
acoord('y', y);
|
||||
return new Point(x, y, _1n, modP(x * y));
|
||||
}
|
||||
// Uses algo from RFC8032 5.1.3.
|
||||
static fromBytes(bytes, zip215 = false) {
|
||||
const len = Fp.BYTES;
|
||||
const { a, d } = CURVE;
|
||||
bytes = copyBytes(abytes(bytes, len, 'point'));
|
||||
abool(zip215, 'zip215');
|
||||
const normed = copyBytes(bytes); // copy again, we'll manipulate it
|
||||
const lastByte = bytes[len - 1]; // select last byte
|
||||
normed[len - 1] = lastByte & ~0x80; // clear last bit
|
||||
const y = bytesToNumberLE(normed);
|
||||
// zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.
|
||||
// RFC8032 prohibits >= p, but ZIP215 doesn't
|
||||
// zip215=true: 0 <= y < MASK (2^256 for ed25519)
|
||||
// zip215=false: 0 <= y < P (2^255-19 for ed25519)
|
||||
const max = zip215 ? MASK : Fp.ORDER;
|
||||
aInRange('point.y', y, _0n, max);
|
||||
// Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case:
|
||||
// ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a)
|
||||
const y2 = modP(y * y); // denominator is always non-0 mod p.
|
||||
const u = modP(y2 - _1n); // u = y² - 1
|
||||
const v = modP(d * y2 - a); // v = d y² + 1.
|
||||
let { isValid, value: x } = uvRatio(u, v); // √(u/v)
|
||||
if (!isValid)
|
||||
throw new Error('bad point: invalid y coordinate');
|
||||
const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper
|
||||
const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit
|
||||
if (!zip215 && x === _0n && isLastByteOdd)
|
||||
// if x=0 and x_0 = 1, fail
|
||||
throw new Error('bad point: x=0 and x_0=1');
|
||||
if (isLastByteOdd !== isXOdd)
|
||||
x = modP(-x); // if x_0 != x mod 2, set x = p-x
|
||||
return Point.fromAffine({ x, y });
|
||||
}
|
||||
static fromHex(hex, zip215 = false) {
|
||||
return Point.fromBytes(hexToBytes(hex), zip215);
|
||||
}
|
||||
get x() {
|
||||
return this.toAffine().x;
|
||||
}
|
||||
get y() {
|
||||
return this.toAffine().y;
|
||||
}
|
||||
precompute(windowSize = 8, isLazy = true) {
|
||||
wnaf.createCache(this, windowSize);
|
||||
if (!isLazy)
|
||||
this.multiply(_2n); // random number
|
||||
return this;
|
||||
}
|
||||
// Useful in fromAffine() - not for fromBytes(), which always created valid points.
|
||||
assertValidity() {
|
||||
const p = this;
|
||||
const { a, d } = CURVE;
|
||||
// Keep generic Edwards validation fail-closed on the neutral point.
|
||||
// Even though ZERO is algebraically valid and can roundtrip through encodings, higher-level
|
||||
// callers often reach it only through broken hash/scalar plumbing; rejecting it here avoids
|
||||
// silently treating that degenerate state as an ordinary public point.
|
||||
if (p.is0())
|
||||
throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?
|
||||
// Equation in affine coordinates: ax² + y² = 1 + dx²y²
|
||||
// Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²
|
||||
const { X, Y, Z, T } = p;
|
||||
const X2 = modP(X * X); // X²
|
||||
const Y2 = modP(Y * Y); // Y²
|
||||
const Z2 = modP(Z * Z); // Z²
|
||||
const Z4 = modP(Z2 * Z2); // Z⁴
|
||||
const aX2 = modP(X2 * a); // aX²
|
||||
const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z²
|
||||
const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y²
|
||||
if (left !== right)
|
||||
throw new Error('bad point: equation left != right (1)');
|
||||
// In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T
|
||||
const XY = modP(X * Y);
|
||||
const ZT = modP(Z * T);
|
||||
if (XY !== ZT)
|
||||
throw new Error('bad point: equation left != right (2)');
|
||||
}
|
||||
// Compare one point to another.
|
||||
equals(other) {
|
||||
aedpoint(other);
|
||||
const { X: X1, Y: Y1, Z: Z1 } = this;
|
||||
const { X: X2, Y: Y2, Z: Z2 } = other;
|
||||
const X1Z2 = modP(X1 * Z2);
|
||||
const X2Z1 = modP(X2 * Z1);
|
||||
const Y1Z2 = modP(Y1 * Z2);
|
||||
const Y2Z1 = modP(Y2 * Z1);
|
||||
return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
|
||||
}
|
||||
is0() {
|
||||
return this.equals(Point.ZERO);
|
||||
}
|
||||
negate() {
|
||||
// Flips point sign to a negative one (-x, y in affine coords)
|
||||
return new Point(modP(-this.X), this.Y, this.Z, modP(-this.T));
|
||||
}
|
||||
// Fast algo for doubling Extended Point.
|
||||
// https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd
|
||||
// Cost: 4M + 4S + 1*a + 6add + 1*2.
|
||||
double() {
|
||||
const { a } = CURVE;
|
||||
const { X: X1, Y: Y1, Z: Z1 } = this;
|
||||
const A = modP(X1 * X1); // A = X12
|
||||
const B = modP(Y1 * Y1); // B = Y12
|
||||
const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12
|
||||
const D = modP(a * A); // D = a*A
|
||||
const x1y1 = X1 + Y1;
|
||||
const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B
|
||||
const G = D + B; // G = D+B
|
||||
const F = G - C; // F = G-C
|
||||
const H = D - B; // H = D-B
|
||||
const X3 = modP(E * F); // X3 = E*F
|
||||
const Y3 = modP(G * H); // Y3 = G*H
|
||||
const T3 = modP(E * H); // T3 = E*H
|
||||
const Z3 = modP(F * G); // Z3 = F*G
|
||||
return new Point(X3, Y3, Z3, T3);
|
||||
}
|
||||
// Fast algo for adding 2 Extended Points.
|
||||
// https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd
|
||||
// Cost: 9M + 1*a + 1*d + 7add.
|
||||
add(other) {
|
||||
aedpoint(other);
|
||||
const { a, d } = CURVE;
|
||||
const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
|
||||
const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;
|
||||
const A = modP(X1 * X2); // A = X1*X2
|
||||
const B = modP(Y1 * Y2); // B = Y1*Y2
|
||||
const C = modP(T1 * d * T2); // C = T1*d*T2
|
||||
const D = modP(Z1 * Z2); // D = Z1*Z2
|
||||
const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B
|
||||
const F = D - C; // F = D-C
|
||||
const G = D + C; // G = D+C
|
||||
const H = modP(B - a * A); // H = B-a*A
|
||||
const X3 = modP(E * F); // X3 = E*F
|
||||
const Y3 = modP(G * H); // Y3 = G*H
|
||||
const T3 = modP(E * H); // T3 = E*H
|
||||
const Z3 = modP(F * G); // Z3 = F*G
|
||||
return new Point(X3, Y3, Z3, T3);
|
||||
}
|
||||
subtract(other) {
|
||||
// Validate before calling `negate()` so wrong inputs fail with the point guard
|
||||
// instead of leaking a foreign `negate()` error.
|
||||
aedpoint(other);
|
||||
return this.add(other.negate());
|
||||
}
|
||||
// Constant-time multiplication.
|
||||
multiply(scalar) {
|
||||
// 1 <= scalar < L
|
||||
// Keep the subgroup-scalar contract strict instead of reducing 0 / n to ZERO.
|
||||
// In keygen/signing-style callers, those values usually mean broken hash/scalar plumbing,
|
||||
// and failing closed is safer than silently producing the identity point.
|
||||
if (!Fn.isValidNot0(scalar))
|
||||
throw new RangeError('invalid scalar: expected 1 <= sc < curve.n');
|
||||
const { p, f } = wnaf.cached(this, scalar, (p) => normalizeZ(Point, p));
|
||||
return normalizeZ(Point, [p, f])[0];
|
||||
}
|
||||
// Non-constant-time multiplication. Uses double-and-add algorithm.
|
||||
// It's faster, but should only be used when you don't care about
|
||||
// an exposed private key e.g. sig verification.
|
||||
// Keeps the same subgroup-scalar contract: 0 is allowed for public-scalar callers, but
|
||||
// n and larger values are rejected instead of being reduced mod n to the identity point.
|
||||
multiplyUnsafe(scalar) {
|
||||
// 0 <= scalar < L
|
||||
if (!Fn.isValid(scalar))
|
||||
throw new RangeError('invalid scalar: expected 0 <= sc < curve.n');
|
||||
if (scalar === _0n)
|
||||
return Point.ZERO;
|
||||
if (this.is0() || scalar === _1n)
|
||||
return this;
|
||||
return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p));
|
||||
}
|
||||
// Checks if point is of small order.
|
||||
// If you add something to small order point, you will have "dirty"
|
||||
// point with torsion component.
|
||||
// Clears cofactor and checks if the result is 0.
|
||||
isSmallOrder() {
|
||||
return this.clearCofactor().is0();
|
||||
}
|
||||
// Multiplies point by curve order and checks if the result is 0.
|
||||
// Returns `false` is the point is dirty.
|
||||
isTorsionFree() {
|
||||
return wnaf.unsafe(this, CURVE.n).is0();
|
||||
}
|
||||
// Converts Extended point to default (x, y) coordinates.
|
||||
// Can accept precomputed Z^-1 - for example, from invertBatch.
|
||||
toAffine(invertedZ) {
|
||||
const p = this;
|
||||
let iz = invertedZ;
|
||||
const { X, Y, Z } = p;
|
||||
const is0 = p.is0();
|
||||
if (iz == null)
|
||||
iz = is0 ? _8n : Fp.inv(Z); // 8 was chosen arbitrarily
|
||||
const x = modP(X * iz);
|
||||
const y = modP(Y * iz);
|
||||
const zz = Fp.mul(Z, iz);
|
||||
if (is0)
|
||||
return { x: _0n, y: _1n };
|
||||
if (zz !== _1n)
|
||||
throw new Error('invZ was invalid');
|
||||
return { x, y };
|
||||
}
|
||||
clearCofactor() {
|
||||
if (cofactor === _1n)
|
||||
return this;
|
||||
return this.multiplyUnsafe(cofactor);
|
||||
}
|
||||
toBytes() {
|
||||
const { x, y } = this.toAffine();
|
||||
// Fp.toBytes() allows non-canonical encoding of y (>= p).
|
||||
const bytes = Fp.toBytes(y);
|
||||
// Each y has 2 valid points: (x, y), (x,-y).
|
||||
// When compressing, it's enough to store y and use the last byte to encode sign of x
|
||||
bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0;
|
||||
return bytes;
|
||||
}
|
||||
toHex() {
|
||||
return bytesToHex(this.toBytes());
|
||||
}
|
||||
toString() {
|
||||
return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;
|
||||
}
|
||||
}
|
||||
const wnaf = new wNAF(Point, Fn.BITS);
|
||||
// Keep constructor work cheap: subgroup/generator validation belongs to the caller's curve
|
||||
// parameters, and doing the extra checks here adds about 10-15ms to heavy module imports.
|
||||
// Callers that construct custom curves are responsible for supplying the correct base point.
|
||||
// try {
|
||||
// Point.BASE.assertValidity();
|
||||
// if (!Point.BASE.isTorsionFree()) throw new Error('bad point: not in prime-order subgroup');
|
||||
// } catch {
|
||||
// throw new Error('bad curve params: generator point');
|
||||
// }
|
||||
// Tiny toy curves can have scalar fields narrower than 8 bits. Skip the
|
||||
// eager W=8 cache there instead of rejecting an otherwise valid constructor.
|
||||
if (Fn.BITS >= 8)
|
||||
Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.
|
||||
Object.freeze(Point.prototype);
|
||||
Object.freeze(Point);
|
||||
return Point;
|
||||
}
|
||||
/**
|
||||
* Base class for prime-order points like Ristretto255 and Decaf448.
|
||||
* These points eliminate cofactor issues by representing equivalence classes
|
||||
* of Edwards curve points. Multiple Edwards representatives can describe the
|
||||
* same abstract wrapper element, so wrapper validity is not the same thing as
|
||||
* the hidden representative being torsion-free.
|
||||
* @param ep - Backing Edwards point.
|
||||
* @example
|
||||
* Base class for prime-order points like Ristretto255 and Decaf448.
|
||||
*
|
||||
* ```ts
|
||||
* import { ristretto255 } from '@noble/curves/ed25519.js';
|
||||
* const point = ristretto255.Point.BASE.multiply(2n);
|
||||
* ```
|
||||
*/
|
||||
export class PrimeEdwardsPoint {
|
||||
static BASE;
|
||||
static ZERO;
|
||||
static Fp;
|
||||
static Fn;
|
||||
ep;
|
||||
/**
|
||||
* Wrap one internal Edwards representative directly.
|
||||
* This is not a canonical encoding boundary: alternate Edwards
|
||||
* representatives may still describe the same abstract wrapper element.
|
||||
*/
|
||||
constructor(ep) {
|
||||
this.ep = ep;
|
||||
}
|
||||
// Static methods that must be implemented by subclasses
|
||||
static fromBytes(_bytes) {
|
||||
notImplemented();
|
||||
}
|
||||
static fromHex(_hex) {
|
||||
notImplemented();
|
||||
}
|
||||
get x() {
|
||||
return this.toAffine().x;
|
||||
}
|
||||
get y() {
|
||||
return this.toAffine().y;
|
||||
}
|
||||
// Common implementations
|
||||
clearCofactor() {
|
||||
// no-op for the abstract prime-order wrapper group; this is about the
|
||||
// wrapper element, not the hidden Edwards representative.
|
||||
return this;
|
||||
}
|
||||
assertValidity() {
|
||||
// Keep wrapper validity at the abstract-group boundary. Canonical decode
|
||||
// may choose Edwards representatives that differ by small torsion, so
|
||||
// checking `this.ep.isTorsionFree()` here would reject valid wrapper points.
|
||||
this.ep.assertValidity();
|
||||
}
|
||||
/**
|
||||
* Return affine coordinates of the current internal Edwards representative.
|
||||
* This is a convenience helper, not a canonical Ristretto/Decaf encoding.
|
||||
* Equal abstract elements may expose different `x` / `y`; use
|
||||
* `toBytes()` / `fromBytes()` for canonical roundtrips.
|
||||
*/
|
||||
toAffine(invertedZ) {
|
||||
return this.ep.toAffine(invertedZ);
|
||||
}
|
||||
toHex() {
|
||||
return bytesToHex(this.toBytes());
|
||||
}
|
||||
toString() {
|
||||
return this.toHex();
|
||||
}
|
||||
isTorsionFree() {
|
||||
// Abstract Ristretto/Decaf elements are already prime-order even when the
|
||||
// hidden Edwards representative is not torsion-free.
|
||||
return true;
|
||||
}
|
||||
isSmallOrder() {
|
||||
return false;
|
||||
}
|
||||
add(other) {
|
||||
this.assertSame(other);
|
||||
return this.init(this.ep.add(other.ep));
|
||||
}
|
||||
subtract(other) {
|
||||
this.assertSame(other);
|
||||
return this.init(this.ep.subtract(other.ep));
|
||||
}
|
||||
multiply(scalar) {
|
||||
return this.init(this.ep.multiply(scalar));
|
||||
}
|
||||
multiplyUnsafe(scalar) {
|
||||
return this.init(this.ep.multiplyUnsafe(scalar));
|
||||
}
|
||||
double() {
|
||||
return this.init(this.ep.double());
|
||||
}
|
||||
negate() {
|
||||
return this.init(this.ep.negate());
|
||||
}
|
||||
precompute(windowSize, isLazy) {
|
||||
this.ep.precompute(windowSize, isLazy);
|
||||
// Keep the wrapper identity stable like the backing Edwards API instead of
|
||||
// allocating a fresh wrapper around the same cached point.
|
||||
return this;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Initializes EdDSA signatures over given Edwards curve.
|
||||
* @param Point - Edwards point constructor.
|
||||
* @param cHash - Hash function.
|
||||
* @param eddsaOpts - Optional signature helpers. See {@link EdDSAOpts}.
|
||||
* @returns EdDSA helper namespace.
|
||||
* @throws If the hash function, options, or derived point operations are invalid. {@link Error}
|
||||
* @example
|
||||
* Initializes EdDSA signatures over given Edwards curve.
|
||||
*
|
||||
* ```ts
|
||||
* import { eddsa } from '@noble/curves/abstract/edwards.js';
|
||||
* import { jubjub } from '@noble/curves/misc.js';
|
||||
* import { sha512 } from '@noble/hashes/sha2.js';
|
||||
* const sigs = eddsa(jubjub.Point, sha512);
|
||||
* const { secretKey, publicKey } = sigs.keygen();
|
||||
* const msg = new TextEncoder().encode('hello noble');
|
||||
* const sig = sigs.sign(msg, secretKey);
|
||||
* const isValid = sigs.verify(sig, msg, publicKey);
|
||||
* ```
|
||||
*/
|
||||
export function eddsa(Point, cHash, eddsaOpts = {}) {
|
||||
if (typeof cHash !== 'function')
|
||||
throw new Error('"hash" function param is required');
|
||||
const hash = cHash;
|
||||
const opts = eddsaOpts;
|
||||
validateObject(opts, {}, {
|
||||
adjustScalarBytes: 'function',
|
||||
randomBytes: 'function',
|
||||
domain: 'function',
|
||||
prehash: 'function',
|
||||
zip215: 'boolean',
|
||||
mapToCurve: 'function',
|
||||
});
|
||||
const { prehash } = opts;
|
||||
const { BASE, Fp, Fn } = Point;
|
||||
const outputLen = hash.outputLen;
|
||||
const expectedLen = 2 * Fp.BYTES;
|
||||
// When hash metadata is available, reject incompatible EdDSA wrappers at construction time
|
||||
// instead of deferring the mismatch until the first keygen/sign call.
|
||||
if (outputLen !== undefined) {
|
||||
asafenumber(outputLen, 'hash.outputLen');
|
||||
if (outputLen !== expectedLen)
|
||||
throw new Error(`hash.outputLen must be ${expectedLen}, got ${outputLen}`);
|
||||
}
|
||||
const randomBytes = opts.randomBytes === undefined ? wcRandomBytes : opts.randomBytes;
|
||||
const adjustScalarBytes = opts.adjustScalarBytes === undefined
|
||||
? (bytes) => bytes
|
||||
: opts.adjustScalarBytes;
|
||||
const domain = opts.domain === undefined
|
||||
? (data, ctx, phflag) => {
|
||||
abool(phflag, 'phflag');
|
||||
if (ctx.length || phflag)
|
||||
throw new Error('Contexts/pre-hash are not supported');
|
||||
return data;
|
||||
}
|
||||
: opts.domain; // NOOP
|
||||
// Parse an EdDSA digest as a little-endian integer and reduce it modulo the scalar field order.
|
||||
function modN_LE(hash) {
|
||||
return Fn.create(bytesToNumberLE(hash)); // Not Fn.fromBytes: it has length limit
|
||||
}
|
||||
// Get the hashed private scalar per RFC8032 5.1.5
|
||||
function getPrivateScalar(key) {
|
||||
const len = lengths.secretKey;
|
||||
abytes(key, lengths.secretKey, 'secretKey');
|
||||
// Hash private key with curve's hash function to produce uniformingly random input
|
||||
// Check byte lengths: ensure(64, h(ensure(32, key)))
|
||||
const hashed = abytes(hash(key), 2 * len, 'hashedSecretKey');
|
||||
// Slice before clamping so in-place adjustors don't corrupt the prefix half.
|
||||
const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE
|
||||
const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)
|
||||
const scalar = modN_LE(head); // The actual private scalar
|
||||
return { head, prefix, scalar };
|
||||
}
|
||||
/** Convenience method that creates public key from scalar. RFC8032 5.1.5
|
||||
* Also exposes the derived scalar/prefix tuple and point form reused by sign().
|
||||
*/
|
||||
function getExtendedPublicKey(secretKey) {
|
||||
const { head, prefix, scalar } = getPrivateScalar(secretKey);
|
||||
const point = BASE.multiply(scalar); // Point on Edwards curve aka public key
|
||||
const pointBytes = point.toBytes();
|
||||
return { head, prefix, scalar, point, pointBytes };
|
||||
}
|
||||
/** Calculates EdDSA pub key. RFC8032 5.1.5. */
|
||||
function getPublicKey(secretKey) {
|
||||
return getExtendedPublicKey(secretKey).pointBytes;
|
||||
}
|
||||
// Hash domain-separated chunks into a little-endian scalar modulo the group order.
|
||||
function hashDomainToScalar(context = Uint8Array.of(), ...msgs) {
|
||||
const msg = concatBytes(...msgs);
|
||||
return modN_LE(hash(domain(msg, abytes(context, undefined, 'context'), !!prehash)));
|
||||
}
|
||||
/** Signs message with secret key. RFC8032 5.1.6 */
|
||||
function sign(msg, secretKey, options = {}) {
|
||||
msg = abytes(msg, undefined, 'message');
|
||||
if (prehash)
|
||||
msg = prehash(msg); // for ed25519ph etc.
|
||||
const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);
|
||||
const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)
|
||||
// RFC 8032 5.1.6 allows r mod L = 0, and SUPERCOP ref10 accepts the resulting identity-point
|
||||
// signature.
|
||||
// We intentionally keep the safe multiply() rejection here so a miswired all-zero hash provider
|
||||
// fails loudly instead of silently producing a degenerate signature.
|
||||
const R = BASE.multiply(r).toBytes(); // R = rG
|
||||
const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)
|
||||
const s = Fn.create(r + k * scalar); // S = (r + k * s) mod L
|
||||
if (!Fn.isValid(s))
|
||||
throw new Error('sign failed: invalid s'); // 0 <= s < L
|
||||
const rs = concatBytes(R, Fn.toBytes(s));
|
||||
return abytes(rs, lengths.signature, 'result');
|
||||
}
|
||||
// Keep the shared helper strict by default: RFC 8032 / NIST-style wrappers should reject
|
||||
// non-canonical encodings unless they explicitly opt into ZIP-215's more permissive decode rules.
|
||||
const verifyOpts = {
|
||||
zip215: opts.zip215,
|
||||
};
|
||||
/**
|
||||
* Verifies EdDSA signature against message and public key. RFC 8032 §§5.1.7 and 5.2.7.
|
||||
* A cofactored verification equation is checked.
|
||||
*/
|
||||
function verify(sig, msg, publicKey, options = verifyOpts) {
|
||||
// Preserve the wrapper-selected default for `{}` / `{ zip215: undefined }`, not just omitted opts.
|
||||
const { context } = options;
|
||||
const zip215 = options.zip215 === undefined ? !!verifyOpts.zip215 : options.zip215;
|
||||
const len = lengths.signature;
|
||||
sig = abytes(sig, len, 'signature');
|
||||
msg = abytes(msg, undefined, 'message');
|
||||
publicKey = abytes(publicKey, lengths.publicKey, 'publicKey');
|
||||
if (zip215 !== undefined)
|
||||
abool(zip215, 'zip215');
|
||||
if (prehash)
|
||||
msg = prehash(msg); // for ed25519ph, etc
|
||||
const mid = len / 2;
|
||||
const r = sig.subarray(0, mid);
|
||||
const s = bytesToNumberLE(sig.subarray(mid, len));
|
||||
let A, R, SB;
|
||||
try {
|
||||
// ZIP-215 is more permissive than RFC 8032 / NIST186-5. Use it only for wrappers that
|
||||
// explicitly want consensus-style unreduced encoding acceptance.
|
||||
// zip215=true: 0 <= y < MASK (2^256 for ed25519)
|
||||
// zip215=false: 0 <= y < P (2^255-19 for ed25519)
|
||||
A = Point.fromBytes(publicKey, zip215);
|
||||
R = Point.fromBytes(r, zip215);
|
||||
SB = BASE.multiplyUnsafe(s); // 0 <= s < l is done inside
|
||||
}
|
||||
catch (error) {
|
||||
return false;
|
||||
}
|
||||
// RFC 8032 §§5.1.7/5.2.7 and FIPS 186-5 §§7.7.2/7.8.2 only decode A' and check the cofactored
|
||||
// verification equation; they do not add a separate low-order-public-key rejection here.
|
||||
// Strict mode still rejects small-order A' intentionally for SBS-style non-repudiation and to
|
||||
// avoid ambiguous verification outcomes where unusual low-order keys can make distinct
|
||||
// key/signature/message combinations verify.
|
||||
if (!zip215 && A.isSmallOrder())
|
||||
return false;
|
||||
// ZIP-215 accepts noncanonical / unreduced point encodings, so the challenge hash must use the
|
||||
// exact signature/public-key bytes rather than canonicalized re-encodings of the decoded points.
|
||||
const k = hashDomainToScalar(context, r, publicKey, msg);
|
||||
const RkA = R.add(A.multiplyUnsafe(k));
|
||||
// Check the cofactored verification equation via the curve cofactor h.
|
||||
// [h][S]B = [h]R + [h][k]A'
|
||||
return RkA.subtract(SB).clearCofactor().is0();
|
||||
}
|
||||
const _size = Fp.BYTES; // 32 for ed25519, 57 for ed448
|
||||
const lengths = {
|
||||
secretKey: _size,
|
||||
publicKey: _size,
|
||||
signature: 2 * _size,
|
||||
seed: _size,
|
||||
};
|
||||
function randomSecretKey(seed) {
|
||||
seed = seed === undefined ? randomBytes(lengths.seed) : seed;
|
||||
return abytes(seed, lengths.seed, 'seed');
|
||||
}
|
||||
function isValidSecretKey(key) {
|
||||
return isBytes(key) && key.length === lengths.secretKey;
|
||||
}
|
||||
function isValidPublicKey(key, zip215) {
|
||||
try {
|
||||
// Preserve the wrapper-selected default for omitted / `undefined` ZIP-215 flags here too.
|
||||
return !!Point.fromBytes(key, zip215 === undefined ? verifyOpts.zip215 : zip215);
|
||||
}
|
||||
catch (error) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
const utils = {
|
||||
getExtendedPublicKey,
|
||||
randomSecretKey,
|
||||
isValidSecretKey,
|
||||
isValidPublicKey,
|
||||
/**
|
||||
* Converts ed public key to x public key. Uses formula:
|
||||
* - ed25519:
|
||||
* - `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`
|
||||
* - `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`
|
||||
* - ed448:
|
||||
* - `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)`
|
||||
* - `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))`
|
||||
*/
|
||||
toMontgomery(publicKey) {
|
||||
const { y } = Point.fromBytes(publicKey);
|
||||
const size = lengths.publicKey;
|
||||
const is25519 = size === 32;
|
||||
if (!is25519 && size !== 57)
|
||||
throw new Error('only defined for 25519 and 448');
|
||||
const u = is25519 ? Fp.div(_1n + y, _1n - y) : Fp.div(y - _1n, y + _1n);
|
||||
return Fp.toBytes(u);
|
||||
},
|
||||
toMontgomerySecret(secretKey) {
|
||||
const size = lengths.secretKey;
|
||||
abytes(secretKey, size);
|
||||
const hashed = hash(secretKey.subarray(0, size));
|
||||
return adjustScalarBytes(hashed).subarray(0, size);
|
||||
},
|
||||
};
|
||||
Object.freeze(lengths);
|
||||
Object.freeze(utils);
|
||||
return Object.freeze({
|
||||
keygen: createKeygen(randomSecretKey, getPublicKey),
|
||||
getPublicKey,
|
||||
sign,
|
||||
verify,
|
||||
utils,
|
||||
Point,
|
||||
lengths,
|
||||
});
|
||||
}
|
||||
//# sourceMappingURL=edwards.js.map
|
||||
1
node_modules/@noble/curves/abstract/edwards.js.map
generated
vendored
Normal file
1
node_modules/@noble/curves/abstract/edwards.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
439
node_modules/@noble/curves/abstract/fft.d.ts
generated
vendored
Normal file
439
node_modules/@noble/curves/abstract/fft.d.ts
generated
vendored
Normal file
@@ -0,0 +1,439 @@
|
||||
/**
|
||||
* Experimental implementation of NTT / FFT (Fast Fourier Transform) over finite fields.
|
||||
* API may change at any time. The code has not been audited. Feature requests are welcome.
|
||||
* @module
|
||||
*/
|
||||
import type { TArg } from '../utils.ts';
|
||||
import type { IField } from './modular.ts';
|
||||
/** Array-like coefficient storage that can be mutated in place. */
|
||||
export interface MutableArrayLike<T> {
|
||||
/** Element access by numeric index. */
|
||||
[index: number]: T;
|
||||
/** Current amount of stored coefficients. */
|
||||
length: number;
|
||||
/**
|
||||
* Return a sliced copy using the same storage shape.
|
||||
* @param start - Inclusive start index.
|
||||
* @param end - Exclusive end index.
|
||||
* @returns Sliced copy.
|
||||
*/
|
||||
slice(start?: number, end?: number): this;
|
||||
/**
|
||||
* Iterate over stored coefficients in order.
|
||||
* @returns Coefficient iterator.
|
||||
*/
|
||||
[Symbol.iterator](): Iterator<T>;
|
||||
}
|
||||
/**
|
||||
* Concrete polynomial containers accepted by the high-level `poly(...)` helpers.
|
||||
* Lower-level FFT helpers can work with structural `MutableArrayLike`, but `poly(...)`
|
||||
* intentionally keeps runtime dispatch on plain arrays and typed-array views.
|
||||
*/
|
||||
export type PolyStorage<T> = T[] | (MutableArrayLike<T> & ArrayBufferView);
|
||||
/**
|
||||
* Checks if integer is in form of `1 << X`.
|
||||
* @param x - Integer to inspect.
|
||||
* @returns `true` when the value is a power of two.
|
||||
* @throws If `x` is not a valid unsigned 32-bit integer. {@link Error}
|
||||
* @example
|
||||
* Validate that an FFT size is a power of two.
|
||||
*
|
||||
* ```ts
|
||||
* isPowerOfTwo(8);
|
||||
* ```
|
||||
*/
|
||||
export declare function isPowerOfTwo(x: number): boolean;
|
||||
/**
|
||||
* @param n - Input value.
|
||||
* @returns Next power of two within the u32/array-length domain.
|
||||
* @throws If `n` is not a valid unsigned 32-bit integer. {@link Error}
|
||||
* @example
|
||||
* Round an integer up to the FFT size it needs.
|
||||
*
|
||||
* ```ts
|
||||
* nextPowerOfTwo(9);
|
||||
* ```
|
||||
*/
|
||||
export declare function nextPowerOfTwo(n: number): number;
|
||||
/**
|
||||
* @param n - Value to reverse.
|
||||
* @param bits - Number of bits to use.
|
||||
* @returns Bit-reversed integer.
|
||||
* @throws If `n` is not a valid unsigned 32-bit integer. {@link Error}
|
||||
* @example
|
||||
* Reverse the low `bits` bits of one index.
|
||||
*
|
||||
* ```ts
|
||||
* reverseBits(3, 3);
|
||||
* ```
|
||||
*/
|
||||
export declare function reverseBits(n: number, bits: number): number;
|
||||
/**
|
||||
* Similar to `bitLen(x)-1` but much faster for small integers, like indices.
|
||||
* @param n - Input value.
|
||||
* @returns Base-2 logarithm. For `n = 0`, the current implementation returns `-1`.
|
||||
* @throws If `n` is not a valid unsigned 32-bit integer. {@link Error}
|
||||
* @example
|
||||
* Compute the radix-2 stage count for one transform size.
|
||||
*
|
||||
* ```ts
|
||||
* log2(8);
|
||||
* ```
|
||||
*/
|
||||
export declare function log2(n: number): number;
|
||||
/**
|
||||
* Moves lowest bit to highest position, which at first step splits
|
||||
* array on even and odd indices, then it applied again to each part,
|
||||
* which is core of fft
|
||||
* @param values - Mutable coefficient array.
|
||||
* @returns Mutated input array.
|
||||
* @throws If the array length is not a positive power of two. {@link Error}
|
||||
* @example
|
||||
* Reorder coefficients into bit-reversed order in place.
|
||||
*
|
||||
* ```ts
|
||||
* const values = Uint8Array.from([0, 1, 2, 3]);
|
||||
* bitReversalInplace(values);
|
||||
* ```
|
||||
*/
|
||||
export declare function bitReversalInplace<T extends MutableArrayLike<any>>(values: T): T;
|
||||
/**
|
||||
* @param values - Input values.
|
||||
* @returns Reordered copy.
|
||||
* @throws If the array length is not a positive power of two. {@link Error}
|
||||
* @example
|
||||
* Return a reordered copy instead of mutating the input in place.
|
||||
*
|
||||
* ```ts
|
||||
* const reordered = bitReversalPermutation([0, 1, 2, 3]);
|
||||
* ```
|
||||
*/
|
||||
export declare function bitReversalPermutation<T>(values: T[]): T[];
|
||||
/** Cached roots-of-unity tables derived from one finite field. */
|
||||
export type RootsOfUnity = {
|
||||
/** Generator and 2-adicity metadata for the cached field. */
|
||||
info: {
|
||||
G: bigint;
|
||||
oddFactor: bigint;
|
||||
powerOfTwo: number;
|
||||
};
|
||||
/**
|
||||
* Return the natural-order roots of unity for one radix-2 size.
|
||||
* @param bits - Transform size as `log2(N)`.
|
||||
* @returns Natural-order roots for that size.
|
||||
*/
|
||||
roots: (bits: number) => bigint[];
|
||||
/**
|
||||
* Return the bit-reversal permutation of the roots for one radix-2 size.
|
||||
* @param bits - Transform size as `log2(N)`.
|
||||
* @returns Bit-reversed roots.
|
||||
*/
|
||||
brp(bits: number): bigint[];
|
||||
/**
|
||||
* Return the inverse roots of unity for one radix-2 size.
|
||||
* @param bits - Transform size as `log2(N)`.
|
||||
* @returns Inverse roots.
|
||||
*/
|
||||
inverse(bits: number): bigint[];
|
||||
/**
|
||||
* Return one primitive root used by a radix-2 stage.
|
||||
* @param bits - Transform size as `log2(N)`.
|
||||
* @returns Primitive root for that stage.
|
||||
*/
|
||||
omega: (bits: number) => bigint;
|
||||
/**
|
||||
* Drop all cached root tables.
|
||||
* @returns Nothing.
|
||||
*/
|
||||
clear: () => void;
|
||||
};
|
||||
/**
|
||||
* We limit roots up to 2**31, which is a lot: 2-billion polynomimal should be rare.
|
||||
* @param field - Field implementation.
|
||||
* @param generator - Optional generator override.
|
||||
* @returns Roots-of-unity cache.
|
||||
* @example
|
||||
* Cache roots once, then ask for the omega table of one FFT size.
|
||||
*
|
||||
* ```ts
|
||||
* import { rootsOfUnity } from '@noble/curves/abstract/fft.js';
|
||||
* import { Field } from '@noble/curves/abstract/modular.js';
|
||||
* const roots = rootsOfUnity(Field(17n));
|
||||
* const omega = roots.omega(4);
|
||||
* ```
|
||||
*/
|
||||
export declare function rootsOfUnity(field: TArg<IField<bigint>>, generator?: bigint): RootsOfUnity;
|
||||
/** Polynomial coefficient container used by the FFT helpers. */
|
||||
export type Polynomial<T> = MutableArrayLike<T>;
|
||||
/**
|
||||
* Arithmetic operations used by the generic FFT implementation.
|
||||
*
|
||||
* Maps great to Field<bigint>, but not to Group (EC points):
|
||||
* - inv from scalar field
|
||||
* - we need multiplyUnsafe here, instead of multiply for speed
|
||||
* - multiplyUnsafe is safe in the context: we do mul(rootsOfUnity), which are public and sparse
|
||||
*/
|
||||
export type FFTOpts<T, R> = {
|
||||
/**
|
||||
* Add two coefficients.
|
||||
* @param a - Left coefficient.
|
||||
* @param b - Right coefficient.
|
||||
* @returns Sum coefficient.
|
||||
*/
|
||||
add: (a: T, b: T) => T;
|
||||
/**
|
||||
* Subtract two coefficients.
|
||||
* @param a - Left coefficient.
|
||||
* @param b - Right coefficient.
|
||||
* @returns Difference coefficient.
|
||||
*/
|
||||
sub: (a: T, b: T) => T;
|
||||
/**
|
||||
* Multiply one coefficient by a scalar/root factor.
|
||||
* @param a - Coefficient value.
|
||||
* @param scalar - Scalar/root factor.
|
||||
* @returns Scaled coefficient.
|
||||
*/
|
||||
mul: (a: T, scalar: R) => T;
|
||||
/**
|
||||
* Invert one scalar/root factor.
|
||||
* @param a - Scalar/root factor.
|
||||
* @returns Inverse factor.
|
||||
*/
|
||||
inv: (a: R) => R;
|
||||
};
|
||||
/** Configuration for one low-level FFT loop. */
|
||||
export type FFTCoreOpts<R> = {
|
||||
/** Transform size. Must be a power of two. */
|
||||
N: number;
|
||||
/** Stage roots for the selected transform size. */
|
||||
roots: Polynomial<R>;
|
||||
/** Whether to run the DIT variant instead of DIF. */
|
||||
dit: boolean;
|
||||
/** Whether to invert butterfly placement for decode-oriented layouts. */
|
||||
invertButterflies?: boolean;
|
||||
/** Number of initial stages to skip. */
|
||||
skipStages?: number;
|
||||
/** Whether to apply bit-reversal permutation at the boundary. */
|
||||
brp?: boolean;
|
||||
};
|
||||
/**
|
||||
* Callable low-level FFT loop over one polynomial storage shape.
|
||||
* @param values - Polynomial coefficients to transform in place.
|
||||
* @returns The mutated input polynomial.
|
||||
*/
|
||||
export type FFTCoreLoop<T> = <P extends Polynomial<T>>(values: P) => P;
|
||||
/**
|
||||
* Constructs different flavors of FFT. radix2 implementation of low level mutating API. Flavors:
|
||||
*
|
||||
* - DIT (Decimation-in-Time): Bottom-Up (leaves to root), Cool-Turkey
|
||||
* - DIF (Decimation-in-Frequency): Top-Down (root to leaves), Gentleman-Sande
|
||||
*
|
||||
* DIT takes brp input, returns natural output.
|
||||
* DIF takes natural input, returns brp output.
|
||||
*
|
||||
* The output is actually identical. Time / frequence distinction is not meaningful
|
||||
* for Polynomial multiplication in fields.
|
||||
* Which means if protocol supports/needs brp output/inputs, then we can skip this step.
|
||||
*
|
||||
* Cyclic NTT: Rq = Zq[x]/(x^n-1). butterfly_DIT+loop_DIT OR butterfly_DIF+loop_DIT, roots are omega
|
||||
* Negacyclic NTT: Rq = Zq[x]/(x^n+1). butterfly_DIT+loop_DIF, at least for mlkem / mldsa
|
||||
* @param F - Field operations.
|
||||
* @param coreOpts - FFT configuration:
|
||||
* - `N`: Transform size. Must be a power of two.
|
||||
* - `roots`: Stage roots for the selected transform size.
|
||||
* - `dit`: Whether to run the DIT variant instead of DIF.
|
||||
* - `invertButterflies` (optional): Whether to invert butterfly placement.
|
||||
* - `skipStages` (optional): Number of initial stages to skip.
|
||||
* - `brp` (optional): Whether to apply bit-reversal permutation at the boundary.
|
||||
* @returns Low-level FFT loop.
|
||||
* @throws If the FFT options or cached roots are invalid for the requested size. {@link Error}
|
||||
* @example
|
||||
* Constructs different flavors of FFT.
|
||||
*
|
||||
* ```ts
|
||||
* import { FFTCore, rootsOfUnity } from '@noble/curves/abstract/fft.js';
|
||||
* import { Field } from '@noble/curves/abstract/modular.js';
|
||||
* const Fp = Field(17n);
|
||||
* const roots = rootsOfUnity(Fp).roots(2);
|
||||
* const loop = FFTCore(Fp, { N: 4, roots, dit: true });
|
||||
* const values = loop([1n, 2n, 3n, 4n]);
|
||||
* ```
|
||||
*/
|
||||
export declare const FFTCore: <T, R>(F: FFTOpts<T, R>, coreOpts: FFTCoreOpts<R>) => FFTCoreLoop<T>;
|
||||
/** Forward and inverse FFT helpers for one coefficient domain. */
|
||||
export type FFTMethods<T> = {
|
||||
/**
|
||||
* Apply the forward transform.
|
||||
* @param values - Polynomial coefficients to transform.
|
||||
* @param brpInput - Whether the input is already bit-reversed.
|
||||
* @param brpOutput - Whether to keep the output bit-reversed.
|
||||
* @returns Transformed copy.
|
||||
*/
|
||||
direct<P extends Polynomial<T>>(values: P, brpInput?: boolean, brpOutput?: boolean): P;
|
||||
/**
|
||||
* Apply the inverse transform.
|
||||
* @param values - Polynomial coefficients to transform.
|
||||
* @param brpInput - Whether the input is already bit-reversed.
|
||||
* @param brpOutput - Whether to keep the output bit-reversed.
|
||||
* @returns Inverse-transformed copy.
|
||||
*/
|
||||
inverse<P extends Polynomial<T>>(values: P, brpInput?: boolean, brpOutput?: boolean): P;
|
||||
};
|
||||
/**
|
||||
* NTT aka FFT over finite field (NOT over complex numbers).
|
||||
* Naming mirrors other libraries.
|
||||
* @param roots - Roots-of-unity cache.
|
||||
* @param opts - Field operations. See {@link FFTOpts}.
|
||||
* @returns Forward and inverse FFT helpers.
|
||||
* @example
|
||||
* NTT aka FFT over finite field (NOT over complex numbers).
|
||||
*
|
||||
* ```ts
|
||||
* import { FFT, rootsOfUnity } from '@noble/curves/abstract/fft.js';
|
||||
* import { Field } from '@noble/curves/abstract/modular.js';
|
||||
* const Fp = Field(17n);
|
||||
* const fft = FFT(rootsOfUnity(Fp), Fp);
|
||||
* const values = fft.direct([1n, 2n, 3n, 4n]);
|
||||
* ```
|
||||
*/
|
||||
export declare function FFT<T>(roots: RootsOfUnity, opts: FFTOpts<T, bigint>): FFTMethods<T>;
|
||||
/**
|
||||
* Factory that allocates one polynomial storage container.
|
||||
* Callers must ensure `_create(len)` returns field-zero-filled storage when `elm` is omitted,
|
||||
* because the quadratic `mul()` / `convolve()` paths and the Kronecker-δ shortcut in
|
||||
* `lagrange.basis()` rely on that default instead of always passing `field.ZERO` explicitly.
|
||||
* @param len - Requested amount of coefficients.
|
||||
* @param elm - Optional fill value.
|
||||
* @returns Newly allocated polynomial container.
|
||||
*/
|
||||
export type CreatePolyFn<P extends PolyStorage<T>, T> = (len: number, elm?: T) => P;
|
||||
/** High-level polynomial helpers layered on top of FFT and field arithmetic. */
|
||||
export type PolyFn<P extends PolyStorage<T>, T> = {
|
||||
/** Roots-of-unity cache used by the helper namespace. */
|
||||
roots: RootsOfUnity;
|
||||
/** Factory used to allocate new polynomial containers. */
|
||||
create: CreatePolyFn<P, T>;
|
||||
/** Optional enforced polynomial length. */
|
||||
length?: number;
|
||||
/**
|
||||
* Compute the polynomial degree.
|
||||
* @param a - Polynomial coefficients.
|
||||
* @returns Polynomial degree.
|
||||
*/
|
||||
degree: (a: P) => number;
|
||||
/**
|
||||
* Extend or truncate one polynomial to a requested length.
|
||||
* @param a - Polynomial coefficients.
|
||||
* @param len - Target length.
|
||||
* @returns Resized polynomial.
|
||||
*/
|
||||
extend: (a: P, len: number) => P;
|
||||
/**
|
||||
* Add two polynomials coefficient-wise.
|
||||
* @param a - Left polynomial.
|
||||
* @param b - Right polynomial.
|
||||
* @returns Sum polynomial.
|
||||
*/
|
||||
add: (a: P, b: P) => P;
|
||||
/**
|
||||
* Subtract two polynomials coefficient-wise.
|
||||
* @param a - Left polynomial.
|
||||
* @param b - Right polynomial.
|
||||
* @returns Difference polynomial.
|
||||
*/
|
||||
sub: (a: P, b: P) => P;
|
||||
/**
|
||||
* Multiply by another polynomial or by one scalar.
|
||||
* @param a - Left polynomial.
|
||||
* @param b - Right polynomial or scalar.
|
||||
* @returns Product polynomial.
|
||||
*/
|
||||
mul: (a: P, b: P | T) => P;
|
||||
/**
|
||||
* Multiply coefficients point-wise.
|
||||
* @param a - Left polynomial.
|
||||
* @param b - Right polynomial.
|
||||
* @returns Point-wise product polynomial.
|
||||
*/
|
||||
dot: (a: P, b: P) => P;
|
||||
/**
|
||||
* Multiply two polynomials with convolution.
|
||||
* @param a - Left polynomial.
|
||||
* @param b - Right polynomial.
|
||||
* @returns Convolution product.
|
||||
*/
|
||||
convolve: (a: P, b: P) => P;
|
||||
/**
|
||||
* Apply a point-wise coefficient shift by powers of one factor.
|
||||
* @param p - Polynomial coefficients.
|
||||
* @param factor - Shift factor.
|
||||
* @returns Shifted polynomial.
|
||||
*/
|
||||
shift: (p: P, factor: bigint) => P;
|
||||
/**
|
||||
* Clone one polynomial container.
|
||||
* @param a - Polynomial coefficients.
|
||||
* @returns Cloned polynomial.
|
||||
*/
|
||||
clone: (a: P) => P;
|
||||
/**
|
||||
* Evaluate one polynomial on a basis vector.
|
||||
* @param a - Polynomial coefficients.
|
||||
* @param basis - Basis vector.
|
||||
* @returns Evaluated field element.
|
||||
*/
|
||||
eval: (a: P, basis: P) => T;
|
||||
/** Helpers for monomial-basis polynomials. */
|
||||
monomial: {
|
||||
/** Build the monomial basis vector for one evaluation point. */
|
||||
basis: (x: T, n: number) => P;
|
||||
/** Evaluate a polynomial in the monomial basis. */
|
||||
eval: (a: P, x: T) => T;
|
||||
};
|
||||
/** Helpers for Lagrange-basis polynomials. */
|
||||
lagrange: {
|
||||
/** Build the Lagrange basis vector for one evaluation point. */
|
||||
basis: (x: T, n: number, brp?: boolean) => P;
|
||||
/** Evaluate a polynomial in the Lagrange basis. */
|
||||
eval: (a: P, x: T, brp?: boolean) => T;
|
||||
};
|
||||
/**
|
||||
* Build the vanishing polynomial for a root set.
|
||||
* @param roots - Root set.
|
||||
* @returns Vanishing polynomial.
|
||||
*/
|
||||
vanishing: (roots: P) => P;
|
||||
};
|
||||
/**
|
||||
* Poly wants a cracker.
|
||||
*
|
||||
* Polynomials are functions like `y=f(x)`, which means when we multiply two polynomials, result is
|
||||
* function `f3(x) = f1(x) * f2(x)`, we don't multiply values. Key takeaways:
|
||||
*
|
||||
* - **Polynomial** is an array of coefficients: `f(x) = sum(coeff[i] * basis[i](x))`
|
||||
* - **Basis** is array of functions
|
||||
* - **Monominal** is Polynomial where `basis[i](x) == x**i` (powers)
|
||||
* - **Array size** is domain size
|
||||
* - **Lattice** is matrix (Polynomial of Polynomials)
|
||||
* @param field - Field implementation.
|
||||
* @param roots - Roots-of-unity cache.
|
||||
* @param create - Optional polynomial factory. Runtime input validation accepts only plain `Array`
|
||||
* and typed-array polynomial containers; arbitrary structural wrappers are intentionally rejected.
|
||||
* @param fft - Optional FFT implementation.
|
||||
* @param length - Optional fixed polynomial length.
|
||||
* @returns Polynomial helper namespace.
|
||||
* @example
|
||||
* Build polynomial helpers, then convolve two coefficient arrays.
|
||||
*
|
||||
* ```ts
|
||||
* import { poly, rootsOfUnity } from '@noble/curves/abstract/fft.js';
|
||||
* import { Field } from '@noble/curves/abstract/modular.js';
|
||||
* const Fp = Field(17n);
|
||||
* const poly17 = poly(Fp, rootsOfUnity(Fp));
|
||||
* const product = poly17.convolve([1n, 2n], [3n, 4n]);
|
||||
* ```
|
||||
*/
|
||||
export declare function poly<T>(field: TArg<IField<T>>, roots: RootsOfUnity, create?: undefined, fft?: FFTMethods<T>, length?: number): PolyFn<T[], T>;
|
||||
export declare function poly<T, P extends PolyStorage<T>>(field: TArg<IField<T>>, roots: RootsOfUnity, create: CreatePolyFn<P, T>, fft?: FFTMethods<T>, length?: number): PolyFn<P, T>;
|
||||
//# sourceMappingURL=fft.d.ts.map
|
||||
1
node_modules/@noble/curves/abstract/fft.d.ts.map
generated
vendored
Normal file
1
node_modules/@noble/curves/abstract/fft.d.ts.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
568
node_modules/@noble/curves/abstract/fft.js
generated
vendored
Normal file
568
node_modules/@noble/curves/abstract/fft.js
generated
vendored
Normal file
@@ -0,0 +1,568 @@
|
||||
function checkU32(n) {
|
||||
// 0xff_ff_ff_ff
|
||||
if (!Number.isSafeInteger(n) || n < 0 || n > 0xffffffff)
|
||||
throw new Error('wrong u32 integer:' + n);
|
||||
return n;
|
||||
}
|
||||
/**
|
||||
* Checks if integer is in form of `1 << X`.
|
||||
* @param x - Integer to inspect.
|
||||
* @returns `true` when the value is a power of two.
|
||||
* @throws If `x` is not a valid unsigned 32-bit integer. {@link Error}
|
||||
* @example
|
||||
* Validate that an FFT size is a power of two.
|
||||
*
|
||||
* ```ts
|
||||
* isPowerOfTwo(8);
|
||||
* ```
|
||||
*/
|
||||
export function isPowerOfTwo(x) {
|
||||
checkU32(x);
|
||||
return (x & (x - 1)) === 0 && x !== 0;
|
||||
}
|
||||
/**
|
||||
* @param n - Input value.
|
||||
* @returns Next power of two within the u32/array-length domain.
|
||||
* @throws If `n` is not a valid unsigned 32-bit integer. {@link Error}
|
||||
* @example
|
||||
* Round an integer up to the FFT size it needs.
|
||||
*
|
||||
* ```ts
|
||||
* nextPowerOfTwo(9);
|
||||
* ```
|
||||
*/
|
||||
export function nextPowerOfTwo(n) {
|
||||
checkU32(n);
|
||||
if (n <= 1)
|
||||
return 1;
|
||||
// FFT sizes here are used as JS array lengths, so `2^32` is not a meaningful result:
|
||||
// keep the fast u32 bit-twiddling path and fail explicitly instead of wrapping to 1.
|
||||
if (n > 0x8000_0000)
|
||||
throw new Error('nextPowerOfTwo overflow: result does not fit u32');
|
||||
return (1 << (log2(n - 1) + 1)) >>> 0;
|
||||
}
|
||||
/**
|
||||
* @param n - Value to reverse.
|
||||
* @param bits - Number of bits to use.
|
||||
* @returns Bit-reversed integer.
|
||||
* @throws If `n` is not a valid unsigned 32-bit integer. {@link Error}
|
||||
* @example
|
||||
* Reverse the low `bits` bits of one index.
|
||||
*
|
||||
* ```ts
|
||||
* reverseBits(3, 3);
|
||||
* ```
|
||||
*/
|
||||
export function reverseBits(n, bits) {
|
||||
checkU32(n);
|
||||
if (!Number.isSafeInteger(bits) || bits < 0 || bits > 32)
|
||||
throw new Error(`expected integer 0 <= bits <= 32, got ${bits}`);
|
||||
let reversed = 0;
|
||||
for (let i = 0; i < bits; i++, n >>>= 1)
|
||||
reversed = (reversed << 1) | (n & 1);
|
||||
// JS bitwise ops are signed i32; cast back so 32-bit reversals stay in the unsigned u32 domain.
|
||||
return reversed >>> 0;
|
||||
}
|
||||
/**
|
||||
* Similar to `bitLen(x)-1` but much faster for small integers, like indices.
|
||||
* @param n - Input value.
|
||||
* @returns Base-2 logarithm. For `n = 0`, the current implementation returns `-1`.
|
||||
* @throws If `n` is not a valid unsigned 32-bit integer. {@link Error}
|
||||
* @example
|
||||
* Compute the radix-2 stage count for one transform size.
|
||||
*
|
||||
* ```ts
|
||||
* log2(8);
|
||||
* ```
|
||||
*/
|
||||
export function log2(n) {
|
||||
checkU32(n);
|
||||
return 31 - Math.clz32(n);
|
||||
}
|
||||
/**
|
||||
* Moves lowest bit to highest position, which at first step splits
|
||||
* array on even and odd indices, then it applied again to each part,
|
||||
* which is core of fft
|
||||
* @param values - Mutable coefficient array.
|
||||
* @returns Mutated input array.
|
||||
* @throws If the array length is not a positive power of two. {@link Error}
|
||||
* @example
|
||||
* Reorder coefficients into bit-reversed order in place.
|
||||
*
|
||||
* ```ts
|
||||
* const values = Uint8Array.from([0, 1, 2, 3]);
|
||||
* bitReversalInplace(values);
|
||||
* ```
|
||||
*/
|
||||
export function bitReversalInplace(values) {
|
||||
const n = values.length;
|
||||
// Size-1 FFT is the identity, so bit-reversal must stay a no-op there instead of rejecting it.
|
||||
if (!isPowerOfTwo(n))
|
||||
throw new Error('expected positive power-of-two length, got ' + n);
|
||||
const bits = log2(n);
|
||||
for (let i = 0; i < n; i++) {
|
||||
const j = reverseBits(i, bits);
|
||||
if (i < j) {
|
||||
const tmp = values[i];
|
||||
values[i] = values[j];
|
||||
values[j] = tmp;
|
||||
}
|
||||
}
|
||||
return values;
|
||||
}
|
||||
/**
|
||||
* @param values - Input values.
|
||||
* @returns Reordered copy.
|
||||
* @throws If the array length is not a positive power of two. {@link Error}
|
||||
* @example
|
||||
* Return a reordered copy instead of mutating the input in place.
|
||||
*
|
||||
* ```ts
|
||||
* const reordered = bitReversalPermutation([0, 1, 2, 3]);
|
||||
* ```
|
||||
*/
|
||||
export function bitReversalPermutation(values) {
|
||||
return bitReversalInplace(values.slice());
|
||||
}
|
||||
const _1n = /** @__PURE__ */ BigInt(1);
|
||||
function findGenerator(field) {
|
||||
let G = BigInt(2);
|
||||
for (; field.eql(field.pow(G, field.ORDER >> _1n), field.ONE); G++)
|
||||
;
|
||||
return G;
|
||||
}
|
||||
/**
|
||||
* We limit roots up to 2**31, which is a lot: 2-billion polynomimal should be rare.
|
||||
* @param field - Field implementation.
|
||||
* @param generator - Optional generator override.
|
||||
* @returns Roots-of-unity cache.
|
||||
* @example
|
||||
* Cache roots once, then ask for the omega table of one FFT size.
|
||||
*
|
||||
* ```ts
|
||||
* import { rootsOfUnity } from '@noble/curves/abstract/fft.js';
|
||||
* import { Field } from '@noble/curves/abstract/modular.js';
|
||||
* const roots = rootsOfUnity(Field(17n));
|
||||
* const omega = roots.omega(4);
|
||||
* ```
|
||||
*/
|
||||
export function rootsOfUnity(field, generator) {
|
||||
// Factor field.ORDER-1 as oddFactor * 2^powerOfTwo
|
||||
let oddFactor = field.ORDER - _1n;
|
||||
let powerOfTwo = 0;
|
||||
for (; (oddFactor & _1n) !== _1n; powerOfTwo++, oddFactor >>= _1n)
|
||||
;
|
||||
// Find non quadratic residue
|
||||
let G = generator !== undefined ? BigInt(generator) : findGenerator(field);
|
||||
// Powers of generator
|
||||
const omegas = new Array(powerOfTwo + 1);
|
||||
omegas[powerOfTwo] = field.pow(G, oddFactor);
|
||||
for (let i = powerOfTwo; i > 0; i--)
|
||||
omegas[i - 1] = field.sqr(omegas[i]);
|
||||
// Compute all roots of unity for powers up to maxPower
|
||||
const rootsCache = [];
|
||||
const checkBits = (bits) => {
|
||||
checkU32(bits);
|
||||
if (bits > 31 || bits > powerOfTwo)
|
||||
throw new Error('rootsOfUnity: wrong bits ' + bits + ' powerOfTwo=' + powerOfTwo);
|
||||
return bits;
|
||||
};
|
||||
const precomputeRoots = (maxPower) => {
|
||||
checkBits(maxPower);
|
||||
for (let power = maxPower; power >= 0; power--) {
|
||||
if (rootsCache[power])
|
||||
continue; // Skip if we've already computed roots for this power
|
||||
const rootsAtPower = [];
|
||||
for (let j = 0, cur = field.ONE; j < 2 ** power; j++, cur = field.mul(cur, omegas[power]))
|
||||
rootsAtPower.push(cur);
|
||||
rootsCache[power] = rootsAtPower;
|
||||
}
|
||||
return rootsCache[maxPower];
|
||||
};
|
||||
const brpCache = new Map();
|
||||
const inverseCache = new Map();
|
||||
// roots()/brp()/inverse() expose shared cached arrays by reference for speed; callers must treat them as read-only.
|
||||
// NOTE: we use bits instead of power, because power = 2**bits,
|
||||
// but power is not neccesary isPowerOfTwo(power)!
|
||||
return {
|
||||
info: { G, powerOfTwo, oddFactor },
|
||||
roots: (bits) => {
|
||||
const b = checkBits(bits);
|
||||
return precomputeRoots(b);
|
||||
},
|
||||
brp(bits) {
|
||||
const b = checkBits(bits);
|
||||
if (brpCache.has(b))
|
||||
return brpCache.get(b);
|
||||
else {
|
||||
const res = bitReversalPermutation(this.roots(b));
|
||||
brpCache.set(b, res);
|
||||
return res;
|
||||
}
|
||||
},
|
||||
inverse(bits) {
|
||||
const b = checkBits(bits);
|
||||
if (inverseCache.has(b))
|
||||
return inverseCache.get(b);
|
||||
else {
|
||||
const res = field.invertBatch(this.roots(b));
|
||||
inverseCache.set(b, res);
|
||||
return res;
|
||||
}
|
||||
},
|
||||
omega: (bits) => omegas[checkBits(bits)],
|
||||
clear: () => {
|
||||
rootsCache.splice(0, rootsCache.length);
|
||||
brpCache.clear();
|
||||
inverseCache.clear();
|
||||
},
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Constructs different flavors of FFT. radix2 implementation of low level mutating API. Flavors:
|
||||
*
|
||||
* - DIT (Decimation-in-Time): Bottom-Up (leaves to root), Cool-Turkey
|
||||
* - DIF (Decimation-in-Frequency): Top-Down (root to leaves), Gentleman-Sande
|
||||
*
|
||||
* DIT takes brp input, returns natural output.
|
||||
* DIF takes natural input, returns brp output.
|
||||
*
|
||||
* The output is actually identical. Time / frequence distinction is not meaningful
|
||||
* for Polynomial multiplication in fields.
|
||||
* Which means if protocol supports/needs brp output/inputs, then we can skip this step.
|
||||
*
|
||||
* Cyclic NTT: Rq = Zq[x]/(x^n-1). butterfly_DIT+loop_DIT OR butterfly_DIF+loop_DIT, roots are omega
|
||||
* Negacyclic NTT: Rq = Zq[x]/(x^n+1). butterfly_DIT+loop_DIF, at least for mlkem / mldsa
|
||||
* @param F - Field operations.
|
||||
* @param coreOpts - FFT configuration:
|
||||
* - `N`: Transform size. Must be a power of two.
|
||||
* - `roots`: Stage roots for the selected transform size.
|
||||
* - `dit`: Whether to run the DIT variant instead of DIF.
|
||||
* - `invertButterflies` (optional): Whether to invert butterfly placement.
|
||||
* - `skipStages` (optional): Number of initial stages to skip.
|
||||
* - `brp` (optional): Whether to apply bit-reversal permutation at the boundary.
|
||||
* @returns Low-level FFT loop.
|
||||
* @throws If the FFT options or cached roots are invalid for the requested size. {@link Error}
|
||||
* @example
|
||||
* Constructs different flavors of FFT.
|
||||
*
|
||||
* ```ts
|
||||
* import { FFTCore, rootsOfUnity } from '@noble/curves/abstract/fft.js';
|
||||
* import { Field } from '@noble/curves/abstract/modular.js';
|
||||
* const Fp = Field(17n);
|
||||
* const roots = rootsOfUnity(Fp).roots(2);
|
||||
* const loop = FFTCore(Fp, { N: 4, roots, dit: true });
|
||||
* const values = loop([1n, 2n, 3n, 4n]);
|
||||
* ```
|
||||
*/
|
||||
export const FFTCore = (F, coreOpts) => {
|
||||
const { N, roots, dit, invertButterflies = false, skipStages = 0, brp = true } = coreOpts;
|
||||
const bits = log2(N);
|
||||
if (!isPowerOfTwo(N))
|
||||
throw new Error('FFT: Polynomial size should be power of two');
|
||||
// Wrong-sized root tables can stay in-bounds for some loop shapes and silently compute nonsense.
|
||||
if (roots.length !== N)
|
||||
throw new Error(`FFT: wrong roots length: expected ${N}, got ${roots.length}`);
|
||||
const isDit = dit !== invertButterflies;
|
||||
isDit;
|
||||
return (values) => {
|
||||
if (values.length !== N)
|
||||
throw new Error('FFT: wrong Polynomial length');
|
||||
if (dit && brp)
|
||||
bitReversalInplace(values);
|
||||
for (let i = 0, g = 1; i < bits - skipStages; i++) {
|
||||
// For each stage s (sub-FFT length m = 2^s)
|
||||
const s = dit ? i + 1 + skipStages : bits - i;
|
||||
const m = 1 << s;
|
||||
const m2 = m >> 1;
|
||||
const stride = N >> s;
|
||||
// Loop over each subarray of length m
|
||||
for (let k = 0; k < N; k += m) {
|
||||
// Loop over each butterfly within the subarray
|
||||
for (let j = 0, grp = g++; j < m2; j++) {
|
||||
const rootPos = invertButterflies ? (dit ? N - grp : grp) : j * stride;
|
||||
const i0 = k + j;
|
||||
const i1 = k + j + m2;
|
||||
const omega = roots[rootPos];
|
||||
const b = values[i1];
|
||||
const a = values[i0];
|
||||
// Inlining gives us 10% perf in kyber vs functions
|
||||
if (isDit) {
|
||||
const t = F.mul(b, omega); // Standard DIT butterfly
|
||||
values[i0] = F.add(a, t);
|
||||
values[i1] = F.sub(a, t);
|
||||
}
|
||||
else if (invertButterflies) {
|
||||
values[i0] = F.add(b, a); // DIT loop + inverted butterflies (Kyber decode)
|
||||
values[i1] = F.mul(F.sub(b, a), omega);
|
||||
}
|
||||
else {
|
||||
values[i0] = F.add(a, b); // Standard DIF butterfly
|
||||
values[i1] = F.mul(F.sub(a, b), omega);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!dit && brp)
|
||||
bitReversalInplace(values);
|
||||
return values;
|
||||
};
|
||||
};
|
||||
/**
|
||||
* NTT aka FFT over finite field (NOT over complex numbers).
|
||||
* Naming mirrors other libraries.
|
||||
* @param roots - Roots-of-unity cache.
|
||||
* @param opts - Field operations. See {@link FFTOpts}.
|
||||
* @returns Forward and inverse FFT helpers.
|
||||
* @example
|
||||
* NTT aka FFT over finite field (NOT over complex numbers).
|
||||
*
|
||||
* ```ts
|
||||
* import { FFT, rootsOfUnity } from '@noble/curves/abstract/fft.js';
|
||||
* import { Field } from '@noble/curves/abstract/modular.js';
|
||||
* const Fp = Field(17n);
|
||||
* const fft = FFT(rootsOfUnity(Fp), Fp);
|
||||
* const values = fft.direct([1n, 2n, 3n, 4n]);
|
||||
* ```
|
||||
*/
|
||||
export function FFT(roots, opts) {
|
||||
const getLoop = (N, roots, brpInput = false, brpOutput = false) => {
|
||||
if (brpInput && brpOutput) {
|
||||
// we cannot optimize this case, but lets support it anyway
|
||||
return (values) => FFTCore(opts, { N, roots, dit: false, brp: false })(bitReversalInplace(values));
|
||||
}
|
||||
if (brpInput)
|
||||
return FFTCore(opts, { N, roots, dit: true, brp: false });
|
||||
if (brpOutput)
|
||||
return FFTCore(opts, { N, roots, dit: false, brp: false });
|
||||
return FFTCore(opts, { N, roots, dit: true, brp: true }); // all natural
|
||||
};
|
||||
return {
|
||||
direct(values, brpInput = false, brpOutput = false) {
|
||||
const N = values.length;
|
||||
if (!isPowerOfTwo(N))
|
||||
throw new Error('FFT: Polynomial size should be power of two');
|
||||
const bits = log2(N);
|
||||
return getLoop(N, roots.roots(bits), brpInput, brpOutput)(values.slice());
|
||||
},
|
||||
inverse(values, brpInput = false, brpOutput = false) {
|
||||
const N = values.length;
|
||||
if (!isPowerOfTwo(N))
|
||||
throw new Error('FFT: Polynomial size should be power of two');
|
||||
const bits = log2(N);
|
||||
const res = getLoop(N, roots.inverse(bits), brpInput, brpOutput)(values.slice());
|
||||
const ivm = opts.inv(BigInt(values.length)); // scale
|
||||
// we can get brp output if we use dif instead of dit!
|
||||
for (let i = 0; i < res.length; i++)
|
||||
res[i] = opts.mul(res[i], ivm);
|
||||
// Allows to re-use non-inverted roots, but is VERY fragile
|
||||
// return [res[0]].concat(res.slice(1).reverse());
|
||||
// inverse calculated as pow(-1), which transforms into ω^{-kn} (-> reverses indices)
|
||||
return res;
|
||||
},
|
||||
};
|
||||
}
|
||||
export function poly(field, roots, create, fft, length) {
|
||||
const F = field;
|
||||
const _create = create ||
|
||||
((len, elm) => new Array(len).fill(elm ?? F.ZERO));
|
||||
// `poly.mul(a, b)` distinguishes polynomial-vs-scalar at runtime, so keep accepted
|
||||
// polynomial containers concrete instead of trying to support arbitrary wrappers.
|
||||
const isPoly = (x) => {
|
||||
if (Array.isArray(x))
|
||||
return true;
|
||||
if (!ArrayBuffer.isView(x))
|
||||
return false;
|
||||
const v = x;
|
||||
return (typeof v.length === 'number' &&
|
||||
typeof v.slice === 'function' &&
|
||||
typeof v[Symbol.iterator] === 'function');
|
||||
};
|
||||
const checkLength = (...lst) => {
|
||||
if (!lst.length)
|
||||
return 0;
|
||||
for (const i of lst)
|
||||
if (!isPoly(i))
|
||||
throw new Error('poly: not polynomial: ' + i);
|
||||
const L = lst[0].length;
|
||||
for (let i = 1; i < lst.length; i++)
|
||||
if (lst[i].length !== L)
|
||||
throw new Error(`poly: mismatched lengths ${L} vs ${lst[i].length}`);
|
||||
if (length !== undefined && L !== length)
|
||||
throw new Error(`poly: expected fixed length ${length}, got ${L}`);
|
||||
return L;
|
||||
};
|
||||
function findOmegaIndex(x, n, brp = false) {
|
||||
const bits = log2(n);
|
||||
const omega = brp ? roots.brp(bits) : roots.roots(bits);
|
||||
for (let i = 0; i < n; i++)
|
||||
if (F.eql(x, omega[i]))
|
||||
return i;
|
||||
return -1;
|
||||
}
|
||||
// TODO: mutating versions for mlkem/mldsa
|
||||
return {
|
||||
roots,
|
||||
create: _create,
|
||||
length,
|
||||
extend: (a, len) => {
|
||||
checkLength(a);
|
||||
const out = _create(len, F.ZERO);
|
||||
// Plain arrays grow when writing past `out.length`, so cap the copy explicitly to keep
|
||||
// `extend()` consistent with typed arrays and with its documented truncate behavior.
|
||||
for (let i = 0; i < Math.min(a.length, len); i++)
|
||||
out[i] = a[i];
|
||||
return out;
|
||||
},
|
||||
degree: (a) => {
|
||||
checkLength(a);
|
||||
for (let i = a.length - 1; i >= 0; i--)
|
||||
if (!F.is0(a[i]))
|
||||
return i;
|
||||
return -1;
|
||||
},
|
||||
add: (a, b) => {
|
||||
const len = checkLength(a, b);
|
||||
const out = _create(len);
|
||||
for (let i = 0; i < len; i++)
|
||||
out[i] = F.add(a[i], b[i]);
|
||||
return out;
|
||||
},
|
||||
sub: (a, b) => {
|
||||
const len = checkLength(a, b);
|
||||
const out = _create(len);
|
||||
for (let i = 0; i < len; i++)
|
||||
out[i] = F.sub(a[i], b[i]);
|
||||
return out;
|
||||
},
|
||||
dot: (a, b) => {
|
||||
const len = checkLength(a, b);
|
||||
const out = _create(len);
|
||||
for (let i = 0; i < len; i++)
|
||||
out[i] = F.mul(a[i], b[i]);
|
||||
return out;
|
||||
},
|
||||
mul: (a, b) => {
|
||||
if (isPoly(b)) {
|
||||
const len = checkLength(a, b);
|
||||
if (fft) {
|
||||
const A = fft.direct(a, false, true);
|
||||
const B = fft.direct(b, false, true);
|
||||
for (let i = 0; i < A.length; i++)
|
||||
A[i] = F.mul(A[i], B[i]);
|
||||
return fft.inverse(A, true, false);
|
||||
}
|
||||
else {
|
||||
// NOTE: this is quadratic and mostly for compat tests with FFT
|
||||
const res = _create(len);
|
||||
for (let i = 0; i < len; i++) {
|
||||
for (let j = 0; j < len; j++) {
|
||||
const k = (i + j) % len; // wrap mod length
|
||||
res[k] = F.add(res[k], F.mul(a[i], b[j]));
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
}
|
||||
else {
|
||||
const out = _create(checkLength(a));
|
||||
for (let i = 0; i < out.length; i++)
|
||||
out[i] = F.mul(a[i], b);
|
||||
return out;
|
||||
}
|
||||
},
|
||||
convolve(a, b) {
|
||||
const len = nextPowerOfTwo(a.length + b.length - 1);
|
||||
return this.mul(this.extend(a, len), this.extend(b, len));
|
||||
},
|
||||
shift(p, factor) {
|
||||
const out = _create(checkLength(p));
|
||||
out[0] = p[0];
|
||||
for (let i = 1, power = F.ONE; i < p.length; i++) {
|
||||
power = F.mul(power, factor);
|
||||
out[i] = F.mul(p[i], power);
|
||||
}
|
||||
return out;
|
||||
},
|
||||
clone: (a) => {
|
||||
checkLength(a);
|
||||
const out = _create(a.length);
|
||||
for (let i = 0; i < a.length; i++)
|
||||
out[i] = a[i];
|
||||
return out;
|
||||
},
|
||||
eval: (a, basis) => {
|
||||
checkLength(a, basis);
|
||||
let acc = F.ZERO;
|
||||
for (let i = 0; i < a.length; i++)
|
||||
acc = F.add(acc, F.mul(a[i], basis[i]));
|
||||
return acc;
|
||||
},
|
||||
monomial: {
|
||||
basis: (x, n) => {
|
||||
const out = _create(n);
|
||||
let pow = F.ONE;
|
||||
for (let i = 0; i < n; i++) {
|
||||
out[i] = pow;
|
||||
pow = F.mul(pow, x);
|
||||
}
|
||||
return out;
|
||||
},
|
||||
eval: (a, x) => {
|
||||
checkLength(a);
|
||||
// Same as eval(a, monomialBasis(x, a.length)), but it is faster this way
|
||||
let acc = F.ZERO;
|
||||
for (let i = a.length - 1; i >= 0; i--)
|
||||
acc = F.add(F.mul(acc, x), a[i]);
|
||||
return acc;
|
||||
},
|
||||
},
|
||||
lagrange: {
|
||||
basis: (x, n, brp = false, weights) => {
|
||||
const bits = log2(n);
|
||||
const cache = weights || (brp ? roots.brp(bits) : roots.roots(bits)); // [ω⁰, ω¹, ..., ωⁿ⁻¹]
|
||||
const out = _create(n);
|
||||
// Fast Kronecker-δ shortcut
|
||||
const idx = findOmegaIndex(x, n, brp);
|
||||
if (idx !== -1) {
|
||||
out[idx] = F.ONE;
|
||||
return out;
|
||||
}
|
||||
const tm = F.pow(x, BigInt(n));
|
||||
const c = F.mul(F.sub(tm, F.ONE), F.inv(BigInt(n))); // c = (xⁿ - 1)/n
|
||||
const denom = _create(n);
|
||||
for (let i = 0; i < n; i++)
|
||||
denom[i] = F.sub(x, cache[i]);
|
||||
const inv = F.invertBatch(denom);
|
||||
for (let i = 0; i < n; i++)
|
||||
out[i] = F.mul(c, F.mul(cache[i], inv[i]));
|
||||
return out;
|
||||
},
|
||||
eval(a, x, brp = false) {
|
||||
checkLength(a);
|
||||
const idx = findOmegaIndex(x, a.length, brp);
|
||||
if (idx !== -1)
|
||||
return a[idx]; // fast path
|
||||
const L = this.basis(x, a.length, brp); // Lᵢ(x)
|
||||
let acc = F.ZERO;
|
||||
for (let i = 0; i < a.length; i++)
|
||||
if (!F.is0(a[i]))
|
||||
acc = F.add(acc, F.mul(a[i], L[i]));
|
||||
return acc;
|
||||
},
|
||||
},
|
||||
vanishing(roots) {
|
||||
checkLength(roots);
|
||||
const out = _create(roots.length + 1, F.ZERO);
|
||||
out[0] = F.ONE;
|
||||
for (const r of roots) {
|
||||
const neg = F.neg(r);
|
||||
for (let j = out.length - 1; j > 0; j--)
|
||||
out[j] = F.add(F.mul(out[j], neg), out[j - 1]);
|
||||
out[0] = F.mul(out[0], neg);
|
||||
}
|
||||
return out;
|
||||
},
|
||||
};
|
||||
}
|
||||
//# sourceMappingURL=fft.js.map
|
||||
1
node_modules/@noble/curves/abstract/fft.js.map
generated
vendored
Normal file
1
node_modules/@noble/curves/abstract/fft.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
293
node_modules/@noble/curves/abstract/frost.d.ts
generated
vendored
Normal file
293
node_modules/@noble/curves/abstract/frost.d.ts
generated
vendored
Normal file
@@ -0,0 +1,293 @@
|
||||
import { randomBytes, type TArg, type TRet } from '../utils.ts';
|
||||
import { type CurvePoint, type CurvePointCons } from './curve.ts';
|
||||
import { type H2CDSTOpts } from './hash-to-curve.ts';
|
||||
import { type IField } from './modular.ts';
|
||||
export type RNG = typeof randomBytes;
|
||||
export type Identifier = string;
|
||||
export type Commitment = Uint8Array;
|
||||
export type Coefficient = Uint8Array;
|
||||
export type Signature = Uint8Array;
|
||||
export type Signers = {
|
||||
min: number;
|
||||
max: number;
|
||||
};
|
||||
export type SecretKey = Uint8Array;
|
||||
export type Bytes = Uint8Array;
|
||||
type Point = Uint8Array;
|
||||
export type DKG_Round1 = {
|
||||
identifier: Identifier;
|
||||
commitment: TRet<Commitment[]>;
|
||||
proofOfKnowledge: TRet<Signature>;
|
||||
};
|
||||
export type DKG_Round2 = {
|
||||
identifier: Identifier;
|
||||
signingShare: TRet<Bytes>;
|
||||
};
|
||||
export type DKG_Secret = {
|
||||
identifier: bigint;
|
||||
coefficients?: bigint[];
|
||||
commitment: TRet<Point[]>;
|
||||
signers: Signers;
|
||||
step?: 1 | 2 | 3;
|
||||
};
|
||||
export type FrostPublic = {
|
||||
signers: Signers;
|
||||
commitments: TRet<Bytes[]>;
|
||||
verifyingShares: TRet<Record<Identifier, Bytes>>;
|
||||
};
|
||||
export type FrostSecret = {
|
||||
identifier: Identifier;
|
||||
signingShare: TRet<Bytes>;
|
||||
};
|
||||
export type Key = {
|
||||
public: FrostPublic;
|
||||
secret: FrostSecret;
|
||||
};
|
||||
export type DealerShares = {
|
||||
public: FrostPublic;
|
||||
secretShares: Record<Identifier, FrostSecret>;
|
||||
};
|
||||
export type Nonces = {
|
||||
hiding: TRet<Bytes>;
|
||||
binding: TRet<Bytes>;
|
||||
};
|
||||
export type NonceCommitments = {
|
||||
identifier: Identifier;
|
||||
hiding: TRet<Bytes>;
|
||||
binding: TRet<Bytes>;
|
||||
};
|
||||
export type GenNonce = {
|
||||
nonces: Nonces;
|
||||
commitments: NonceCommitments;
|
||||
};
|
||||
export interface FROSTPoint<T extends CurvePoint<any, T>> extends CurvePoint<any, T> {
|
||||
add(rhs: T): T;
|
||||
multiply(rhs: bigint): T;
|
||||
equals(rhs: T): boolean;
|
||||
toBytes(compressed?: boolean): Bytes;
|
||||
clearCofactor(): T;
|
||||
}
|
||||
export interface FROSTPointConstructor<T extends FROSTPoint<T>> extends CurvePointCons<T> {
|
||||
fromBytes(a: Bytes): T;
|
||||
Fn: IField<bigint>;
|
||||
}
|
||||
export type FrostOpts<P extends FROSTPoint<P>> = {
|
||||
readonly name: string;
|
||||
readonly Point: FROSTPointConstructor<P>;
|
||||
readonly Fn?: IField<bigint>;
|
||||
/** Optional suite hook that tightens canonical decoding with subgroup / identity checks. */
|
||||
readonly validatePoint?: (p: P) => void;
|
||||
/** Optional public-key parser. Implementations MUST preserve the same subgroup / identity policy
|
||||
* as `validatePoint`, because this bypasses generic canonical decoding in `parsePoint()`. */
|
||||
readonly parsePublicKey?: (bytes: TArg<Uint8Array>) => P;
|
||||
readonly hash: (msg: TArg<Uint8Array>) => TRet<Uint8Array>;
|
||||
/** Custom scalar hash hook. Implementations MUST treat `msg` and `options` as read-only. */
|
||||
readonly hashToScalar?: (msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>) => bigint;
|
||||
readonly adjustScalar?: (n: bigint) => bigint;
|
||||
readonly adjustPoint?: (n: P) => P;
|
||||
readonly challenge?: (R: P, PK: P, msg: TArg<Uint8Array>) => bigint;
|
||||
readonly adjustNonces?: (PK: P, nonces: TArg<Nonces>) => TRet<Nonces>;
|
||||
readonly adjustSecret?: (secret: TArg<FrostSecret>, pub: TArg<FrostPublic>) => TRet<FrostSecret>;
|
||||
readonly adjustPublic?: (pub: TArg<FrostPublic>) => TRet<FrostPublic>;
|
||||
readonly adjustGroupCommitmentShare?: (GC: P, GCShare: P) => P;
|
||||
readonly adjustTx?: {
|
||||
readonly encode: (tx: TArg<Uint8Array>) => TRet<Uint8Array>;
|
||||
readonly decode: (tx: TArg<Uint8Array>) => TRet<Uint8Array>;
|
||||
};
|
||||
readonly adjustDKG?: (k: TArg<Key>) => TRet<Key>;
|
||||
readonly H1?: string;
|
||||
readonly H2?: string;
|
||||
readonly H3?: string;
|
||||
readonly H4?: string;
|
||||
readonly H5?: string;
|
||||
readonly HDKG?: string;
|
||||
readonly HID?: string;
|
||||
};
|
||||
/**
|
||||
* FROST: Threshold Protocol for Two‑Round Schnorr Signatures
|
||||
* from [RFC 9591](https://datatracker.ietf.org/doc/rfc9591/).
|
||||
*/
|
||||
export type FROST = {
|
||||
/**
|
||||
* Methods to construct participant identifiers.
|
||||
*/
|
||||
Identifier: {
|
||||
/**
|
||||
* Constructs an identifier from a numeric index.
|
||||
* @param n - A positive integer.
|
||||
* @returns A canonical serialized Identifier.
|
||||
*/
|
||||
fromNumber(n: number): Identifier;
|
||||
/**
|
||||
* Derives an identifier deterministically from a string (e.g. an email).
|
||||
* @param s - Arbitrary string.
|
||||
* @returns A canonical serialized Identifier.
|
||||
*/
|
||||
derive(s: string): Identifier;
|
||||
};
|
||||
/**
|
||||
* Distributed Key Generation (DKG) protocol interface.
|
||||
* RFC 9591 leaves DKG out of scope; Appendix C only specifies dealer/VSS key generation.
|
||||
* These helpers follow the split-round API used by frost-rs for interoperable testing.
|
||||
*/
|
||||
DKG: {
|
||||
/**
|
||||
* Generates the first round of DKG.
|
||||
* @param id - Participant's identifier.
|
||||
* @param signers - Set of all participants (min/max threshold).
|
||||
* @param secret - Optional initial secret scalar.
|
||||
* @param rng - Optional RNG for nonce generation.
|
||||
* @returns Public broadcast and private DKG state. The returned `secret` package is mutable
|
||||
* round state that will be consumed by `round2()` and `round3()`.
|
||||
*/
|
||||
round1: (id: Identifier, signers: Signers, secret?: TArg<SecretKey>, rng?: RNG) => {
|
||||
public: DKG_Round1;
|
||||
secret: DKG_Secret;
|
||||
};
|
||||
/**
|
||||
* Executes DKG round 2 given public round1 data from others.
|
||||
* @param secret - Private DKG state from round1. This mutates `secret.step` in place.
|
||||
* @param others - Public round1 broadcasts from other participants.
|
||||
* @returns A map of round2 messages to be sent to others.
|
||||
*/
|
||||
round2: (secret: TArg<DKG_Secret>, others: TArg<DKG_Round1[]>) => TRet<Record<string, DKG_Round2>>;
|
||||
/**
|
||||
* Finalizes key generation in round3 using received round1 + round2 messages.
|
||||
* @param secret - Private DKG state. This consumes the remaining local polynomial coefficients
|
||||
* and transitions the package to its final post-round3 state.
|
||||
* @param round1 - Public round1 broadcasts from all participants.
|
||||
* @param round2 - Round2 messages received from others.
|
||||
* @returns Final secret/public key information for the participant.
|
||||
* Callers MUST pass the same verified remote `round1` package set that was already
|
||||
* accepted in `round2()`, rather than re-fetching or rebuilding it from the network.
|
||||
*/
|
||||
round3: (secret: TArg<DKG_Secret>, round1: TArg<DKG_Round1[]>, round2: TArg<DKG_Round2[]>) => TRet<Key>;
|
||||
/**
|
||||
* Best-effort erasure of internal secret state. Bigint/JIT copies may still survive outside the
|
||||
* local object even after cleanup.
|
||||
* @param secret - Private DKG state from round1.
|
||||
*/
|
||||
clean(secret: TArg<DKG_Secret>): void;
|
||||
};
|
||||
/**
|
||||
* Trusted dealer mode: generates key shares from a central trusted authority.
|
||||
* Mirrors RFC 9591 Appendix C and returns one shared VSS commitment package
|
||||
* plus per-participant shares.
|
||||
* @param signers - Threshold parameters (min/max).
|
||||
* @param identifiers - Optional explicit participant list.
|
||||
* @param secret - Optional secret scalar.
|
||||
* @param rng - Optional RNG.
|
||||
* @returns One shared public package plus the participant secret-share packages.
|
||||
*/
|
||||
trustedDealer(signers: Signers, identifiers?: Identifier[], secret?: TArg<SecretKey>, rng?: RNG): TRet<DealerShares>;
|
||||
/**
|
||||
* Validates the consistency of a secret share against the shared public commitments.
|
||||
* This is the RFC 9591 Appendix C.2 `vss_verify` check against the shared dealer/DKG commitment.
|
||||
* It does not relax RFC 9591 Section 3.1: public identity elements are still invalid even when
|
||||
* the scalar/share algebra would otherwise be self-consistent.
|
||||
* Throws if invalid.
|
||||
* @param secret - A FrostSecret containing identifier and signing share.
|
||||
* @param pub - Shared public package containing commitments.
|
||||
*/
|
||||
validateSecret(secret: TArg<FrostSecret>, pub: TArg<FrostPublic>): void;
|
||||
/**
|
||||
* Produces nonces and public commitments used in signing.
|
||||
* RFC 9591 Section 5.1 `commit()`.
|
||||
* @param secret - Participant's secret share.
|
||||
* @param rng - Optional RNG.
|
||||
* @returns Nonce values and their public commitments.
|
||||
* Returned nonces are one-time-use and MUST NOT be reused across signing sessions.
|
||||
* This API does not mutate or zeroize caller-owned nonce objects.
|
||||
*/
|
||||
commit(secret: TArg<FrostSecret>, rng?: RNG): TRet<GenNonce>;
|
||||
/**
|
||||
* Signs a message using the participant's secret and nonce.
|
||||
* @param secret - Participant's secret share.
|
||||
* @param pub - Shared public package containing commitments.
|
||||
* @param nonces - Participant's nonce pair.
|
||||
* @param commitmentList - Commitments from all signing participants.
|
||||
* @param msg - Message to be signed.
|
||||
* @returns Signature share as a byte array.
|
||||
* RFC 9591 Sections 4.1/5.1 require round-one commitments to be one-time-use, and
|
||||
* Section 5.2 signs with the nonce corresponding to that published commitment.
|
||||
* The caller MUST pass fresh nonces from `commit()`. On successful signing, this helper
|
||||
* consumes the caller-owned nonce object by zeroing both nonce byte arrays in place.
|
||||
* Later calls reject an all-zero nonce package, so same-object reuse fails closed and an
|
||||
* accidentally generated zero nonce package is not silently used for signing.
|
||||
*/
|
||||
signShare(secret: TArg<FrostSecret>, pub: TArg<FrostPublic>, nonces: TArg<Nonces>, commitmentList: TArg<NonceCommitments[]>, msg: TArg<Uint8Array>): TRet<Uint8Array>;
|
||||
/**
|
||||
* Verifies a signature share against public commitments.
|
||||
* Matches the coordinator-side individual-share verification from RFC 9591 Section 5.4.
|
||||
* @param pub - Group public key information.
|
||||
* @param commitmentList - Commitments from all signing participants.
|
||||
* @param msg - Message being signed.
|
||||
* @param identifier - Identifier of the signer whose share is being verified.
|
||||
* @param sigShare - Signature share to verify.
|
||||
* @returns True if valid, false otherwise.
|
||||
*/
|
||||
verifyShare(pub: TArg<FrostPublic>, commitmentList: TArg<NonceCommitments[]>, msg: TArg<Uint8Array>, identifier: Identifier, sigShare: TArg<Uint8Array>): boolean;
|
||||
/**
|
||||
* Aggregates signature shares into a full signature.
|
||||
* RFC 9591 Section 5.3 `aggregate()`.
|
||||
* @param pub - Group public key.
|
||||
* @param commitmentList - Nonce commitments from all signers.
|
||||
* @param msg - Message to sign.
|
||||
* @param sigShares - Map from identifier to their signature share.
|
||||
* @returns Final aggregated signature.
|
||||
*/
|
||||
aggregate(pub: TArg<FrostPublic>, commitmentList: TArg<NonceCommitments[]>, msg: TArg<Uint8Array>, sigShares: TArg<Record<Identifier, Uint8Array>>): TRet<Uint8Array>;
|
||||
/**
|
||||
* Signs a message using a raw secret key (e.g. from combineSecret).
|
||||
* @param msg - Message to sign.
|
||||
* @param secretKey - Group secret key as bytes.
|
||||
* @returns Signature bytes.
|
||||
*/
|
||||
sign(msg: TArg<Uint8Array>, secretKey: TArg<Uint8Array>): TRet<Uint8Array>;
|
||||
/**
|
||||
* Verifies a full signature against the group public key.
|
||||
* @param sig - Signature bytes.
|
||||
* @param msg - Message that was signed.
|
||||
* @param publicKey - Group public key.
|
||||
* @returns True if valid, false otherwise.
|
||||
*/
|
||||
verify(sig: TArg<Signature>, msg: TArg<Uint8Array>, publicKey: TArg<Uint8Array>): boolean;
|
||||
/**
|
||||
* Combines multiple secret shares into a single secret key (e.g. for recovery).
|
||||
* @param shares - Set of FrostSecret shares.
|
||||
* @param signers - Threshold parameters.
|
||||
* @returns Group secret key as bytes.
|
||||
*/
|
||||
combineSecret(shares: TArg<FrostSecret[]>, signers: Signers): TRet<Uint8Array>;
|
||||
/**
|
||||
* Low-level helper utilities (field arithmetic and polynomial tools).
|
||||
*/
|
||||
utils: {
|
||||
/**
|
||||
* Finite field used for scalars.
|
||||
*/
|
||||
Fn: IField<bigint>;
|
||||
/**
|
||||
* Generates a random scalar (private key).
|
||||
* @param rng - Optional RNG source.
|
||||
* @returns Scalar as 32-byte Uint8Array.
|
||||
*/
|
||||
randomScalar: (rng?: RNG) => TRet<Uint8Array>;
|
||||
/**
|
||||
* Generates a secret-sharing polynomial and its public commitments.
|
||||
* @param signers - Threshold parameters.
|
||||
* @param secret - Optional initial secret scalar.
|
||||
* @param coeffs - Optional manual coefficients.
|
||||
* @param rng - Optional RNG.
|
||||
* @returns Polynomial coefficients, commitments, and secret value.
|
||||
*/
|
||||
generateSecretPolynomial: (signers: Signers, secret?: TArg<Uint8Array>, coeffs?: bigint[], rng?: RNG) => {
|
||||
coefficients: bigint[];
|
||||
commitment: TRet<Point[]>;
|
||||
secret: bigint;
|
||||
};
|
||||
};
|
||||
};
|
||||
export declare function createFROST<P extends FROSTPoint<P>>(opts: FrostOpts<P>): TRet<FROST>;
|
||||
export {};
|
||||
//# sourceMappingURL=frost.d.ts.map
|
||||
1
node_modules/@noble/curves/abstract/frost.d.ts.map
generated
vendored
Normal file
1
node_modules/@noble/curves/abstract/frost.d.ts.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
704
node_modules/@noble/curves/abstract/frost.js
generated
vendored
Normal file
704
node_modules/@noble/curves/abstract/frost.js
generated
vendored
Normal file
@@ -0,0 +1,704 @@
|
||||
/**
|
||||
* FROST: Flexible Round-Optimized Schnorr Threshold Protocol for Two-Round Schnorr Signatures.
|
||||
*
|
||||
* See [RFC 9591](https://datatracker.ietf.org/doc/rfc9591/) and [frost.zfnd.org](https://frost.zfnd.org).
|
||||
* @module
|
||||
*/
|
||||
import { utf8ToBytes } from '@noble/hashes/utils.js';
|
||||
import { bytesToHex, bytesToNumberBE, bytesToNumberLE, concatBytes, hexToBytes, randomBytes, validateObject, } from "../utils.js";
|
||||
import { pippenger, validatePointCons } from "./curve.js";
|
||||
import { poly } from "./fft.js";
|
||||
import {} from "./hash-to-curve.js";
|
||||
import { getMinHashLength, mapHashToField } from "./modular.js";
|
||||
// PubKey = commitments, verifyingShares
|
||||
// PrivKey = id, signingShare, commitment
|
||||
const validateSigners = (signers) => {
|
||||
if (!Number.isSafeInteger(signers.min) || !Number.isSafeInteger(signers.max))
|
||||
throw new Error('Wrong signers info: min=' + signers.min + ' max=' + signers.max);
|
||||
// Compatibility with frost-rs intentionally narrows RFC 9591's positive-nonzero threshold rule
|
||||
// to `min >= 2`, even though the RFC text itself allows `MIN_PARTICIPANTS = 1`.
|
||||
// This API is for actual threshold signing across participants; 1-of-n degenerates to ordinary
|
||||
// single-signer mode, which does not need FROST's network/coordination machinery at all.
|
||||
if (signers.min < 2 || signers.max < 2 || signers.min > signers.max)
|
||||
throw new Error('Wrong signers info: min=' + signers.min + ' max=' + signers.max);
|
||||
};
|
||||
const validateCommitmentsNum = (signers, len) => {
|
||||
// RFC 9591 Sections 5.2/5.3 require MIN_PARTICIPANTS <= NUM_PARTICIPANTS <= MAX_PARTICIPANTS.
|
||||
if (len < signers.min || len > signers.max)
|
||||
throw new Error('Wrong number of commitments=' + len);
|
||||
};
|
||||
class AggErr extends Error {
|
||||
// Empty means aggregation failed before per-share verification could attribute a signer.
|
||||
cheaters;
|
||||
constructor(msg, cheaters) {
|
||||
super(msg);
|
||||
this.cheaters = cheaters;
|
||||
}
|
||||
}
|
||||
export function createFROST(opts) {
|
||||
validateObject(opts, {
|
||||
name: 'string',
|
||||
hash: 'function',
|
||||
}, {
|
||||
hashToScalar: 'function',
|
||||
validatePoint: 'function',
|
||||
parsePublicKey: 'function',
|
||||
adjustScalar: 'function',
|
||||
adjustPoint: 'function',
|
||||
challenge: 'function',
|
||||
adjustNonces: 'function',
|
||||
adjustSecret: 'function',
|
||||
adjustPublic: 'function',
|
||||
adjustGroupCommitmentShare: 'function',
|
||||
adjustDKG: 'function',
|
||||
});
|
||||
// Cheap constructor-surface sanity check only: this verifies the generic static hooks/fields that
|
||||
// FROST consumes, but it does not certify point semantics like BASE/ZERO correctness.
|
||||
validatePointCons(opts.Point);
|
||||
const { Point } = opts;
|
||||
const Fn = opts.Fn === undefined ? Point.Fn : opts.Fn;
|
||||
// Hashes
|
||||
const hashBytes = opts.hash;
|
||||
const hashToScalar = opts.hashToScalar === undefined
|
||||
? (msg, opts = { DST: new Uint8Array() }) => {
|
||||
const t = hashBytes(concatBytes(opts.DST, msg));
|
||||
return Fn.create(Fn.isLE ? bytesToNumberLE(t) : bytesToNumberBE(t));
|
||||
}
|
||||
: opts.hashToScalar;
|
||||
const H1Prefix = utf8ToBytes(opts.H1 !== undefined ? opts.H1 : opts.name + 'rho');
|
||||
const H2Prefix = utf8ToBytes(opts.H2 !== undefined ? opts.H2 : opts.name + 'chal');
|
||||
const H3Prefix = utf8ToBytes(opts.H3 !== undefined ? opts.H3 : opts.name + 'nonce');
|
||||
const H4Prefix = utf8ToBytes(opts.H4 !== undefined ? opts.H4 : opts.name + 'msg');
|
||||
const H5Prefix = utf8ToBytes(opts.H5 !== undefined ? opts.H5 : opts.name + 'com');
|
||||
const HDKGPrefix = utf8ToBytes(opts.HDKG !== undefined ? opts.HDKG : opts.name + 'dkg');
|
||||
const HIDPrefix = utf8ToBytes(opts.HID !== undefined ? opts.HID : opts.name + 'id');
|
||||
const H1 = (msg) => hashToScalar(msg, { DST: H1Prefix });
|
||||
// Empty H2 still passes `{ DST: new Uint8Array() }` into custom hashToScalar hooks.
|
||||
// The built-in fallback hashes that identically to omitted DST, which is how
|
||||
// the Ed25519 suite models RFC 9591's undecorated H2 challenge hash.
|
||||
const H2 = (msg) => hashToScalar(msg, { DST: H2Prefix });
|
||||
const H3 = (msg) => hashToScalar(msg, { DST: H3Prefix });
|
||||
const H4 = (msg) => hashBytes(concatBytes(H4Prefix, msg));
|
||||
const H5 = (msg) => hashBytes(concatBytes(H5Prefix, msg));
|
||||
const HDKG = (msg) => hashToScalar(msg, { DST: HDKGPrefix });
|
||||
const HID = (msg) => hashToScalar(msg, { DST: HIDPrefix });
|
||||
// /Hashes
|
||||
const randomScalar = (rng = randomBytes) => {
|
||||
// Intentional divergence from RFC 9591 §4.1 / §5.1: the RFC nonce_generate helper outputs a
|
||||
// Scalar in [0, p-1], but round-one commit publishes ScalarBaseMult(nonce) values and §3.1
|
||||
// requires SerializeElement / DeserializeElement to reject the identity element. Keep noble's
|
||||
// mapHashToField generation here so round-one public nonce commitments stay in 1..n-1.
|
||||
const t = mapHashToField(rng(getMinHashLength(Fn.ORDER)), Fn.ORDER, Fn.isLE);
|
||||
// We cannot use Fn.fromBytes here because the field can have a different
|
||||
// byte width, like ed448.
|
||||
return Fn.isLE ? bytesToNumberLE(t) : bytesToNumberBE(t);
|
||||
};
|
||||
const serializePoint = (p) => p.toBytes();
|
||||
const parsePoint = (bytes) => {
|
||||
// RFC 9591 Section 3.1 requires DeserializeElement validation. Suite-specific validatePoint
|
||||
// hooks tighten this further for ciphersuites in Section 6. Bare createFROST(...) only gets
|
||||
// canonical point decoding unless the caller installs those extra subgroup / identity checks.
|
||||
const p = Point.fromBytes(bytes);
|
||||
if (opts.validatePoint)
|
||||
opts.validatePoint(p);
|
||||
return p;
|
||||
};
|
||||
// RFC 9591 Sections 4.1/5.1 model each participant's round-one output as two public commitments.
|
||||
const nonceCommitments = (identifier, nonces) => ({
|
||||
identifier,
|
||||
hiding: serializePoint(Point.BASE.multiply(Fn.fromBytes(nonces.hiding))),
|
||||
binding: serializePoint(Point.BASE.multiply(Fn.fromBytes(nonces.binding))),
|
||||
});
|
||||
const adjustPoint = opts.adjustPoint === undefined ? (n) => n : opts.adjustPoint;
|
||||
// We use hex to make it easier to use inside objects
|
||||
const validateIdentifier = (n) => {
|
||||
// Identifiers are canonical non-zero scalars. Custom / derived identifiers are allowed, so this
|
||||
// is intentionally not bounded by the current signers.max slot count.
|
||||
if (!Fn.isValid(n) || Fn.is0(n))
|
||||
throw new Error('Invalid identifier ' + n);
|
||||
return n;
|
||||
};
|
||||
const serializeIdentifier = (id) => bytesToHex(Fn.toBytes(validateIdentifier(id)));
|
||||
const parseIdentifier = (id) => {
|
||||
const n = validateIdentifier(Fn.fromBytes(hexToBytes(id)));
|
||||
// Keep string-keyed maps stable by accepting only the canonical serialized form.
|
||||
if (serializeIdentifier(n) !== id)
|
||||
throw new Error('expected canonical identifier hex');
|
||||
return n;
|
||||
};
|
||||
const Signature = {
|
||||
// RFC 9591 Appendix A encodes signatures canonically as
|
||||
// SerializeElement(R) || SerializeScalar(z).
|
||||
encode: (R, z) => {
|
||||
let res = concatBytes(serializePoint(R), Fn.toBytes(z));
|
||||
if (opts.adjustTx)
|
||||
res = opts.adjustTx.encode(res);
|
||||
return res;
|
||||
},
|
||||
decode: (sig) => {
|
||||
if (opts.adjustTx)
|
||||
sig = opts.adjustTx.decode(sig);
|
||||
// We don't know size of point, but we know size of scalar
|
||||
const R = parsePoint(sig.subarray(0, -Fn.BYTES));
|
||||
const z = Fn.fromBytes(sig.subarray(-Fn.BYTES));
|
||||
return { R, z };
|
||||
},
|
||||
};
|
||||
// Generates pair of (scalar, point)
|
||||
const genPointScalarPair = (rng = randomBytes) => {
|
||||
let n = randomScalar(rng);
|
||||
if (opts.adjustScalar)
|
||||
n = opts.adjustScalar(n);
|
||||
let p = Point.BASE.multiply(n);
|
||||
return { scalar: n, point: p };
|
||||
};
|
||||
// No roots here: root-based methods will throw.
|
||||
// `poly` expects a structured roots-of-unity domain, but FROST uses an
|
||||
// arbitrary domain and only needs the non-root operations below.
|
||||
const nrErr = 'roots are unavailable in FROST polynomial mode';
|
||||
const noRoots = {
|
||||
info: { G: Fn.ZERO, oddFactor: Fn.ZERO, powerOfTwo: 0 },
|
||||
roots() {
|
||||
throw new Error(nrErr);
|
||||
},
|
||||
brp() {
|
||||
throw new Error(nrErr);
|
||||
},
|
||||
inverse() {
|
||||
throw new Error(nrErr);
|
||||
},
|
||||
omega() {
|
||||
throw new Error(nrErr);
|
||||
},
|
||||
clear() { },
|
||||
};
|
||||
const Poly = poly(Fn, noRoots);
|
||||
const msm = (points, scalars) => pippenger(Point, points, scalars);
|
||||
// Internal stuff uses bigints & Points, external Uint8Arrays
|
||||
const polynomialEvaluate = (x, coeffs) => {
|
||||
if (!coeffs.length)
|
||||
throw new Error('empty coefficients');
|
||||
return Poly.monomial.eval(coeffs, x);
|
||||
};
|
||||
const deriveInterpolatingValue = (L, xi) => {
|
||||
const err = 'invalid parameters';
|
||||
// Generates lagrange coefficient
|
||||
if (!L.some((x) => Fn.eql(x, xi)))
|
||||
throw new Error(err);
|
||||
// Throws error if any x-coordinate is represented more than once in L.
|
||||
const Lset = new Set(L);
|
||||
if (Lset.size !== L.length)
|
||||
throw new Error(err);
|
||||
// Or if xi is missing
|
||||
if (!Lset.has(xi))
|
||||
throw new Error(err);
|
||||
let num = Fn.ONE;
|
||||
let den = Fn.ONE;
|
||||
for (const x of L) {
|
||||
if (Fn.eql(x, xi))
|
||||
continue;
|
||||
num = Fn.mul(num, x); // num *= x
|
||||
den = Fn.mul(den, Fn.sub(x, xi)); // RFC 9591 §4.2: denominator *= x_j - x_i
|
||||
}
|
||||
return Fn.div(num, den);
|
||||
};
|
||||
const evalutateVSS = (identifier, commitment) => {
|
||||
// RFC 9591 Appendix C.2: S_i' = Σ_j ScalarMult(vss_commitment[j], i^j).
|
||||
const monomial = Poly.monomial.basis(identifier, commitment.length);
|
||||
return msm(commitment, monomial);
|
||||
};
|
||||
// High-level internal stuff
|
||||
const generateSecretPolynomial = (signers, secret, coeffs, rng = randomBytes) => {
|
||||
validateSigners(signers);
|
||||
// Dealer/DKG polynomial sampling reuses the same hardened scalar derivation as round-one
|
||||
// nonces: overriding `rng` only swaps the entropy source, not the non-zero `1..n-1` policy.
|
||||
const secretScalar = secret === undefined ? randomScalar(rng) : Fn.fromBytes(secret);
|
||||
if (!coeffs) {
|
||||
coeffs = [];
|
||||
for (let i = 0; i < signers.min - 1; i++)
|
||||
coeffs.push(randomScalar(rng));
|
||||
}
|
||||
if (coeffs.length !== signers.min - 1)
|
||||
throw new Error('wrong coefficients length');
|
||||
const coefficients = [secretScalar, ...coeffs];
|
||||
// RFC 9591 Appendix C.2 commits to every polynomial coefficient with ScalarBaseMult.
|
||||
const commitment = coefficients.map((i) => Point.BASE.multiply(i));
|
||||
return { coefficients, commitment, secret: secretScalar };
|
||||
};
|
||||
// Pretty much sign+verify, same as basic
|
||||
const ProofOfKnowledge = {
|
||||
challenge: (id, verKey, R) => HDKG(concatBytes(Fn.toBytes(id), serializePoint(verKey), serializePoint(R))),
|
||||
compute(id, coefficents, commitments, rng = randomBytes) {
|
||||
if (coefficents.length < 1)
|
||||
throw new Error('coefficients should have at least one element');
|
||||
const { point: R, scalar: k } = genPointScalarPair(rng);
|
||||
const verKey = commitments[0]; // verify key is first one
|
||||
const c = this.challenge(id, verKey, R);
|
||||
const mu = Fn.add(k, Fn.mul(coefficents[0], c)); // mu = k + coeff[0] * c
|
||||
return Signature.encode(R, mu);
|
||||
},
|
||||
validate(id, commitment, proof) {
|
||||
if (commitment.length < 1)
|
||||
throw new Error('commitment should have at least one element');
|
||||
const { R, z } = Signature.decode(proof);
|
||||
const phi = parsePoint(commitment[0]);
|
||||
const c = this.challenge(id, phi, R);
|
||||
// R === z*G - phi*c
|
||||
if (!R.equals(Point.BASE.multiply(z).subtract(phi.multiply(c))))
|
||||
throw new Error('invalid proof of knowledge');
|
||||
},
|
||||
};
|
||||
const Basic = {
|
||||
challenge: (R, PK, msg) => {
|
||||
if (opts.challenge)
|
||||
return opts.challenge(R, PK, msg);
|
||||
return H2(concatBytes(serializePoint(R), serializePoint(PK), msg));
|
||||
},
|
||||
sign(msg, sk, rng = randomBytes) {
|
||||
const { point: R, scalar: r } = genPointScalarPair(rng);
|
||||
const PK = Point.BASE.multiply(sk); // sk*G
|
||||
const c = this.challenge(R, PK, msg);
|
||||
const z = Fn.add(r, Fn.mul(c, sk)); // r + c * sk
|
||||
return [R, z];
|
||||
},
|
||||
verify(msg, R, z, PK) {
|
||||
if (opts.adjustPoint)
|
||||
PK = opts.adjustPoint(PK);
|
||||
if (opts.adjustPoint)
|
||||
R = opts.adjustPoint(R);
|
||||
const c = this.challenge(R, PK, msg);
|
||||
const zB = Point.BASE.multiply(z); // z*G
|
||||
const cA = PK.multiply(c); // c*PK
|
||||
let check = zB.subtract(cA).subtract(R); // zB - cA - R
|
||||
// No clearCoffactor on ristretto
|
||||
if (check.clearCofactor)
|
||||
check = check.clearCofactor();
|
||||
return Point.ZERO.equals(check);
|
||||
},
|
||||
};
|
||||
// === vssVerify
|
||||
const validateSecretShare = (identifier, commitment, signingShare) => {
|
||||
// RFC 9591 Appendix C.2 `vss_verify(share_i, vss_commitment)` is purely algebraic.
|
||||
// Public FROST packages still go through Section 3.1 element encoding,
|
||||
// which rejects identity points, so a zero share or commitment does not
|
||||
// become valid wire data just because VSS matches.
|
||||
if (!Point.BASE.multiply(signingShare).equals(evalutateVSS(identifier, commitment)))
|
||||
throw new Error('invalid secret share');
|
||||
};
|
||||
const Identifier = {
|
||||
fromNumber(n) {
|
||||
if (!Number.isSafeInteger(n))
|
||||
throw new Error('expected safe interger');
|
||||
return serializeIdentifier(BigInt(n));
|
||||
},
|
||||
// Not in spec, but in FROST implementation,
|
||||
// seems useful and nice, no need to sync identifiers (would require more interactions)
|
||||
derive(s) {
|
||||
if (typeof s !== 'string')
|
||||
throw new Error('wrong identifier string: ' + s);
|
||||
// Derived identifiers may land anywhere in the scalar field; they are not restricted to
|
||||
// sequential `1..max_signers` values.
|
||||
return serializeIdentifier(HID(utf8ToBytes(s)));
|
||||
},
|
||||
};
|
||||
// RFC 9591 §4.1: nonce_generate() hashes 32 fresh RNG bytes with SerializeScalar(secret).
|
||||
const generateNonce = (secret, rng = randomBytes) => H3(concatBytes(rng(32), Fn.toBytes(secret)));
|
||||
const getGroupCommitment = (GPK, commitmentList, msg) => {
|
||||
const CL = commitmentList.map((i) => [
|
||||
i.identifier,
|
||||
parseIdentifier(i.identifier),
|
||||
parsePoint(i.hiding),
|
||||
parsePoint(i.binding),
|
||||
]);
|
||||
// RFC 9591 Sections 4.3/4.4/4.5 and 5.2/5.3 treat commitment_list as sorted by identifier.
|
||||
CL.sort((a, b) => (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0));
|
||||
// Encode commitment list
|
||||
const Cbytes = [];
|
||||
for (const [_, id, hC, bC] of CL)
|
||||
Cbytes.push(Fn.toBytes(id), serializePoint(hC), serializePoint(bC));
|
||||
const encodedCommitmentHash = H5(concatBytes(...Cbytes));
|
||||
const rhoPrefix = concatBytes(serializePoint(GPK), H4(msg), encodedCommitmentHash);
|
||||
// Compute binding factors
|
||||
const bindingFactors = {};
|
||||
for (const [i, id] of CL) {
|
||||
bindingFactors[i] = H1(concatBytes(rhoPrefix, Fn.toBytes(id)));
|
||||
}
|
||||
const points = [];
|
||||
const scalars = [];
|
||||
for (const [i, _, hC, bC] of CL) {
|
||||
if (Point.ZERO.equals(hC) || Point.ZERO.equals(bC))
|
||||
throw new Error('infinity commitment');
|
||||
points.push(hC, bC);
|
||||
scalars.push(Fn.ONE, bindingFactors[i]);
|
||||
}
|
||||
const groupCommitment = msm(points, scalars); // GC += hC + bC*bindingFactor
|
||||
const identifiers = CL.map((i) => i[1]);
|
||||
return { identifiers, groupCommitment, bindingFactors };
|
||||
};
|
||||
const prepareShare = (PK, commitmentList, msg, identifier) => {
|
||||
// RFC 9591 Sections 4.4/4.5/4.6 feed directly into the Section 5.2 signer computation.
|
||||
const GPK = adjustPoint(parsePoint(PK));
|
||||
const id = parseIdentifier(identifier);
|
||||
const { identifiers, groupCommitment, bindingFactors } = getGroupCommitment(GPK, commitmentList, msg);
|
||||
const bindingFactor = bindingFactors[identifier];
|
||||
const lambda = deriveInterpolatingValue(identifiers, id);
|
||||
const challenge = Basic.challenge(groupCommitment, GPK, msg);
|
||||
return { lambda, challenge, bindingFactor, groupCommitment };
|
||||
};
|
||||
Object.freeze(Identifier);
|
||||
const frost = {
|
||||
Identifier,
|
||||
// DKG is Distributed Key Generation, not Trusted Dealer Key Generation.
|
||||
DKG: Object.freeze({
|
||||
// NOTE: we allow to pass secret scalar from user side,
|
||||
// this way it can be derived, instead of random generation
|
||||
round1: (id, signers, secret, rng = randomBytes) => {
|
||||
validateSigners(signers);
|
||||
const idNum = parseIdentifier(id);
|
||||
const { coefficients, commitment } = generateSecretPolynomial(signers, secret, undefined, rng);
|
||||
const proofOfKnowledge = ProofOfKnowledge.compute(idNum, coefficients, commitment, rng);
|
||||
const commitmentBytes = commitment.map(serializePoint);
|
||||
const round1Public = {
|
||||
identifier: serializeIdentifier(idNum),
|
||||
commitment: commitmentBytes,
|
||||
proofOfKnowledge,
|
||||
};
|
||||
// store secret information for signing
|
||||
const round1Secret = {
|
||||
identifier: idNum,
|
||||
coefficients,
|
||||
commitment: commitment.map(serializePoint),
|
||||
// Copy threshold metadata instead of retaining the caller-owned object by reference.
|
||||
signers: { min: signers.min, max: signers.max },
|
||||
step: 1,
|
||||
};
|
||||
return { public: round1Public, secret: round1Secret };
|
||||
},
|
||||
round2: (secret, others) => {
|
||||
if (others.length !== secret.signers.max - 1)
|
||||
throw new Error('wrong number of round1 packages');
|
||||
if (!secret.coefficients || secret.step === 3)
|
||||
throw new Error('round3 package used in round2');
|
||||
const res = {};
|
||||
for (const p of others) {
|
||||
if (p.commitment.length !== secret.signers.min)
|
||||
throw new Error('wrong number of commitments');
|
||||
const id = parseIdentifier(p.identifier);
|
||||
if (id === secret.identifier)
|
||||
throw new Error('duplicate id=' + serializeIdentifier(id));
|
||||
ProofOfKnowledge.validate(id, p.commitment, p.proofOfKnowledge);
|
||||
for (const c of p.commitment)
|
||||
parsePoint(c);
|
||||
if (res[p.identifier])
|
||||
throw new Error('Duplicate id=' + id);
|
||||
const signingShare = Fn.toBytes(polynomialEvaluate(id, secret.coefficients));
|
||||
res[p.identifier] = {
|
||||
identifier: serializeIdentifier(secret.identifier),
|
||||
signingShare: signingShare,
|
||||
};
|
||||
}
|
||||
secret.step = 2;
|
||||
return res;
|
||||
},
|
||||
round3: (secret, round1, round2) => {
|
||||
// DKG is outside RFC 9591's signing flow; callers are expected to reuse the same
|
||||
// remote round1 packages already accepted in round2, like frost-rs documents.
|
||||
if (round1.length !== secret.signers.max - 1)
|
||||
throw new Error('wrong length of round1 packages');
|
||||
if (!secret.coefficients || secret.step !== 2)
|
||||
throw new Error('round2 package used in round3');
|
||||
if (round2.length !== round1.length)
|
||||
throw new Error('wrong length of round2 packages');
|
||||
const merged = {};
|
||||
for (const r1 of round1) {
|
||||
if (!r1.identifier || !r1.commitment)
|
||||
throw new Error('wrong round1 share');
|
||||
merged[r1.identifier] = { ...r1 };
|
||||
}
|
||||
for (const r2 of round2) {
|
||||
if (!r2.identifier || !r2.signingShare)
|
||||
throw new Error('wrong round2 share');
|
||||
if (!merged[r2.identifier])
|
||||
throw new Error('round1 share for ' + r2.identifier + ' is missing');
|
||||
merged[r2.identifier].signingShare = r2.signingShare;
|
||||
}
|
||||
if (Object.keys(merged).length !== round1.length)
|
||||
throw new Error('mismatch identifiers between rounds');
|
||||
let signingShare = Fn.ZERO;
|
||||
if (secret.commitment.length !== secret.signers.min)
|
||||
throw new Error('wrong commitments length');
|
||||
const localCommitment = secret.commitment.map(parsePoint);
|
||||
const localShare = polynomialEvaluate(secret.identifier, secret.coefficients);
|
||||
validateSecretShare(secret.identifier, localCommitment, localShare);
|
||||
const localCommitmentBytes = localCommitment.map(serializePoint);
|
||||
const commitments = {
|
||||
[serializeIdentifier(secret.identifier)]: localCommitmentBytes,
|
||||
};
|
||||
for (const k in merged) {
|
||||
const v = merged[k];
|
||||
if (!v.signingShare || !v.commitment)
|
||||
throw new Error('mismatch identifiers');
|
||||
const id = parseIdentifier(k); // from
|
||||
const signingSharePart = Fn.fromBytes(v.signingShare);
|
||||
const commitment = v.commitment.map(parsePoint);
|
||||
validateSecretShare(secret.identifier, commitment, signingSharePart);
|
||||
signingShare = Fn.add(signingShare, signingSharePart);
|
||||
const idSer = serializeIdentifier(id);
|
||||
if (commitments[idSer])
|
||||
throw new Error('duplicated id=' + idSer);
|
||||
commitments[idSer] = v.commitment;
|
||||
}
|
||||
signingShare = Fn.add(signingShare, localShare);
|
||||
const mergedCommitment = new Array(secret.signers.min).fill(Point.ZERO);
|
||||
for (const k in commitments) {
|
||||
const v = commitments[k];
|
||||
if (v.length !== secret.signers.min)
|
||||
throw new Error('wrong commitments length');
|
||||
for (let i = 0; i < v.length; i++)
|
||||
mergedCommitment[i] = mergedCommitment[i].add(parsePoint(v[i]));
|
||||
}
|
||||
const mergedCommitmentBytes = mergedCommitment.map(serializePoint);
|
||||
const verifyingShares = {};
|
||||
for (const k in commitments)
|
||||
verifyingShares[k] = serializePoint(evalutateVSS(parseIdentifier(k), mergedCommitment));
|
||||
// This is enough to sign stuff
|
||||
let res = {
|
||||
public: {
|
||||
signers: { min: secret.signers.min, max: secret.signers.max },
|
||||
commitments: mergedCommitmentBytes,
|
||||
verifyingShares: Object.fromEntries(Object.entries(verifyingShares).map(([k, v]) => [k, v.slice()])),
|
||||
},
|
||||
secret: {
|
||||
identifier: serializeIdentifier(secret.identifier),
|
||||
signingShare: Fn.toBytes(signingShare),
|
||||
},
|
||||
};
|
||||
if (opts.adjustDKG)
|
||||
res = opts.adjustDKG(res);
|
||||
for (let i = 0; i < secret.coefficients.length; i++)
|
||||
secret.coefficients[i] -= secret.coefficients[i];
|
||||
delete secret.coefficients;
|
||||
secret.step = 3;
|
||||
return res;
|
||||
},
|
||||
clean(secret) {
|
||||
// Instead of replacing secret bigint with another (zero?), we subtract it from itself
|
||||
// in the hope that JIT will modify it inplace, instead of creating new value.
|
||||
// This is unverified and may not work, but it is best we can do in regard of bigints.
|
||||
secret.identifier -= secret.identifier;
|
||||
if (secret.coefficients) {
|
||||
for (let i = 0; i < secret.coefficients.length; i++)
|
||||
secret.coefficients[i] -= secret.coefficients[i];
|
||||
}
|
||||
// for (const c of secret.commitment) c.fill(0);
|
||||
secret.step = 3;
|
||||
},
|
||||
}),
|
||||
// Trusted dealer setup
|
||||
// Generates keys for all participants
|
||||
trustedDealer(signers, identifiers, secret, rng = randomBytes) {
|
||||
// if no identifiers provided, we generated default identifiers
|
||||
validateSigners(signers);
|
||||
if (identifiers === undefined) {
|
||||
identifiers = [];
|
||||
for (let i = 1; i <= signers.max; i++)
|
||||
identifiers.push(Identifier.fromNumber(i));
|
||||
}
|
||||
else {
|
||||
if (!Array.isArray(identifiers) || identifiers.length !== signers.max)
|
||||
throw new Error('identifiers should be array of ' + signers.max);
|
||||
}
|
||||
const identifierNums = {};
|
||||
for (const id of identifiers) {
|
||||
const idNum = parseIdentifier(id);
|
||||
if (id in identifierNums)
|
||||
throw new Error('duplicated id=' + id);
|
||||
identifierNums[id] = idNum;
|
||||
}
|
||||
const sp = generateSecretPolynomial(signers, secret, undefined, rng);
|
||||
const commitmentBytes = sp.commitment.map(serializePoint);
|
||||
const secretShares = {};
|
||||
const verifyingShares = {};
|
||||
for (const id of identifiers) {
|
||||
const signingShare = polynomialEvaluate(identifierNums[id], sp.coefficients);
|
||||
verifyingShares[id] = serializePoint(Point.BASE.multiply(signingShare));
|
||||
secretShares[id] = {
|
||||
identifier: id,
|
||||
signingShare: Fn.toBytes(signingShare),
|
||||
};
|
||||
}
|
||||
return {
|
||||
public: {
|
||||
signers: { min: signers.min, max: signers.max },
|
||||
commitments: commitmentBytes,
|
||||
verifyingShares,
|
||||
},
|
||||
secretShares,
|
||||
};
|
||||
},
|
||||
// Validate secret (from trusted dealer or DKG)
|
||||
validateSecret(secret, pub) {
|
||||
const id = parseIdentifier(secret.identifier);
|
||||
const commitment = pub.commitments.map(parsePoint);
|
||||
const signingShare = Fn.fromBytes(secret.signingShare);
|
||||
validateSecretShare(id, commitment, signingShare);
|
||||
},
|
||||
// Actual signing
|
||||
// Round 1: each participant commit to nonces
|
||||
// Nonces kept private, commitments sent to coordinator (or every other participant)
|
||||
// NOTE: we don't need the message at this point, which lets a coordinator
|
||||
// keep multiple nonce commitments per participant in advance and skip
|
||||
// round1 for signing.
|
||||
// But then each participant needs to remember generated shares
|
||||
commit(secret, rng = randomBytes) {
|
||||
const secretScalar = Fn.fromBytes(secret.signingShare);
|
||||
const hiding = generateNonce(secretScalar, rng);
|
||||
const binding = generateNonce(secretScalar, rng);
|
||||
const nonces = { hiding: Fn.toBytes(hiding), binding: Fn.toBytes(binding) };
|
||||
return { nonces, commitments: nonceCommitments(secret.identifier, nonces) };
|
||||
},
|
||||
// Round2: sign. Each participant creates a signature share from the secret
|
||||
// and the selected nonce commitments.
|
||||
signShare(secret, pub, nonces, commitmentList, msg) {
|
||||
validateCommitmentsNum(pub.signers, commitmentList.length);
|
||||
const hidingNonce0 = Fn.fromBytes(nonces.hiding);
|
||||
const bindingNonce0 = Fn.fromBytes(nonces.binding);
|
||||
if (Fn.is0(hidingNonce0) || Fn.is0(bindingNonce0))
|
||||
throw new Error('signing nonces already used');
|
||||
// Reject a coordinator-assigned commitment pair that does not match the signer's own nonce
|
||||
// pair. This must happen before suite-specific nonce adjustment; secp256k1-tr may negate the
|
||||
// actual signing nonces later, but the coordinator still assigns the original commitments.
|
||||
const expectedCommitment = {
|
||||
identifier: secret.identifier,
|
||||
hiding: serializePoint(Point.BASE.multiply(hidingNonce0)),
|
||||
binding: serializePoint(Point.BASE.multiply(bindingNonce0)),
|
||||
};
|
||||
const commitment = commitmentList.find((i) => i.identifier === secret.identifier);
|
||||
if (!commitment)
|
||||
throw new Error('missing signer commitment');
|
||||
if (bytesToHex(commitment.hiding) !== bytesToHex(expectedCommitment.hiding) ||
|
||||
bytesToHex(commitment.binding) !== bytesToHex(expectedCommitment.binding))
|
||||
throw new Error('incorrect signer commitment');
|
||||
if (opts.adjustSecret)
|
||||
secret = opts.adjustSecret(secret, pub);
|
||||
if (opts.adjustPublic)
|
||||
pub = opts.adjustPublic(pub);
|
||||
const SK = Fn.fromBytes(secret.signingShare);
|
||||
const { lambda, challenge, bindingFactor, groupCommitment } = prepareShare(pub.commitments[0], commitmentList, msg, secret.identifier);
|
||||
const N = opts.adjustNonces ? opts.adjustNonces(groupCommitment, nonces) : nonces;
|
||||
const hidingNonce = opts.adjustNonces ? Fn.fromBytes(N.hiding) : hidingNonce0;
|
||||
const bindingNonce = opts.adjustNonces ? Fn.fromBytes(N.binding) : bindingNonce0;
|
||||
const t = Fn.mul(Fn.mul(lambda, SK), challenge); // challenge * lambda * SK
|
||||
const t2 = Fn.mul(bindingNonce, bindingFactor); // bindingNonce * bindingFactor
|
||||
const r = Fn.toBytes(Fn.add(Fn.add(hidingNonce, t2), t)); // t + t2 + hidingNonce
|
||||
// RFC 9591 round-one commitments are one-time-use, and round two must use the nonce
|
||||
// corresponding to the published commitment. This API returns mutable local nonce bytes,
|
||||
// so consume them after a successful signShare() call: later all-zero reuse fails closed.
|
||||
nonces.hiding.fill(0);
|
||||
nonces.binding.fill(0);
|
||||
return r;
|
||||
},
|
||||
// Each participant (or coordinator) can verify signatures from other participants
|
||||
verifyShare(pub, commitmentList, msg, identifier, sigShare) {
|
||||
if (opts.adjustPublic)
|
||||
pub = opts.adjustPublic(pub);
|
||||
const comm = commitmentList.find((i) => i.identifier === identifier);
|
||||
if (!comm)
|
||||
throw new Error('cannot find identifier commitment');
|
||||
const PK = parsePoint(pub.verifyingShares[identifier]);
|
||||
const hidingNonceCommitment = parsePoint(comm.hiding);
|
||||
const bindingNonceCommitment = parsePoint(comm.binding);
|
||||
const { lambda, challenge, bindingFactor, groupCommitment } = prepareShare(pub.commitments[0], commitmentList, msg, identifier);
|
||||
// hC + bC * bF
|
||||
let commShare = hidingNonceCommitment.add(bindingNonceCommitment.multiply(bindingFactor));
|
||||
if (opts.adjustGroupCommitmentShare)
|
||||
commShare = opts.adjustGroupCommitmentShare(groupCommitment, commShare);
|
||||
const l = Point.BASE.multiply(Fn.fromBytes(sigShare)); // sigShare*G
|
||||
// commShare + PK * (challenge * lambda)
|
||||
const r = commShare.add(PK.multiply(Fn.mul(challenge, lambda)));
|
||||
return l.equals(r);
|
||||
},
|
||||
// Aggregate multiple signature shares into groupSignature
|
||||
aggregate(pub, commitmentList, msg, sigShares) {
|
||||
if (opts.adjustPublic)
|
||||
pub = opts.adjustPublic(pub);
|
||||
try {
|
||||
validateCommitmentsNum(pub.signers, commitmentList.length);
|
||||
}
|
||||
catch {
|
||||
throw new AggErr('aggregation failed', []);
|
||||
}
|
||||
const ids = commitmentList.map((i) => i.identifier);
|
||||
if (ids.length !== Object.keys(sigShares).length)
|
||||
throw new AggErr('aggregation failed', []);
|
||||
for (const id of ids) {
|
||||
if (!(id in sigShares) || !(id in pub.verifyingShares))
|
||||
throw new AggErr('aggregation failed', []);
|
||||
}
|
||||
const GPK = parsePoint(pub.commitments[0]);
|
||||
const { groupCommitment } = getGroupCommitment(GPK, commitmentList, msg);
|
||||
let z = Fn.ZERO;
|
||||
// RFC 9591 Section 5.3 aggregates by summing the validated signature shares.
|
||||
for (const id of ids)
|
||||
z = Fn.add(z, Fn.fromBytes(sigShares[id])); // z += zi
|
||||
if (!Basic.verify(msg, groupCommitment, z, GPK)) {
|
||||
const cheaters = [];
|
||||
for (const id of ids) {
|
||||
if (!this.verifyShare(pub, commitmentList, msg, id, sigShares[id]))
|
||||
cheaters.push(id);
|
||||
}
|
||||
throw new AggErr('aggregation failed', cheaters);
|
||||
}
|
||||
return Signature.encode(groupCommitment, z);
|
||||
},
|
||||
// Basic sign/verify using single key
|
||||
sign(msg, secretKey) {
|
||||
let sk = Fn.fromBytes(secretKey);
|
||||
// Taproot single-key signing needs the same scalar normalization as threshold keys.
|
||||
if (opts.adjustScalar)
|
||||
sk = opts.adjustScalar(sk);
|
||||
const [R, z] = Basic.sign(msg, sk);
|
||||
return Signature.encode(R, z);
|
||||
},
|
||||
verify(sig, msg, publicKey) {
|
||||
const PK = opts.parsePublicKey ? opts.parsePublicKey(publicKey) : parsePoint(publicKey);
|
||||
const { R, z } = Signature.decode(sig);
|
||||
return Basic.verify(msg, R, z, PK);
|
||||
},
|
||||
// Combine multiple secret shares to restore secret
|
||||
combineSecret(shares, signers) {
|
||||
validateSigners(signers);
|
||||
if (!Array.isArray(shares) || shares.length < signers.min)
|
||||
throw new Error('wrong secret shares array');
|
||||
const points = [];
|
||||
const seen = {};
|
||||
// Interpolate over the full provided share set and reject duplicate identifiers.
|
||||
for (const s of shares) {
|
||||
const idNum = parseIdentifier(s.identifier);
|
||||
const id = serializeIdentifier(idNum);
|
||||
if (seen[id])
|
||||
throw new Error('duplicated id=' + id);
|
||||
seen[id] = true;
|
||||
points.push([idNum, Fn.fromBytes(s.signingShare)]);
|
||||
}
|
||||
const xCoords = points.map(([x]) => x);
|
||||
let res = Fn.ZERO;
|
||||
for (const [x, y] of points)
|
||||
res = Fn.add(res, Fn.mul(y, deriveInterpolatingValue(xCoords, x)));
|
||||
return Fn.toBytes(res);
|
||||
},
|
||||
// Utils
|
||||
utils: Object.freeze({
|
||||
Fn, // NOTE: we re-export it here because it may be different from Point.Fn (ed448 is fun!)
|
||||
// Test RNG overrides still go through noble's non-zero scalar derivation; this is not a raw
|
||||
// "bytes become scalar" escape hatch.
|
||||
randomScalar: (rng = randomBytes) => Fn.toBytes(genPointScalarPair(rng).scalar),
|
||||
generateSecretPolynomial: (signers, secret, coeffs, rng) => {
|
||||
const res = generateSecretPolynomial(signers, secret, coeffs, rng);
|
||||
return { ...res, commitment: res.commitment.map(serializePoint) };
|
||||
},
|
||||
}),
|
||||
};
|
||||
return Object.freeze(frost);
|
||||
}
|
||||
//# sourceMappingURL=frost.js.map
|
||||
1
node_modules/@noble/curves/abstract/frost.js.map
generated
vendored
Normal file
1
node_modules/@noble/curves/abstract/frost.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
239
node_modules/@noble/curves/abstract/hash-to-curve.d.ts
generated
vendored
Normal file
239
node_modules/@noble/curves/abstract/hash-to-curve.d.ts
generated
vendored
Normal file
@@ -0,0 +1,239 @@
|
||||
/**
|
||||
* hash-to-curve from RFC 9380.
|
||||
* Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.
|
||||
* https://www.rfc-editor.org/rfc/rfc9380
|
||||
* @module
|
||||
*/
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
import type { CHash, TArg, TRet } from '../utils.ts';
|
||||
import type { AffinePoint, PC_ANY, PC_F, PC_P } from './curve.ts';
|
||||
import { type IField } from './modular.ts';
|
||||
/** ASCII domain-separation tag or raw bytes. */
|
||||
export type AsciiOrBytes = string | Uint8Array;
|
||||
type H2CDefaults = {
|
||||
DST: AsciiOrBytes;
|
||||
expand: 'xmd' | 'xof';
|
||||
hash: CHash;
|
||||
p: bigint;
|
||||
m: number;
|
||||
k: number;
|
||||
encodeDST?: AsciiOrBytes;
|
||||
};
|
||||
/**
|
||||
* * `DST` is a domain separation tag, defined in section 2.2.5
|
||||
* * `p` characteristic of F, where F is a finite field of characteristic p and order q = p^m
|
||||
* * `m` is extension degree (1 for prime fields)
|
||||
* * `k` is the target security target in bits (e.g. 128), from section 5.1
|
||||
* * `expand` is `xmd` (SHA2, SHA3, BLAKE) or `xof` (SHAKE, BLAKE-XOF)
|
||||
* * `hash` conforming to `utils.CHash` interface, with `outputLen` / `blockLen` props
|
||||
*/
|
||||
export type H2COpts = {
|
||||
/** Domain separation tag. */
|
||||
DST: AsciiOrBytes;
|
||||
/** Expander family used by RFC 9380. */
|
||||
expand: 'xmd' | 'xof';
|
||||
/** Hash or XOF implementation used by the expander. */
|
||||
hash: CHash;
|
||||
/** Base-field characteristic. */
|
||||
p: bigint;
|
||||
/** Extension degree (`1` for prime fields). */
|
||||
m: number;
|
||||
/** Target security level in bits. */
|
||||
k: number;
|
||||
};
|
||||
/** Hash-only subset of RFC 9380 options used by per-call overrides. */
|
||||
export type H2CHashOpts = {
|
||||
/** Expander family used by RFC 9380. */
|
||||
expand: 'xmd' | 'xof';
|
||||
/** Hash or XOF implementation used by the expander. */
|
||||
hash: CHash;
|
||||
};
|
||||
/**
|
||||
* Map one hash-to-field output tuple onto affine curve coordinates.
|
||||
* Implementations receive the validated scalar tuple by reference for performance and MUST treat it
|
||||
* as read-only. Callers that need scratch space should copy before mutating.
|
||||
* @param scalar - Field-element tuple produced by `hash_to_field`.
|
||||
* @returns Affine point before subgroup clearing.
|
||||
*/
|
||||
export type MapToCurve<T> = (scalar: bigint[]) => AffinePoint<T>;
|
||||
/** Per-call override for the domain-separation tag. */
|
||||
export type H2CDSTOpts = {
|
||||
/** Domain-separation tag override. */
|
||||
DST: AsciiOrBytes;
|
||||
};
|
||||
/** Base hash-to-curve helpers shared by `hashToCurve` and `encodeToCurve`. */
|
||||
export type H2CHasherBase<PC extends PC_ANY> = {
|
||||
/**
|
||||
* Hash arbitrary bytes to one curve point.
|
||||
* @param msg - Input message bytes.
|
||||
* @param options - Optional domain-separation override. See {@link H2CDSTOpts}.
|
||||
* @returns Curve point after hash-to-curve.
|
||||
*/
|
||||
hashToCurve(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): PC_P<PC>;
|
||||
/**
|
||||
* Hash arbitrary bytes to one scalar.
|
||||
* @param msg - Input message bytes.
|
||||
* @param options - Optional domain-separation override. See {@link H2CDSTOpts}.
|
||||
* @returns Scalar reduced into the target field.
|
||||
*/
|
||||
hashToScalar(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): bigint;
|
||||
/**
|
||||
* Derive one curve point from non-uniform bytes without the random-oracle
|
||||
* guarantees of `hashToCurve`.
|
||||
* Accepts the same arguments as `hashToCurve`, but runs the encode-to-curve
|
||||
* path instead of the random-oracle construction.
|
||||
*/
|
||||
deriveToCurve?(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): PC_P<PC>;
|
||||
/** Point constructor for the target curve. */
|
||||
Point: PC;
|
||||
};
|
||||
/**
|
||||
* RFC 9380 methods, with cofactor clearing. See {@link https://www.rfc-editor.org/rfc/rfc9380#section-3 | RFC 9380 section 3}.
|
||||
*
|
||||
* * hashToCurve: `map(hash(input))`, encodes RANDOM bytes to curve (WITH hashing)
|
||||
* * encodeToCurve: `map(hash(input))`, encodes NON-UNIFORM bytes to curve (WITH hashing)
|
||||
* * mapToCurve: `map(scalars)`, encodes NON-UNIFORM scalars to curve (NO hashing)
|
||||
*/
|
||||
export type H2CHasher<PC extends PC_ANY> = H2CHasherBase<PC> & {
|
||||
/**
|
||||
* Encode non-uniform bytes to one curve point.
|
||||
* @param msg - Input message bytes.
|
||||
* @param options - Optional domain-separation override. See {@link H2CDSTOpts}.
|
||||
* @returns Curve point after encode-to-curve.
|
||||
*/
|
||||
encodeToCurve(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): PC_P<PC>;
|
||||
/** Deterministic map from `hash_to_field` tuples into affine coordinates. */
|
||||
mapToCurve: MapToCurve<PC_F<PC>>;
|
||||
/** Default RFC 9380 options captured by this hasher bundle. */
|
||||
defaults: H2CDefaults;
|
||||
};
|
||||
/**
|
||||
* Produces a uniformly random byte string using a cryptographic hash
|
||||
* function H that outputs b bits.
|
||||
* See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1 | RFC 9380 section 5.3.1}.
|
||||
* @param msg - Input message.
|
||||
* @param DST - Domain separation tag. This helper normalizes DST, rejects empty DSTs, and
|
||||
* oversize-hashes DST when needed.
|
||||
* @param lenInBytes - Output length.
|
||||
* @param H - Hash function.
|
||||
* @returns Uniform byte string.
|
||||
* @throws If the message, DST, hash, or output length is invalid. {@link Error}
|
||||
* @example
|
||||
* Expand one message into uniform bytes with the XMD construction.
|
||||
*
|
||||
* ```ts
|
||||
* import { expand_message_xmd } from '@noble/curves/abstract/hash-to-curve.js';
|
||||
* import { sha256 } from '@noble/hashes/sha2.js';
|
||||
* const uniform = expand_message_xmd(new TextEncoder().encode('hello noble'), 'DST', 32, sha256);
|
||||
* ```
|
||||
*/
|
||||
export declare function expand_message_xmd(msg: TArg<Uint8Array>, DST: TArg<AsciiOrBytes>, lenInBytes: number, H: TArg<CHash>): TRet<Uint8Array>;
|
||||
/**
|
||||
* Produces a uniformly random byte string using an extendable-output function (XOF) H.
|
||||
* 1. The collision resistance of H MUST be at least k bits.
|
||||
* 2. H MUST be an XOF that has been proved indifferentiable from
|
||||
* a random oracle under a reasonable cryptographic assumption.
|
||||
* See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2 | RFC 9380 section 5.3.2}.
|
||||
* @param msg - Input message.
|
||||
* @param DST - Domain separation tag. This helper normalizes DST, rejects empty DSTs, and
|
||||
* oversize-hashes DST when needed.
|
||||
* @param lenInBytes - Output length.
|
||||
* @param k - Target security level.
|
||||
* @param H - XOF hash function.
|
||||
* @returns Uniform byte string.
|
||||
* @throws If the message, DST, XOF, or output length is invalid. {@link Error}
|
||||
* @example
|
||||
* Expand one message into uniform bytes with the XOF construction.
|
||||
*
|
||||
* ```ts
|
||||
* import { expand_message_xof } from '@noble/curves/abstract/hash-to-curve.js';
|
||||
* import { shake256 } from '@noble/hashes/sha3.js';
|
||||
* const uniform = expand_message_xof(
|
||||
* new TextEncoder().encode('hello noble'),
|
||||
* 'DST',
|
||||
* 32,
|
||||
* 128,
|
||||
* shake256
|
||||
* );
|
||||
* ```
|
||||
*/
|
||||
export declare function expand_message_xof(msg: TArg<Uint8Array>, DST: TArg<AsciiOrBytes>, lenInBytes: number, k: number, H: TArg<CHash>): TRet<Uint8Array>;
|
||||
/**
|
||||
* Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.
|
||||
* See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.2 | RFC 9380 section 5.2}.
|
||||
* @param msg - Input message bytes.
|
||||
* @param count - Number of field elements to derive. Must be `>= 1`.
|
||||
* @param options - RFC 9380 options. See {@link H2COpts}. `m` must be `>= 1`.
|
||||
* @returns `[u_0, ..., u_(count - 1)]`, a list of field elements.
|
||||
* @throws If the expander choice or RFC 9380 options are invalid. {@link Error}
|
||||
* @example
|
||||
* Hash one message into field elements before mapping it onto a curve.
|
||||
*
|
||||
* ```ts
|
||||
* import { hash_to_field } from '@noble/curves/abstract/hash-to-curve.js';
|
||||
* import { sha256 } from '@noble/hashes/sha2.js';
|
||||
* const scalars = hash_to_field(new TextEncoder().encode('hello noble'), 2, {
|
||||
* DST: 'DST',
|
||||
* p: 17n,
|
||||
* m: 1,
|
||||
* k: 128,
|
||||
* expand: 'xmd',
|
||||
* hash: sha256,
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export declare function hash_to_field(msg: TArg<Uint8Array>, count: number, options: TArg<H2COpts>): bigint[][];
|
||||
type XY<T> = (x: T, y: T) => {
|
||||
x: T;
|
||||
y: T;
|
||||
};
|
||||
type XYRatio<T> = [T[], T[], T[], T[]];
|
||||
/**
|
||||
* @param field - Field implementation.
|
||||
* @param map - Isogeny coefficients.
|
||||
* @returns Isogeny mapping helper.
|
||||
* @example
|
||||
* Build one rational isogeny map, then apply it to affine x/y coordinates.
|
||||
*
|
||||
* ```ts
|
||||
* import { isogenyMap } from '@noble/curves/abstract/hash-to-curve.js';
|
||||
* import { Field } from '@noble/curves/abstract/modular.js';
|
||||
* const Fp = Field(17n);
|
||||
* const iso = isogenyMap(Fp, [[0n, 1n], [1n], [1n], [1n]]);
|
||||
* const point = iso(3n, 5n);
|
||||
* ```
|
||||
*/
|
||||
export declare function isogenyMap<T, F extends IField<T>>(field: F, map: XYRatio<T>): XY<T>;
|
||||
export declare const _DST_scalar: "HashToScalar-";
|
||||
/**
|
||||
* Creates hash-to-curve methods from EC Point and mapToCurve function. See {@link H2CHasher}.
|
||||
* @param Point - Point constructor.
|
||||
* @param mapToCurve - Map-to-curve function.
|
||||
* @param defaults - Default hash-to-curve options. This object is frozen in place and reused as
|
||||
* the shared defaults bundle for the returned helpers.
|
||||
* @returns Hash-to-curve helper namespace.
|
||||
* @throws If the map-to-curve callback or default hash-to-curve options are invalid. {@link Error}
|
||||
* @example
|
||||
* Bundle hash-to-curve, hash-to-scalar, and encode-to-curve helpers for one curve.
|
||||
*
|
||||
* ```ts
|
||||
* import { createHasher } from '@noble/curves/abstract/hash-to-curve.js';
|
||||
* import { p256 } from '@noble/curves/nist.js';
|
||||
* import { sha256 } from '@noble/hashes/sha2.js';
|
||||
* const hasher = createHasher(p256.Point, () => p256.Point.BASE.toAffine(), {
|
||||
* DST: 'P256_XMD:SHA-256_SSWU_RO_',
|
||||
* encodeDST: 'P256_XMD:SHA-256_SSWU_NU_',
|
||||
* p: p256.Point.Fp.ORDER,
|
||||
* m: 1,
|
||||
* k: 128,
|
||||
* expand: 'xmd',
|
||||
* hash: sha256,
|
||||
* });
|
||||
* const point = hasher.encodeToCurve(new TextEncoder().encode('hello noble'));
|
||||
* ```
|
||||
*/
|
||||
export declare function createHasher<PC extends PC_ANY>(Point: PC, mapToCurve: MapToCurve<PC_F<PC>>, defaults: TArg<H2COpts & {
|
||||
encodeDST?: AsciiOrBytes;
|
||||
}>): H2CHasher<PC>;
|
||||
export {};
|
||||
//# sourceMappingURL=hash-to-curve.d.ts.map
|
||||
1
node_modules/@noble/curves/abstract/hash-to-curve.d.ts.map
generated
vendored
Normal file
1
node_modules/@noble/curves/abstract/hash-to-curve.d.ts.map
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"hash-to-curve.d.ts","sourceRoot":"","sources":["../src/abstract/hash-to-curve.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,sEAAsE;AACtE,OAAO,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,aAAa,CAAC;AAWrD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAClE,OAAO,EAAsB,KAAK,MAAM,EAAE,MAAM,cAAc,CAAC;AAE/D,gDAAgD;AAChD,MAAM,MAAM,YAAY,GAAG,MAAM,GAAG,UAAU,CAAC;AAC/C,KAAK,WAAW,GAAG;IACjB,GAAG,EAAE,YAAY,CAAC;IAClB,MAAM,EAAE,KAAK,GAAG,KAAK,CAAC;IACtB,IAAI,EAAE,KAAK,CAAC;IACZ,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;IACV,SAAS,CAAC,EAAE,YAAY,CAAC;CAC1B,CAAC;AAEF;;;;;;;GAOG;AACH,MAAM,MAAM,OAAO,GAAG;IACpB,6BAA6B;IAC7B,GAAG,EAAE,YAAY,CAAC;IAClB,wCAAwC;IACxC,MAAM,EAAE,KAAK,GAAG,KAAK,CAAC;IACtB,uDAAuD;IACvD,IAAI,EAAE,KAAK,CAAC;IACZ,iCAAiC;IACjC,CAAC,EAAE,MAAM,CAAC;IACV,+CAA+C;IAC/C,CAAC,EAAE,MAAM,CAAC;IACV,qCAAqC;IACrC,CAAC,EAAE,MAAM,CAAC;CACX,CAAC;AACF,uEAAuE;AACvE,MAAM,MAAM,WAAW,GAAG;IACxB,wCAAwC;IACxC,MAAM,EAAE,KAAK,GAAG,KAAK,CAAC;IACtB,uDAAuD;IACvD,IAAI,EAAE,KAAK,CAAC;CACb,CAAC;AACF;;;;;;GAMG;AACH,MAAM,MAAM,UAAU,CAAC,CAAC,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,WAAW,CAAC,CAAC,CAAC,CAAC;AAIjE,uDAAuD;AACvD,MAAM,MAAM,UAAU,GAAG;IACvB,sCAAsC;IACtC,GAAG,EAAE,YAAY,CAAC;CACnB,CAAC;AACF,8EAA8E;AAC9E,MAAM,MAAM,aAAa,CAAC,EAAE,SAAS,MAAM,IAAI;IAC7C;;;;;OAKG;IACH,WAAW,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,OAAO,CAAC,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI,CAAC,EAAE,CAAC,CAAC;IACzE;;;;;OAKG;IACH,YAAY,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,OAAO,CAAC,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,MAAM,CAAC;IACxE;;;;;OAKG;IACH,aAAa,CAAC,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,OAAO,CAAC,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI,CAAC,EAAE,CAAC,CAAC;IAC5E,8CAA8C;IAC9C,KAAK,EAAE,EAAE,CAAC;CACX,CAAC;AACF;;;;;;GAMG;AACH,MAAM,MAAM,SAAS,CAAC,EAAE,SAAS,MAAM,IAAI,aAAa,CAAC,EAAE,CAAC,GAAG;IAC7D;;;;;OAKG;IACH,aAAa,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,OAAO,CAAC,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI,CAAC,EAAE,CAAC,CAAC;IAC3E,6EAA6E;IAC7E,UAAU,EAAE,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC;IACjC,+DAA+D;IAC/D,QAAQ,EAAE,WAAW,CAAC;CACvB,CAAC;AAyCF;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,kBAAkB,CAChC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EACrB,GAAG,EAAE,IAAI,CAAC,YAAY,CAAC,EACvB,UAAU,EAAE,MAAM,EAClB,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,GACb,IAAI,CAAC,UAAU,CAAC,CAwBlB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAgB,kBAAkB,CAChC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EACrB,GAAG,EAAE,IAAI,CAAC,YAAY,CAAC,EACvB,UAAU,EAAE,MAAM,EAClB,CAAC,EAAE,MAAM,EACT,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,GACb,IAAI,CAAC,UAAU,CAAC,CAqBlB;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,aAAa,CAC3B,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EACrB,KAAK,EAAE,MAAM,EACb,OAAO,EAAE,IAAI,CAAC,OAAO,CAAC,GACrB,MAAM,EAAE,EAAE,CAwCZ;AAED,KAAK,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,KAAK;IAAE,CAAC,EAAE,CAAC,CAAC;IAAC,CAAC,EAAE,CAAC,CAAA;CAAE,CAAC;AAC5C,KAAK,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC;AACvC;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,UAAU,CAAC,CAAC,EAAE,CAAC,SAAS,MAAM,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAiBnF;AAOD,eAAO,MAAM,WAAW,EAAG,eAAwB,CAAC;AAEpD;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAgB,YAAY,CAAC,EAAE,SAAS,MAAM,EAC5C,KAAK,EAAE,EAAE,EACT,UAAU,EAAE,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,EAChC,QAAQ,EAAE,IAAI,CAAC,OAAO,GAAG;IAAE,SAAS,CAAC,EAAE,YAAY,CAAA;CAAE,CAAC,GACrD,SAAS,CAAC,EAAE,CAAC,CAyEf"}
|
||||
346
node_modules/@noble/curves/abstract/hash-to-curve.js
generated
vendored
Normal file
346
node_modules/@noble/curves/abstract/hash-to-curve.js
generated
vendored
Normal file
@@ -0,0 +1,346 @@
|
||||
import { abytes, asafenumber, asciiToBytes, bytesToNumberBE, copyBytes, concatBytes, isBytes, validateObject, } from "../utils.js";
|
||||
import { FpInvertBatch, mod } from "./modular.js";
|
||||
// Octet Stream to Integer. "spec" implementation of os2ip is 2.5x slower vs bytesToNumberBE.
|
||||
const os2ip = bytesToNumberBE;
|
||||
// Integer to Octet Stream (numberToBytesBE).
|
||||
function i2osp(value, length) {
|
||||
asafenumber(value);
|
||||
asafenumber(length);
|
||||
// This helper stays on the JS bitwise/u32 fast-path. Callers that need wider encodings should
|
||||
// use bigint + numberToBytesBE instead of routing large widths through this small helper.
|
||||
if (length < 0 || length > 4)
|
||||
throw new Error('invalid I2OSP length: ' + length);
|
||||
if (value < 0 || value > 2 ** (8 * length) - 1)
|
||||
throw new Error('invalid I2OSP input: ' + value);
|
||||
const res = Array.from({ length }).fill(0);
|
||||
for (let i = length - 1; i >= 0; i--) {
|
||||
res[i] = value & 0xff;
|
||||
value >>>= 8;
|
||||
}
|
||||
return new Uint8Array(res);
|
||||
}
|
||||
// RFC 9380 only applies strxor() to equal-length strings; callers must preserve that invariant.
|
||||
function strxor(a, b) {
|
||||
const arr = new Uint8Array(a.length);
|
||||
for (let i = 0; i < a.length; i++) {
|
||||
arr[i] = a[i] ^ b[i];
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
// User can always use utf8 if they want, by passing Uint8Array.
|
||||
// If string is passed, we treat it as ASCII: other formats are likely a mistake.
|
||||
function normDST(DST) {
|
||||
if (!isBytes(DST) && typeof DST !== 'string')
|
||||
throw new Error('DST must be Uint8Array or ascii string');
|
||||
const dst = typeof DST === 'string' ? asciiToBytes(DST) : DST;
|
||||
// RFC 9380 §3.1 requirement 2: tags "MUST have nonzero length".
|
||||
if (dst.length === 0)
|
||||
throw new Error('DST must be non-empty');
|
||||
return dst;
|
||||
}
|
||||
/**
|
||||
* Produces a uniformly random byte string using a cryptographic hash
|
||||
* function H that outputs b bits.
|
||||
* See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1 | RFC 9380 section 5.3.1}.
|
||||
* @param msg - Input message.
|
||||
* @param DST - Domain separation tag. This helper normalizes DST, rejects empty DSTs, and
|
||||
* oversize-hashes DST when needed.
|
||||
* @param lenInBytes - Output length.
|
||||
* @param H - Hash function.
|
||||
* @returns Uniform byte string.
|
||||
* @throws If the message, DST, hash, or output length is invalid. {@link Error}
|
||||
* @example
|
||||
* Expand one message into uniform bytes with the XMD construction.
|
||||
*
|
||||
* ```ts
|
||||
* import { expand_message_xmd } from '@noble/curves/abstract/hash-to-curve.js';
|
||||
* import { sha256 } from '@noble/hashes/sha2.js';
|
||||
* const uniform = expand_message_xmd(new TextEncoder().encode('hello noble'), 'DST', 32, sha256);
|
||||
* ```
|
||||
*/
|
||||
export function expand_message_xmd(msg, DST, lenInBytes, H) {
|
||||
abytes(msg);
|
||||
asafenumber(lenInBytes);
|
||||
DST = normDST(DST);
|
||||
// https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3
|
||||
if (DST.length > 255)
|
||||
DST = H(concatBytes(asciiToBytes('H2C-OVERSIZE-DST-'), DST));
|
||||
const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;
|
||||
const ell = Math.ceil(lenInBytes / b_in_bytes);
|
||||
if (lenInBytes > 65535 || ell > 255)
|
||||
throw new Error('expand_message_xmd: invalid lenInBytes');
|
||||
const DST_prime = concatBytes(DST, i2osp(DST.length, 1));
|
||||
const Z_pad = new Uint8Array(r_in_bytes); // RFC 9380: Z_pad = I2OSP(0, s_in_bytes)
|
||||
const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str
|
||||
const b = new Array(ell);
|
||||
const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
|
||||
b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime));
|
||||
// `b[0]` already stores RFC `b_1`, so only derive `b_2..b_ell` here. The old `<= ell`
|
||||
// loop computed one extra tail block, which was usually sliced away but broke at max `ell=255`
|
||||
// by reaching `I2OSP(256, 1)`.
|
||||
for (let i = 1; i < ell; i++) {
|
||||
const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];
|
||||
b[i] = H(concatBytes(...args));
|
||||
}
|
||||
const pseudo_random_bytes = concatBytes(...b);
|
||||
return pseudo_random_bytes.slice(0, lenInBytes);
|
||||
}
|
||||
/**
|
||||
* Produces a uniformly random byte string using an extendable-output function (XOF) H.
|
||||
* 1. The collision resistance of H MUST be at least k bits.
|
||||
* 2. H MUST be an XOF that has been proved indifferentiable from
|
||||
* a random oracle under a reasonable cryptographic assumption.
|
||||
* See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2 | RFC 9380 section 5.3.2}.
|
||||
* @param msg - Input message.
|
||||
* @param DST - Domain separation tag. This helper normalizes DST, rejects empty DSTs, and
|
||||
* oversize-hashes DST when needed.
|
||||
* @param lenInBytes - Output length.
|
||||
* @param k - Target security level.
|
||||
* @param H - XOF hash function.
|
||||
* @returns Uniform byte string.
|
||||
* @throws If the message, DST, XOF, or output length is invalid. {@link Error}
|
||||
* @example
|
||||
* Expand one message into uniform bytes with the XOF construction.
|
||||
*
|
||||
* ```ts
|
||||
* import { expand_message_xof } from '@noble/curves/abstract/hash-to-curve.js';
|
||||
* import { shake256 } from '@noble/hashes/sha3.js';
|
||||
* const uniform = expand_message_xof(
|
||||
* new TextEncoder().encode('hello noble'),
|
||||
* 'DST',
|
||||
* 32,
|
||||
* 128,
|
||||
* shake256
|
||||
* );
|
||||
* ```
|
||||
*/
|
||||
export function expand_message_xof(msg, DST, lenInBytes, k, H) {
|
||||
abytes(msg);
|
||||
asafenumber(lenInBytes);
|
||||
DST = normDST(DST);
|
||||
// https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3
|
||||
// RFC 9380 §5.3.3: DST = H("H2C-OVERSIZE-DST-" || a_very_long_DST, ceil(2 * k / 8)).
|
||||
if (DST.length > 255) {
|
||||
const dkLen = Math.ceil((2 * k) / 8);
|
||||
DST = H.create({ dkLen }).update(asciiToBytes('H2C-OVERSIZE-DST-')).update(DST).digest();
|
||||
}
|
||||
if (lenInBytes > 65535 || DST.length > 255)
|
||||
throw new Error('expand_message_xof: invalid lenInBytes');
|
||||
return (H.create({ dkLen: lenInBytes })
|
||||
.update(msg)
|
||||
.update(i2osp(lenInBytes, 2))
|
||||
// 2. DST_prime = DST || I2OSP(len(DST), 1)
|
||||
.update(DST)
|
||||
.update(i2osp(DST.length, 1))
|
||||
.digest());
|
||||
}
|
||||
/**
|
||||
* Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.
|
||||
* See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.2 | RFC 9380 section 5.2}.
|
||||
* @param msg - Input message bytes.
|
||||
* @param count - Number of field elements to derive. Must be `>= 1`.
|
||||
* @param options - RFC 9380 options. See {@link H2COpts}. `m` must be `>= 1`.
|
||||
* @returns `[u_0, ..., u_(count - 1)]`, a list of field elements.
|
||||
* @throws If the expander choice or RFC 9380 options are invalid. {@link Error}
|
||||
* @example
|
||||
* Hash one message into field elements before mapping it onto a curve.
|
||||
*
|
||||
* ```ts
|
||||
* import { hash_to_field } from '@noble/curves/abstract/hash-to-curve.js';
|
||||
* import { sha256 } from '@noble/hashes/sha2.js';
|
||||
* const scalars = hash_to_field(new TextEncoder().encode('hello noble'), 2, {
|
||||
* DST: 'DST',
|
||||
* p: 17n,
|
||||
* m: 1,
|
||||
* k: 128,
|
||||
* expand: 'xmd',
|
||||
* hash: sha256,
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function hash_to_field(msg, count, options) {
|
||||
validateObject(options, {
|
||||
p: 'bigint',
|
||||
m: 'number',
|
||||
k: 'number',
|
||||
hash: 'function',
|
||||
});
|
||||
const { p, k, m, hash, expand, DST } = options;
|
||||
asafenumber(hash.outputLen, 'valid hash');
|
||||
abytes(msg);
|
||||
asafenumber(count);
|
||||
// RFC 9380 §5.2 defines hash_to_field over a list of one or more field elements and requires
|
||||
// extension degree `m >= 1`; rejecting here avoids degenerate `[]` / `[[]]` helper outputs.
|
||||
if (count < 1)
|
||||
throw new Error('hash_to_field: expected count >= 1');
|
||||
if (m < 1)
|
||||
throw new Error('hash_to_field: expected m >= 1');
|
||||
const log2p = p.toString(2).length;
|
||||
const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above
|
||||
const len_in_bytes = count * m * L;
|
||||
let prb; // pseudo_random_bytes
|
||||
if (expand === 'xmd') {
|
||||
prb = expand_message_xmd(msg, DST, len_in_bytes, hash);
|
||||
}
|
||||
else if (expand === 'xof') {
|
||||
prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);
|
||||
}
|
||||
else if (expand === '_internal_pass') {
|
||||
// for internal tests only
|
||||
prb = msg;
|
||||
}
|
||||
else {
|
||||
throw new Error('expand must be "xmd" or "xof"');
|
||||
}
|
||||
const u = new Array(count);
|
||||
for (let i = 0; i < count; i++) {
|
||||
const e = new Array(m);
|
||||
for (let j = 0; j < m; j++) {
|
||||
const elm_offset = L * (j + i * m);
|
||||
const tv = prb.subarray(elm_offset, elm_offset + L);
|
||||
e[j] = mod(os2ip(tv), p);
|
||||
}
|
||||
u[i] = e;
|
||||
}
|
||||
return u;
|
||||
}
|
||||
/**
|
||||
* @param field - Field implementation.
|
||||
* @param map - Isogeny coefficients.
|
||||
* @returns Isogeny mapping helper.
|
||||
* @example
|
||||
* Build one rational isogeny map, then apply it to affine x/y coordinates.
|
||||
*
|
||||
* ```ts
|
||||
* import { isogenyMap } from '@noble/curves/abstract/hash-to-curve.js';
|
||||
* import { Field } from '@noble/curves/abstract/modular.js';
|
||||
* const Fp = Field(17n);
|
||||
* const iso = isogenyMap(Fp, [[0n, 1n], [1n], [1n], [1n]]);
|
||||
* const point = iso(3n, 5n);
|
||||
* ```
|
||||
*/
|
||||
export function isogenyMap(field, map) {
|
||||
// Make same order as in spec
|
||||
const coeff = map.map((i) => Array.from(i).reverse());
|
||||
return (x, y) => {
|
||||
const [xn, xd, yn, yd] = coeff.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i)));
|
||||
// RFC 9380 §6.6.3 / Appendix E: denominator-zero exceptional cases must
|
||||
// return the identity on E.
|
||||
// Shipped Weierstrass consumers encode that affine identity as all-zero
|
||||
// coordinates, so `passZero=true` intentionally collapses zero
|
||||
// denominators to `{ x: 0, y: 0 }`.
|
||||
const [xd_inv, yd_inv] = FpInvertBatch(field, [xd, yd], true);
|
||||
x = field.mul(xn, xd_inv); // xNum / xDen
|
||||
y = field.mul(y, field.mul(yn, yd_inv)); // y * (yNum / yDev)
|
||||
return { x, y };
|
||||
};
|
||||
}
|
||||
// Keep the shared DST removable when the selected bundle never hashes to scalar.
|
||||
// Callers that need protocol-specific scalar domain separation must override this generic default.
|
||||
// RFC 9497 §§4.1-4.5 use this ASCII prefix before appending the ciphersuite context string.
|
||||
// Export a string instead of mutable bytes so callers cannot poison default hash-to-scalar behavior
|
||||
// by mutating a shared Uint8Array in place.
|
||||
export const _DST_scalar = 'HashToScalar-';
|
||||
/**
|
||||
* Creates hash-to-curve methods from EC Point and mapToCurve function. See {@link H2CHasher}.
|
||||
* @param Point - Point constructor.
|
||||
* @param mapToCurve - Map-to-curve function.
|
||||
* @param defaults - Default hash-to-curve options. This object is frozen in place and reused as
|
||||
* the shared defaults bundle for the returned helpers.
|
||||
* @returns Hash-to-curve helper namespace.
|
||||
* @throws If the map-to-curve callback or default hash-to-curve options are invalid. {@link Error}
|
||||
* @example
|
||||
* Bundle hash-to-curve, hash-to-scalar, and encode-to-curve helpers for one curve.
|
||||
*
|
||||
* ```ts
|
||||
* import { createHasher } from '@noble/curves/abstract/hash-to-curve.js';
|
||||
* import { p256 } from '@noble/curves/nist.js';
|
||||
* import { sha256 } from '@noble/hashes/sha2.js';
|
||||
* const hasher = createHasher(p256.Point, () => p256.Point.BASE.toAffine(), {
|
||||
* DST: 'P256_XMD:SHA-256_SSWU_RO_',
|
||||
* encodeDST: 'P256_XMD:SHA-256_SSWU_NU_',
|
||||
* p: p256.Point.Fp.ORDER,
|
||||
* m: 1,
|
||||
* k: 128,
|
||||
* expand: 'xmd',
|
||||
* hash: sha256,
|
||||
* });
|
||||
* const point = hasher.encodeToCurve(new TextEncoder().encode('hello noble'));
|
||||
* ```
|
||||
*/
|
||||
export function createHasher(Point, mapToCurve, defaults) {
|
||||
if (typeof mapToCurve !== 'function')
|
||||
throw new Error('mapToCurve() must be defined');
|
||||
// `Point` is intentionally not shape-validated eagerly here: point constructors vary across
|
||||
// curve families, so this helper only checks the hooks it can validate cheaply. Misconfigured
|
||||
// suites fail later when hashing first touches Point.fromAffine / Point.ZERO / clearCofactor().
|
||||
const snapshot = (src) => Object.freeze({
|
||||
...src,
|
||||
DST: isBytes(src.DST) ? copyBytes(src.DST) : src.DST,
|
||||
...(src.encodeDST === undefined
|
||||
? {}
|
||||
: { encodeDST: isBytes(src.encodeDST) ? copyBytes(src.encodeDST) : src.encodeDST }),
|
||||
});
|
||||
// Keep one private defaults snapshot for actual hashing and expose fresh
|
||||
// detached snapshots via the public getter.
|
||||
// Otherwise a caller could mutate `hasher.defaults.DST` in place and poison
|
||||
// the singleton hasher for every other consumer in the same process.
|
||||
const safeDefaults = snapshot(defaults);
|
||||
function map(num) {
|
||||
return Point.fromAffine(mapToCurve(num));
|
||||
}
|
||||
function clear(initial) {
|
||||
const P = initial.clearCofactor();
|
||||
// Keep ZERO as the algebraic cofactor-clearing result here; strict public point-validity
|
||||
// surfaces may still reject it later, but createHasher.clear() itself is not that boundary.
|
||||
if (P.equals(Point.ZERO))
|
||||
return Point.ZERO;
|
||||
P.assertValidity();
|
||||
return P;
|
||||
}
|
||||
return Object.freeze({
|
||||
get defaults() {
|
||||
return snapshot(safeDefaults);
|
||||
},
|
||||
Point,
|
||||
hashToCurve(msg, options) {
|
||||
const opts = Object.assign({}, safeDefaults, options);
|
||||
const u = hash_to_field(msg, 2, opts);
|
||||
const u0 = map(u[0]);
|
||||
const u1 = map(u[1]);
|
||||
return clear(u0.add(u1));
|
||||
},
|
||||
encodeToCurve(msg, options) {
|
||||
const optsDst = safeDefaults.encodeDST ? { DST: safeDefaults.encodeDST } : {};
|
||||
const opts = Object.assign({}, safeDefaults, optsDst, options);
|
||||
const u = hash_to_field(msg, 1, opts);
|
||||
const u0 = map(u[0]);
|
||||
return clear(u0);
|
||||
},
|
||||
/** See {@link H2CHasher} */
|
||||
mapToCurve(scalars) {
|
||||
// Curves with m=1 accept only single scalar
|
||||
if (safeDefaults.m === 1) {
|
||||
if (typeof scalars !== 'bigint')
|
||||
throw new Error('expected bigint (m=1)');
|
||||
return clear(map([scalars]));
|
||||
}
|
||||
if (!Array.isArray(scalars))
|
||||
throw new Error('expected array of bigints');
|
||||
for (const i of scalars)
|
||||
if (typeof i !== 'bigint')
|
||||
throw new Error('expected array of bigints');
|
||||
return clear(map(scalars));
|
||||
},
|
||||
// hash_to_scalar can produce 0: https://www.rfc-editor.org/errata/eid8393
|
||||
// RFC 9380, draft-irtf-cfrg-bbs-signatures-08. Default scalar DST is the shared generic
|
||||
// `HashToScalar-` prefix above unless the caller overrides it per invocation.
|
||||
hashToScalar(msg, options) {
|
||||
// @ts-ignore
|
||||
const N = Point.Fn.ORDER;
|
||||
const opts = Object.assign({}, safeDefaults, { p: N, m: 1, DST: _DST_scalar }, options);
|
||||
return hash_to_field(msg, 1, opts)[0][0];
|
||||
},
|
||||
});
|
||||
}
|
||||
//# sourceMappingURL=hash-to-curve.js.map
|
||||
1
node_modules/@noble/curves/abstract/hash-to-curve.js.map
generated
vendored
Normal file
1
node_modules/@noble/curves/abstract/hash-to-curve.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
551
node_modules/@noble/curves/abstract/modular.d.ts
generated
vendored
Normal file
551
node_modules/@noble/curves/abstract/modular.d.ts
generated
vendored
Normal file
@@ -0,0 +1,551 @@
|
||||
/**
|
||||
* Utils for modular division and fields.
|
||||
* Field over 11 is a finite (Galois) field is integer number operations `mod 11`.
|
||||
* There is no division: it is replaced by modular multiplicative inverse.
|
||||
* @module
|
||||
*/
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
import { type TArg, type TRet } from '../utils.ts';
|
||||
/**
|
||||
* @param a - Dividend value.
|
||||
* @param b - Positive modulus.
|
||||
* @returns Reduced value in `[0, b)` only when `b` is positive.
|
||||
* @throws If the modulus is not positive. {@link Error}
|
||||
* @example
|
||||
* Normalize a bigint into one field residue.
|
||||
*
|
||||
* ```ts
|
||||
* mod(-1n, 5n);
|
||||
* ```
|
||||
*/
|
||||
export declare function mod(a: bigint, b: bigint): bigint;
|
||||
/**
|
||||
* Efficiently raise num to a power with modular reduction.
|
||||
* Unsafe in some contexts: uses ladder, so can expose bigint bits.
|
||||
* Low-level helper: callers that need canonical residues must pass a valid `num` for the chosen
|
||||
* modulus instead of relying on the `power===0/1` fast paths to normalize it.
|
||||
* @param num - Base value.
|
||||
* @param power - Exponent value.
|
||||
* @param modulo - Reduction modulus.
|
||||
* @returns Modular exponentiation result.
|
||||
* @throws If the modulus or exponent is invalid. {@link Error}
|
||||
* @example
|
||||
* Raise one bigint to a modular power.
|
||||
*
|
||||
* ```ts
|
||||
* pow(2n, 6n, 11n) // 64n % 11n == 9n
|
||||
* ```
|
||||
*/
|
||||
export declare function pow(num: bigint, power: bigint, modulo: bigint): bigint;
|
||||
/**
|
||||
* Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)`.
|
||||
* Low-level helper: callers that need canonical residues must pass a valid `x` for the chosen
|
||||
* modulus; the `power===0` fast path intentionally returns the input unchanged.
|
||||
* @param x - Base value.
|
||||
* @param power - Number of squarings.
|
||||
* @param modulo - Reduction modulus.
|
||||
* @returns Repeated-squaring result.
|
||||
* @throws If the exponent is negative. {@link Error}
|
||||
* @example
|
||||
* Apply repeated squaring inside one field.
|
||||
*
|
||||
* ```ts
|
||||
* pow2(3n, 2n, 11n);
|
||||
* ```
|
||||
*/
|
||||
export declare function pow2(x: bigint, power: bigint, modulo: bigint): bigint;
|
||||
/**
|
||||
* Inverses number over modulo.
|
||||
* Implemented using the {@link https://brilliant.org/wiki/extended-euclidean-algorithm/ | extended Euclidean algorithm}.
|
||||
* @param number - Value to invert.
|
||||
* @param modulo - Positive modulus.
|
||||
* @returns Multiplicative inverse.
|
||||
* @throws If the modulus is invalid or the inverse does not exist. {@link Error}
|
||||
* @example
|
||||
* Compute one modular inverse with the extended Euclidean algorithm.
|
||||
*
|
||||
* ```ts
|
||||
* invert(3n, 11n);
|
||||
* ```
|
||||
*/
|
||||
export declare function invert(number: bigint, modulo: bigint): bigint;
|
||||
/**
|
||||
* Tonelli-Shanks square root search algorithm.
|
||||
* This implementation is variable-time: it searches data-dependently for the first non-residue `Z`
|
||||
* and for the smallest `i` in the main loop, unlike RFC 9380 Appendix I.4's constant-time shape.
|
||||
* 1. {@link https://eprint.iacr.org/2012/685.pdf | eprint 2012/685}, page 12
|
||||
* 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
|
||||
* @param P - field order
|
||||
* @returns function that takes field Fp (created from P) and number n
|
||||
* @throws If the field is too small, non-prime, or the square root does not exist. {@link Error}
|
||||
* @example
|
||||
* Construct a square-root helper for primes that need Tonelli-Shanks.
|
||||
*
|
||||
* ```ts
|
||||
* import { Field, tonelliShanks } from '@noble/curves/abstract/modular.js';
|
||||
* const Fp = Field(17n);
|
||||
* const sqrt = tonelliShanks(17n)(Fp, 4n);
|
||||
* ```
|
||||
*/
|
||||
export declare function tonelliShanks(P: bigint): TRet<(<T>(Fp: IField<T>, n: T) => T)>;
|
||||
/**
|
||||
* Square root for a finite field. Will try optimized versions first:
|
||||
*
|
||||
* 1. P ≡ 3 (mod 4)
|
||||
* 2. P ≡ 5 (mod 8)
|
||||
* 3. P ≡ 9 (mod 16)
|
||||
* 4. Tonelli-Shanks algorithm
|
||||
*
|
||||
* Different algorithms can give different roots, it is up to user to decide which one they want.
|
||||
* For example there is FpSqrtOdd/FpSqrtEven to choose a root by oddness
|
||||
* (used for hash-to-curve).
|
||||
* @param P - Field order.
|
||||
* @returns Square-root helper. The generic fallback inherits Tonelli-Shanks' variable-time
|
||||
* behavior and this selector assumes prime-field-style integer moduli.
|
||||
* @throws If the field is unsupported or the square root does not exist. {@link Error}
|
||||
* @example
|
||||
* Choose the square-root helper appropriate for one field modulus.
|
||||
*
|
||||
* ```ts
|
||||
* import { Field, FpSqrt } from '@noble/curves/abstract/modular.js';
|
||||
* const Fp = Field(17n);
|
||||
* const sqrt = FpSqrt(17n)(Fp, 4n);
|
||||
* ```
|
||||
*/
|
||||
export declare function FpSqrt(P: bigint): TRet<(<T>(Fp: IField<T>, n: T) => T)>;
|
||||
/**
|
||||
* @param num - Value to inspect.
|
||||
* @param modulo - Field modulus.
|
||||
* @returns `true` when the least-significant little-endian bit is set.
|
||||
* @throws If the modulus is invalid for `mod(...)`. {@link Error}
|
||||
* @example
|
||||
* Inspect the low bit used by little-endian sign conventions.
|
||||
*
|
||||
* ```ts
|
||||
* isNegativeLE(3n, 11n);
|
||||
* ```
|
||||
*/
|
||||
export declare const isNegativeLE: (num: bigint, modulo: bigint) => boolean;
|
||||
/** Generic field interface used by prime and extension fields alike.
|
||||
* Generic helpers treat field operations as pure functions: implementations MUST treat provided
|
||||
* values/byte buffers as read-only and return detached results instead of mutating arguments.
|
||||
*/
|
||||
export interface IField<T> {
|
||||
/** Field order `q`, which may be prime or a prime power. */
|
||||
ORDER: bigint;
|
||||
/** Canonical encoded byte length. */
|
||||
BYTES: number;
|
||||
/** Canonical encoded bit length. */
|
||||
BITS: number;
|
||||
/** Whether encoded field elements use little-endian bytes. */
|
||||
isLE: boolean;
|
||||
/** Additive identity. */
|
||||
ZERO: T;
|
||||
/** Multiplicative identity. */
|
||||
ONE: T;
|
||||
/**
|
||||
* Normalize one value into the field.
|
||||
* @param num - Input value.
|
||||
* @returns Normalized field value.
|
||||
*/
|
||||
create: (num: T) => T;
|
||||
/**
|
||||
* Check whether one value already belongs to the field.
|
||||
* @param num - Input value.
|
||||
* Implementations may throw `TypeError` on malformed input types instead of returning `false`.
|
||||
* @returns Whether the value already belongs to the field.
|
||||
*/
|
||||
isValid: (num: T) => boolean;
|
||||
/**
|
||||
* Check whether one value is zero.
|
||||
* @param num - Input value.
|
||||
* @returns Whether the value is zero.
|
||||
*/
|
||||
is0: (num: T) => boolean;
|
||||
/**
|
||||
* Check whether one value is non-zero and belongs to the field.
|
||||
* @param num - Input value.
|
||||
* Implementations may throw `TypeError` on malformed input types instead of returning `false`.
|
||||
* @returns Whether the value is non-zero and valid.
|
||||
*/
|
||||
isValidNot0: (num: T) => boolean;
|
||||
/**
|
||||
* Negate one value.
|
||||
* @param num - Input value.
|
||||
* @returns Negated value.
|
||||
*/
|
||||
neg(num: T): T;
|
||||
/**
|
||||
* Invert one value multiplicatively.
|
||||
* @param num - Input value.
|
||||
* @returns Multiplicative inverse.
|
||||
*/
|
||||
inv(num: T): T;
|
||||
/**
|
||||
* Compute one square root when it exists.
|
||||
* @param num - Input value.
|
||||
* @returns Square root.
|
||||
*/
|
||||
sqrt(num: T): T;
|
||||
/**
|
||||
* Square one value.
|
||||
* @param num - Input value.
|
||||
* @returns Squared value.
|
||||
*/
|
||||
sqr(num: T): T;
|
||||
/**
|
||||
* Compare two field values.
|
||||
* @param lhs - Left value.
|
||||
* @param rhs - Right value.
|
||||
* @returns Whether both values are equal.
|
||||
*/
|
||||
eql(lhs: T, rhs: T): boolean;
|
||||
/**
|
||||
* Add two normalized field values.
|
||||
* @param lhs - Left value.
|
||||
* @param rhs - Right value.
|
||||
* @returns Sum value.
|
||||
*/
|
||||
add(lhs: T, rhs: T): T;
|
||||
/**
|
||||
* Subtract two normalized field values.
|
||||
* @param lhs - Left value.
|
||||
* @param rhs - Right value.
|
||||
* @returns Difference value.
|
||||
*/
|
||||
sub(lhs: T, rhs: T): T;
|
||||
/**
|
||||
* Multiply two field values.
|
||||
* @param lhs - Left value.
|
||||
* @param rhs - Right value or scalar.
|
||||
* @returns Product value.
|
||||
*/
|
||||
mul(lhs: T, rhs: T | bigint): T;
|
||||
/**
|
||||
* Raise one field value to a power.
|
||||
* @param lhs - Base value.
|
||||
* @param power - Exponent.
|
||||
* @returns Power value.
|
||||
*/
|
||||
pow(lhs: T, power: bigint): T;
|
||||
/**
|
||||
* Divide one field value by another.
|
||||
* @param lhs - Dividend.
|
||||
* @param rhs - Divisor or scalar.
|
||||
* @returns Quotient value.
|
||||
*/
|
||||
div(lhs: T, rhs: T | bigint): T;
|
||||
/**
|
||||
* Add two values without re-normalizing the result.
|
||||
* @param lhs - Left value.
|
||||
* @param rhs - Right value.
|
||||
* @returns Non-normalized sum.
|
||||
*/
|
||||
addN(lhs: T, rhs: T): T;
|
||||
/**
|
||||
* Subtract two values without re-normalizing the result.
|
||||
* @param lhs - Left value.
|
||||
* @param rhs - Right value.
|
||||
* @returns Non-normalized difference.
|
||||
*/
|
||||
subN(lhs: T, rhs: T): T;
|
||||
/**
|
||||
* Multiply two values without re-normalizing the result.
|
||||
* @param lhs - Left value.
|
||||
* @param rhs - Right value or scalar.
|
||||
* @returns Non-normalized product.
|
||||
*/
|
||||
mulN(lhs: T, rhs: T | bigint): T;
|
||||
/**
|
||||
* Square one value without re-normalizing the result.
|
||||
* @param num - Input value.
|
||||
* @returns Non-normalized square.
|
||||
*/
|
||||
sqrN(num: T): T;
|
||||
/**
|
||||
* Return the RFC 9380 `sgn0`-style oddness bit when supported.
|
||||
* This uses oddness instead of evenness so extension fields like Fp2 can expose the same hook.
|
||||
* Returns whether the value is odd under the field encoding.
|
||||
*/
|
||||
isOdd?(num: T): boolean;
|
||||
/**
|
||||
* Invert many field elements in one batch.
|
||||
* @param lst - Values to invert.
|
||||
* @returns Batch of inverses.
|
||||
*/
|
||||
invertBatch: (lst: T[]) => T[];
|
||||
/**
|
||||
* Encode one field value into fixed-width bytes.
|
||||
* Callers that need canonical encodings MUST supply a valid field element.
|
||||
* Low-level protocols may also use this to serialize raw / non-canonical residues.
|
||||
* @param num - Input value.
|
||||
* @returns Fixed-width byte encoding.
|
||||
*/
|
||||
toBytes(num: T): Uint8Array;
|
||||
/**
|
||||
* Decode one field value from fixed-width bytes.
|
||||
* @param bytes - Fixed-width byte encoding.
|
||||
* @param skipValidation - Whether to skip range validation.
|
||||
* Implementations MUST treat `bytes` as read-only.
|
||||
* @returns Decoded field value.
|
||||
*/
|
||||
fromBytes(bytes: Uint8Array, skipValidation?: boolean): T;
|
||||
/**
|
||||
* Constant-time conditional move.
|
||||
* @param a - Value used when the condition is false.
|
||||
* @param b - Value used when the condition is true.
|
||||
* @param c - Selection bit.
|
||||
* @returns Selected value.
|
||||
*/
|
||||
cmov(a: T, b: T, c: boolean): T;
|
||||
}
|
||||
/**
|
||||
* @param field - Field implementation.
|
||||
* @returns Validated field. This only checks the arithmetic subset needed by generic helpers; it
|
||||
* does not guarantee full runtime-method coverage for serialization, batching, `cmov`, or
|
||||
* field-specific extras beyond positive `BYTES` / `BITS`.
|
||||
* @throws If the field shape or numeric metadata are invalid. {@link Error}
|
||||
* @example
|
||||
* Check that a field implementation exposes the operations curve code expects.
|
||||
*
|
||||
* ```ts
|
||||
* import { Field, validateField } from '@noble/curves/abstract/modular.js';
|
||||
* const Fp = validateField(Field(17n));
|
||||
* ```
|
||||
*/
|
||||
export declare function validateField<T>(field: TArg<IField<T>>): TRet<IField<T>>;
|
||||
/**
|
||||
* Same as `pow` but for Fp: non-constant-time.
|
||||
* Unsafe in some contexts: uses ladder, so can expose bigint bits.
|
||||
* @param Fp - Field implementation.
|
||||
* @param num - Base value.
|
||||
* @param power - Exponent value.
|
||||
* @returns Powered field element.
|
||||
* @throws If the exponent is negative. {@link Error}
|
||||
* @example
|
||||
* Raise one field element to a public exponent.
|
||||
*
|
||||
* ```ts
|
||||
* import { Field, FpPow } from '@noble/curves/abstract/modular.js';
|
||||
* const Fp = Field(17n);
|
||||
* const x = FpPow(Fp, 3n, 5n);
|
||||
* ```
|
||||
*/
|
||||
export declare function FpPow<T>(Fp: TArg<IField<T>>, num: T, power: bigint): T;
|
||||
/**
|
||||
* Efficiently invert an array of Field elements.
|
||||
* Exception-free. Zero-valued field elements stay `undefined` unless `passZero` is enabled.
|
||||
* @param Fp - Field implementation.
|
||||
* @param nums - Values to invert.
|
||||
* @param passZero - map 0 to 0 (instead of undefined)
|
||||
* @returns Inverted values.
|
||||
* @example
|
||||
* Invert several field elements with one shared inversion.
|
||||
*
|
||||
* ```ts
|
||||
* import { Field, FpInvertBatch } from '@noble/curves/abstract/modular.js';
|
||||
* const Fp = Field(17n);
|
||||
* const inv = FpInvertBatch(Fp, [1n, 2n, 4n]);
|
||||
* ```
|
||||
*/
|
||||
export declare function FpInvertBatch<T>(Fp: TArg<IField<T>>, nums: T[], passZero?: boolean): T[];
|
||||
/**
|
||||
* @param Fp - Field implementation.
|
||||
* @param lhs - Dividend value.
|
||||
* @param rhs - Divisor value.
|
||||
* @returns Division result.
|
||||
* @throws If the divisor is non-invertible. {@link Error}
|
||||
* @example
|
||||
* Divide one field element by another.
|
||||
*
|
||||
* ```ts
|
||||
* import { Field, FpDiv } from '@noble/curves/abstract/modular.js';
|
||||
* const Fp = Field(17n);
|
||||
* const x = FpDiv(Fp, 6n, 3n);
|
||||
* ```
|
||||
*/
|
||||
export declare function FpDiv<T>(Fp: TArg<IField<T>>, lhs: T, rhs: T | bigint): T;
|
||||
/**
|
||||
* Legendre symbol.
|
||||
* Legendre constant is used to calculate Legendre symbol (a | p)
|
||||
* which denotes the value of a^((p-1)/2) (mod p).
|
||||
*
|
||||
* * (a | p) ≡ 1 if a is a square (mod p), quadratic residue
|
||||
* * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue
|
||||
* * (a | p) ≡ 0 if a ≡ 0 (mod p)
|
||||
* @param Fp - Field implementation.
|
||||
* @param n - Value to inspect.
|
||||
* @returns Legendre symbol.
|
||||
* @throws If the field returns an invalid Legendre symbol value. {@link Error}
|
||||
* @example
|
||||
* Compute the Legendre symbol of one field element.
|
||||
*
|
||||
* ```ts
|
||||
* import { Field, FpLegendre } from '@noble/curves/abstract/modular.js';
|
||||
* const Fp = Field(17n);
|
||||
* const symbol = FpLegendre(Fp, 4n);
|
||||
* ```
|
||||
*/
|
||||
export declare function FpLegendre<T>(Fp: TArg<IField<T>>, n: T): -1 | 0 | 1;
|
||||
/**
|
||||
* @param Fp - Field implementation.
|
||||
* @param n - Value to inspect.
|
||||
* @returns `true` when `Fp.sqrt(n)` exists. This includes `0`, even though strict "quadratic
|
||||
* residue" terminology often reserves that name for the non-zero square class.
|
||||
* @throws If the field returns an invalid Legendre symbol value. {@link Error}
|
||||
* @example
|
||||
* Check whether one field element has a square root in the field.
|
||||
*
|
||||
* ```ts
|
||||
* import { Field, FpIsSquare } from '@noble/curves/abstract/modular.js';
|
||||
* const Fp = Field(17n);
|
||||
* const isSquare = FpIsSquare(Fp, 4n);
|
||||
* ```
|
||||
*/
|
||||
export declare function FpIsSquare<T>(Fp: TArg<IField<T>>, n: T): boolean;
|
||||
/** Byte and bit lengths derived from one scalar order. */
|
||||
export type NLength = {
|
||||
/** Canonical byte length. */
|
||||
nByteLength: number;
|
||||
/** Canonical bit length. */
|
||||
nBitLength: number;
|
||||
};
|
||||
/**
|
||||
* @param n - Curve order. Callers are expected to pass a positive order.
|
||||
* @param nBitLength - Optional cached bit length. Callers are expected to pass a positive cached
|
||||
* value when overriding the derived bit length.
|
||||
* @returns Byte and bit lengths.
|
||||
* @throws If the order or cached bit length is invalid. {@link Error}
|
||||
* @example
|
||||
* Measure the encoding sizes needed for one modulus.
|
||||
*
|
||||
* ```ts
|
||||
* nLength(255n);
|
||||
* ```
|
||||
*/
|
||||
export declare function nLength(n: bigint, nBitLength?: number): NLength;
|
||||
type FpField = IField<bigint> & Required<Pick<IField<bigint>, 'isOdd'>>;
|
||||
type SqrtFn = (n: bigint) => bigint;
|
||||
type FieldOpts = Partial<{
|
||||
isLE: boolean;
|
||||
BITS: number;
|
||||
sqrt: SqrtFn;
|
||||
allowedLengths?: readonly number[];
|
||||
modFromBytes: boolean;
|
||||
}>;
|
||||
/**
|
||||
* Creates a finite field. Major performance optimizations:
|
||||
* * 1. Denormalized operations like mulN instead of mul.
|
||||
* * 2. Identical object shape: never add or remove keys.
|
||||
* * 3. Frozen stable object shape; the lazy sqrt cache lives in a module-level `WeakMap`.
|
||||
* Fragile: always run a benchmark on a change.
|
||||
* Security note: operations and low-level serializers like `toBytes` don't check `isValid` for
|
||||
* all elements for performance and protocol-flexibility reasons; callers are responsible for
|
||||
* supplying valid elements when they need canonical field behavior.
|
||||
* This is low-level code, please make sure you know what you're doing.
|
||||
*
|
||||
* Note about field properties:
|
||||
* * CHARACTERISTIC p = prime number, number of elements in main subgroup.
|
||||
* * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.
|
||||
*
|
||||
* @param ORDER - field order, probably prime, or could be composite
|
||||
* @param opts - Field options such as bit length or endianness. See {@link FieldOpts}.
|
||||
* @returns Frozen field instance with a stable object shape. This wrapper forwards `opts` straight
|
||||
* into `_Field`, so it inherits `_Field`'s assumptions about cached sizes and `allowedLengths`.
|
||||
* @example
|
||||
* Construct one prime field with optional overrides.
|
||||
*
|
||||
* ```ts
|
||||
* Field(11n);
|
||||
* ```
|
||||
*/
|
||||
export declare function Field(ORDER: bigint, opts?: FieldOpts): TRet<Readonly<FpField>>;
|
||||
/**
|
||||
* @param Fp - Field implementation.
|
||||
* @param elm - Value to square-root.
|
||||
* @returns Odd square root when two roots exist. The special case `elm = 0` still returns `0`,
|
||||
* which is the only square root but is not odd.
|
||||
* @throws If the field lacks oddness checks or the square root does not exist. {@link Error}
|
||||
* @example
|
||||
* Select the odd square root when two roots exist.
|
||||
*
|
||||
* ```ts
|
||||
* import { Field, FpSqrtOdd } from '@noble/curves/abstract/modular.js';
|
||||
* const Fp = Field(17n);
|
||||
* const root = FpSqrtOdd(Fp, 4n);
|
||||
* ```
|
||||
*/
|
||||
export declare function FpSqrtOdd<T>(Fp: TArg<IField<T>>, elm: T): T;
|
||||
/**
|
||||
* @param Fp - Field implementation.
|
||||
* @param elm - Value to square-root.
|
||||
* @returns Even square root.
|
||||
* @throws If the field lacks oddness checks or the square root does not exist. {@link Error}
|
||||
* @example
|
||||
* Select the even square root when two roots exist.
|
||||
*
|
||||
* ```ts
|
||||
* import { Field, FpSqrtEven } from '@noble/curves/abstract/modular.js';
|
||||
* const Fp = Field(17n);
|
||||
* const root = FpSqrtEven(Fp, 4n);
|
||||
* ```
|
||||
*/
|
||||
export declare function FpSqrtEven<T>(Fp: TArg<IField<T>>, elm: T): T;
|
||||
/**
|
||||
* Returns total number of bytes consumed by the field element.
|
||||
* For example, 32 bytes for usual 256-bit weierstrass curve.
|
||||
* @param fieldOrder - number of field elements, usually CURVE.n. Callers are expected to pass an
|
||||
* order greater than 1.
|
||||
* @returns byte length of field
|
||||
* @throws If the field order is not a bigint. {@link Error}
|
||||
* @example
|
||||
* Read the fixed-width byte length of one field.
|
||||
*
|
||||
* ```ts
|
||||
* getFieldBytesLength(255n);
|
||||
* ```
|
||||
*/
|
||||
export declare function getFieldBytesLength(fieldOrder: bigint): number;
|
||||
/**
|
||||
* Returns minimal amount of bytes that can be safely reduced
|
||||
* by field order.
|
||||
* Should be 2^-128 for 128-bit curve such as P256.
|
||||
* This is the reduction / modulo-bias lower bound; higher-level helpers may still impose a larger
|
||||
* absolute floor for policy reasons.
|
||||
* @param fieldOrder - number of field elements greater than 1, usually CURVE.n.
|
||||
* @returns byte length of target hash
|
||||
* @throws If the field order is invalid. {@link Error}
|
||||
* @example
|
||||
* Compute the minimum hash length needed for field reduction.
|
||||
*
|
||||
* ```ts
|
||||
* getMinHashLength(255n);
|
||||
* ```
|
||||
*/
|
||||
export declare function getMinHashLength(fieldOrder: bigint): number;
|
||||
/**
|
||||
* "Constant-time" private key generation utility.
|
||||
* Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF
|
||||
* and convert them into private scalar, with the modulo bias being negligible.
|
||||
* Needs at least 48 bytes of input for 32-byte private key. The implementation also keeps a hard
|
||||
* 16-byte minimum even when `getMinHashLength(...)` is smaller, so toy-small inputs do not look
|
||||
* accidentally acceptable for real scalar derivation.
|
||||
* See {@link https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/ | Kudelski's modulo-bias guide},
|
||||
* {@link https://csrc.nist.gov/publications/detail/fips/186/5/final | FIPS 186-5 appendix A.2}, and
|
||||
* {@link https://www.rfc-editor.org/rfc/rfc9380#section-5 | RFC 9380 section 5}. Unlike RFC 9380
|
||||
* `hash_to_field`, this helper intentionally maps into the non-zero private-scalar range `1..n-1`.
|
||||
* @param key - Uniform input bytes.
|
||||
* @param fieldOrder - Size of subgroup.
|
||||
* @param isLE - interpret hash bytes as LE num
|
||||
* @returns valid private scalar
|
||||
* @throws If the hash length or field order is invalid for scalar reduction. {@link Error}
|
||||
* @example
|
||||
* Map hash output into a private scalar range.
|
||||
*
|
||||
* ```ts
|
||||
* mapHashToField(new Uint8Array(48).fill(1), 255n);
|
||||
* ```
|
||||
*/
|
||||
export declare function mapHashToField(key: TArg<Uint8Array>, fieldOrder: bigint, isLE?: boolean): TRet<Uint8Array>;
|
||||
export {};
|
||||
//# sourceMappingURL=modular.d.ts.map
|
||||
1
node_modules/@noble/curves/abstract/modular.d.ts.map
generated
vendored
Normal file
1
node_modules/@noble/curves/abstract/modular.d.ts.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
850
node_modules/@noble/curves/abstract/modular.js
generated
vendored
Normal file
850
node_modules/@noble/curves/abstract/modular.js
generated
vendored
Normal file
@@ -0,0 +1,850 @@
|
||||
/**
|
||||
* Utils for modular division and fields.
|
||||
* Field over 11 is a finite (Galois) field is integer number operations `mod 11`.
|
||||
* There is no division: it is replaced by modular multiplicative inverse.
|
||||
* @module
|
||||
*/
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
import { abool, abytes, anumber, asafenumber, bitLen, bytesToNumberBE, bytesToNumberLE, numberToBytesBE, numberToBytesLE, validateObject, } from "../utils.js";
|
||||
// Numbers aren't used in x25519 / x448 builds
|
||||
// prettier-ignore
|
||||
const _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2);
|
||||
// prettier-ignore
|
||||
const _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5);
|
||||
// prettier-ignore
|
||||
const _7n = /* @__PURE__ */ BigInt(7), _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9);
|
||||
const _16n = /* @__PURE__ */ BigInt(16);
|
||||
/**
|
||||
* @param a - Dividend value.
|
||||
* @param b - Positive modulus.
|
||||
* @returns Reduced value in `[0, b)` only when `b` is positive.
|
||||
* @throws If the modulus is not positive. {@link Error}
|
||||
* @example
|
||||
* Normalize a bigint into one field residue.
|
||||
*
|
||||
* ```ts
|
||||
* mod(-1n, 5n);
|
||||
* ```
|
||||
*/
|
||||
export function mod(a, b) {
|
||||
if (b <= _0n)
|
||||
throw new Error('mod: expected positive modulus, got ' + b);
|
||||
const result = a % b;
|
||||
return result >= _0n ? result : b + result;
|
||||
}
|
||||
/**
|
||||
* Efficiently raise num to a power with modular reduction.
|
||||
* Unsafe in some contexts: uses ladder, so can expose bigint bits.
|
||||
* Low-level helper: callers that need canonical residues must pass a valid `num` for the chosen
|
||||
* modulus instead of relying on the `power===0/1` fast paths to normalize it.
|
||||
* @param num - Base value.
|
||||
* @param power - Exponent value.
|
||||
* @param modulo - Reduction modulus.
|
||||
* @returns Modular exponentiation result.
|
||||
* @throws If the modulus or exponent is invalid. {@link Error}
|
||||
* @example
|
||||
* Raise one bigint to a modular power.
|
||||
*
|
||||
* ```ts
|
||||
* pow(2n, 6n, 11n) // 64n % 11n == 9n
|
||||
* ```
|
||||
*/
|
||||
export function pow(num, power, modulo) {
|
||||
return FpPow(Field(modulo), num, power);
|
||||
}
|
||||
/**
|
||||
* Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)`.
|
||||
* Low-level helper: callers that need canonical residues must pass a valid `x` for the chosen
|
||||
* modulus; the `power===0` fast path intentionally returns the input unchanged.
|
||||
* @param x - Base value.
|
||||
* @param power - Number of squarings.
|
||||
* @param modulo - Reduction modulus.
|
||||
* @returns Repeated-squaring result.
|
||||
* @throws If the exponent is negative. {@link Error}
|
||||
* @example
|
||||
* Apply repeated squaring inside one field.
|
||||
*
|
||||
* ```ts
|
||||
* pow2(3n, 2n, 11n);
|
||||
* ```
|
||||
*/
|
||||
export function pow2(x, power, modulo) {
|
||||
if (power < _0n)
|
||||
throw new Error('pow2: expected non-negative exponent, got ' + power);
|
||||
let res = x;
|
||||
while (power-- > _0n) {
|
||||
res *= res;
|
||||
res %= modulo;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
/**
|
||||
* Inverses number over modulo.
|
||||
* Implemented using the {@link https://brilliant.org/wiki/extended-euclidean-algorithm/ | extended Euclidean algorithm}.
|
||||
* @param number - Value to invert.
|
||||
* @param modulo - Positive modulus.
|
||||
* @returns Multiplicative inverse.
|
||||
* @throws If the modulus is invalid or the inverse does not exist. {@link Error}
|
||||
* @example
|
||||
* Compute one modular inverse with the extended Euclidean algorithm.
|
||||
*
|
||||
* ```ts
|
||||
* invert(3n, 11n);
|
||||
* ```
|
||||
*/
|
||||
export function invert(number, modulo) {
|
||||
if (number === _0n)
|
||||
throw new Error('invert: expected non-zero number');
|
||||
if (modulo <= _0n)
|
||||
throw new Error('invert: expected positive modulus, got ' + modulo);
|
||||
// Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower.
|
||||
let a = mod(number, modulo);
|
||||
let b = modulo;
|
||||
// prettier-ignore
|
||||
let x = _0n, y = _1n, u = _1n, v = _0n;
|
||||
while (a !== _0n) {
|
||||
const q = b / a;
|
||||
const r = b - a * q;
|
||||
const m = x - u * q;
|
||||
const n = y - v * q;
|
||||
// prettier-ignore
|
||||
b = a, a = r, x = u, y = v, u = m, v = n;
|
||||
}
|
||||
const gcd = b;
|
||||
if (gcd !== _1n)
|
||||
throw new Error('invert: does not exist');
|
||||
return mod(x, modulo);
|
||||
}
|
||||
function assertIsSquare(Fp, root, n) {
|
||||
const F = Fp;
|
||||
if (!F.eql(F.sqr(root), n))
|
||||
throw new Error('Cannot find square root');
|
||||
}
|
||||
// Not all roots are possible! Example which will throw:
|
||||
// const NUM =
|
||||
// n = 72057594037927816n;
|
||||
// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));
|
||||
function sqrt3mod4(Fp, n) {
|
||||
const F = Fp;
|
||||
const p1div4 = (F.ORDER + _1n) / _4n;
|
||||
const root = F.pow(n, p1div4);
|
||||
assertIsSquare(F, root, n);
|
||||
return root;
|
||||
}
|
||||
// Equivalent `q = 5 (mod 8)` square-root formula (Atkin-style), not the RFC Appendix I.2 CMOV
|
||||
// pseudocode verbatim.
|
||||
function sqrt5mod8(Fp, n) {
|
||||
const F = Fp;
|
||||
const p5div8 = (F.ORDER - _5n) / _8n;
|
||||
const n2 = F.mul(n, _2n);
|
||||
const v = F.pow(n2, p5div8);
|
||||
const nv = F.mul(n, v);
|
||||
const i = F.mul(F.mul(nv, _2n), v);
|
||||
const root = F.mul(nv, F.sub(i, F.ONE));
|
||||
assertIsSquare(F, root, n);
|
||||
return root;
|
||||
}
|
||||
// Based on RFC9380, Kong algorithm
|
||||
// prettier-ignore
|
||||
function sqrt9mod16(P) {
|
||||
const Fp_ = Field(P);
|
||||
const tn = tonelliShanks(P);
|
||||
const c1 = tn(Fp_, Fp_.neg(Fp_.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F
|
||||
const c2 = tn(Fp_, c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F
|
||||
const c3 = tn(Fp_, Fp_.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F
|
||||
const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic
|
||||
return ((Fp, n) => {
|
||||
const F = Fp;
|
||||
let tv1 = F.pow(n, c4); // 1. tv1 = x^c4
|
||||
let tv2 = F.mul(tv1, c1); // 2. tv2 = c1 * tv1
|
||||
const tv3 = F.mul(tv1, c2); // 3. tv3 = c2 * tv1
|
||||
const tv4 = F.mul(tv1, c3); // 4. tv4 = c3 * tv1
|
||||
const e1 = F.eql(F.sqr(tv2), n); // 5. e1 = (tv2^2) == x
|
||||
const e2 = F.eql(F.sqr(tv3), n); // 6. e2 = (tv3^2) == x
|
||||
tv1 = F.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x
|
||||
tv2 = F.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x
|
||||
const e3 = F.eql(F.sqr(tv2), n); // 9. e3 = (tv2^2) == x
|
||||
const root = F.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select sqrt from tv1 & tv2
|
||||
assertIsSquare(F, root, n);
|
||||
return root;
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Tonelli-Shanks square root search algorithm.
|
||||
* This implementation is variable-time: it searches data-dependently for the first non-residue `Z`
|
||||
* and for the smallest `i` in the main loop, unlike RFC 9380 Appendix I.4's constant-time shape.
|
||||
* 1. {@link https://eprint.iacr.org/2012/685.pdf | eprint 2012/685}, page 12
|
||||
* 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
|
||||
* @param P - field order
|
||||
* @returns function that takes field Fp (created from P) and number n
|
||||
* @throws If the field is too small, non-prime, or the square root does not exist. {@link Error}
|
||||
* @example
|
||||
* Construct a square-root helper for primes that need Tonelli-Shanks.
|
||||
*
|
||||
* ```ts
|
||||
* import { Field, tonelliShanks } from '@noble/curves/abstract/modular.js';
|
||||
* const Fp = Field(17n);
|
||||
* const sqrt = tonelliShanks(17n)(Fp, 4n);
|
||||
* ```
|
||||
*/
|
||||
export function tonelliShanks(P) {
|
||||
// Initialization (precomputation).
|
||||
// Caching initialization could boost perf by 7%.
|
||||
if (P < _3n)
|
||||
throw new Error('sqrt is not defined for small field');
|
||||
// Factor P - 1 = Q * 2^S, where Q is odd
|
||||
let Q = P - _1n;
|
||||
let S = 0;
|
||||
while (Q % _2n === _0n) {
|
||||
Q /= _2n;
|
||||
S++;
|
||||
}
|
||||
// Find the first quadratic non-residue Z >= 2
|
||||
let Z = _2n;
|
||||
const _Fp = Field(P);
|
||||
while (FpLegendre(_Fp, Z) === 1) {
|
||||
// Basic primality test for P. After x iterations, chance of
|
||||
// not finding quadratic non-residue is 2^x, so 2^1000.
|
||||
if (Z++ > 1000)
|
||||
throw new Error('Cannot find square root: probably non-prime P');
|
||||
}
|
||||
// Fast-path; usually done before Z, but we do "primality test".
|
||||
if (S === 1)
|
||||
return sqrt3mod4;
|
||||
// Slow-path
|
||||
// TODO: test on Fp2 and others
|
||||
let cc = _Fp.pow(Z, Q); // c = z^Q
|
||||
const Q1div2 = (Q + _1n) / _2n;
|
||||
return function tonelliSlow(Fp, n) {
|
||||
const F = Fp;
|
||||
if (F.is0(n))
|
||||
return n;
|
||||
// Check if n is a quadratic residue using Legendre symbol
|
||||
if (FpLegendre(F, n) !== 1)
|
||||
throw new Error('Cannot find square root');
|
||||
// Initialize variables for the main loop
|
||||
let M = S;
|
||||
let c = F.mul(F.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp
|
||||
let t = F.pow(n, Q); // t = n^Q, first guess at the fudge factor
|
||||
let R = F.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root
|
||||
// Main loop
|
||||
// while t != 1
|
||||
while (!F.eql(t, F.ONE)) {
|
||||
if (F.is0(t))
|
||||
return F.ZERO; // if t=0 return R=0
|
||||
let i = 1;
|
||||
// Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)
|
||||
let t_tmp = F.sqr(t); // t^(2^1)
|
||||
while (!F.eql(t_tmp, F.ONE)) {
|
||||
i++;
|
||||
t_tmp = F.sqr(t_tmp); // t^(2^2)...
|
||||
if (i === M)
|
||||
throw new Error('Cannot find square root');
|
||||
}
|
||||
// Calculate the exponent for b: 2^(M - i - 1)
|
||||
const exponent = _1n << BigInt(M - i - 1); // bigint is important
|
||||
const b = F.pow(c, exponent); // b = 2^(M - i - 1)
|
||||
// Update variables
|
||||
M = i;
|
||||
c = F.sqr(b); // c = b^2
|
||||
t = F.mul(t, c); // t = (t * b^2)
|
||||
R = F.mul(R, b); // R = R*b
|
||||
}
|
||||
return R;
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Square root for a finite field. Will try optimized versions first:
|
||||
*
|
||||
* 1. P ≡ 3 (mod 4)
|
||||
* 2. P ≡ 5 (mod 8)
|
||||
* 3. P ≡ 9 (mod 16)
|
||||
* 4. Tonelli-Shanks algorithm
|
||||
*
|
||||
* Different algorithms can give different roots, it is up to user to decide which one they want.
|
||||
* For example there is FpSqrtOdd/FpSqrtEven to choose a root by oddness
|
||||
* (used for hash-to-curve).
|
||||
* @param P - Field order.
|
||||
* @returns Square-root helper. The generic fallback inherits Tonelli-Shanks' variable-time
|
||||
* behavior and this selector assumes prime-field-style integer moduli.
|
||||
* @throws If the field is unsupported or the square root does not exist. {@link Error}
|
||||
* @example
|
||||
* Choose the square-root helper appropriate for one field modulus.
|
||||
*
|
||||
* ```ts
|
||||
* import { Field, FpSqrt } from '@noble/curves/abstract/modular.js';
|
||||
* const Fp = Field(17n);
|
||||
* const sqrt = FpSqrt(17n)(Fp, 4n);
|
||||
* ```
|
||||
*/
|
||||
export function FpSqrt(P) {
|
||||
// P ≡ 3 (mod 4) => √n = n^((P+1)/4)
|
||||
if (P % _4n === _3n)
|
||||
return sqrt3mod4;
|
||||
// P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf
|
||||
if (P % _8n === _5n)
|
||||
return sqrt5mod8;
|
||||
// P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)
|
||||
if (P % _16n === _9n)
|
||||
return sqrt9mod16(P);
|
||||
// Tonelli-Shanks algorithm
|
||||
return tonelliShanks(P);
|
||||
}
|
||||
/**
|
||||
* @param num - Value to inspect.
|
||||
* @param modulo - Field modulus.
|
||||
* @returns `true` when the least-significant little-endian bit is set.
|
||||
* @throws If the modulus is invalid for `mod(...)`. {@link Error}
|
||||
* @example
|
||||
* Inspect the low bit used by little-endian sign conventions.
|
||||
*
|
||||
* ```ts
|
||||
* isNegativeLE(3n, 11n);
|
||||
* ```
|
||||
*/
|
||||
export const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;
|
||||
// prettier-ignore
|
||||
// Arithmetic-only subset checked by validateField(). This is intentionally not the full runtime
|
||||
// IField contract: helpers like `isValidNot0`, `invertBatch`, `toBytes`, `fromBytes`, `cmov`, and
|
||||
// field-specific extras like `isOdd` are left to the callers that actually need them.
|
||||
const FIELD_FIELDS = [
|
||||
'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',
|
||||
'eql', 'add', 'sub', 'mul', 'pow', 'div',
|
||||
'addN', 'subN', 'mulN', 'sqrN'
|
||||
];
|
||||
/**
|
||||
* @param field - Field implementation.
|
||||
* @returns Validated field. This only checks the arithmetic subset needed by generic helpers; it
|
||||
* does not guarantee full runtime-method coverage for serialization, batching, `cmov`, or
|
||||
* field-specific extras beyond positive `BYTES` / `BITS`.
|
||||
* @throws If the field shape or numeric metadata are invalid. {@link Error}
|
||||
* @example
|
||||
* Check that a field implementation exposes the operations curve code expects.
|
||||
*
|
||||
* ```ts
|
||||
* import { Field, validateField } from '@noble/curves/abstract/modular.js';
|
||||
* const Fp = validateField(Field(17n));
|
||||
* ```
|
||||
*/
|
||||
export function validateField(field) {
|
||||
const initial = {
|
||||
ORDER: 'bigint',
|
||||
BYTES: 'number',
|
||||
BITS: 'number',
|
||||
};
|
||||
const opts = FIELD_FIELDS.reduce((map, val) => {
|
||||
map[val] = 'function';
|
||||
return map;
|
||||
}, initial);
|
||||
validateObject(field, opts);
|
||||
// Runtime field implementations must expose real integer byte/bit sizes; fractional / NaN /
|
||||
// infinite metadata leaks through validateObject(type='number') but breaks encoders and caches.
|
||||
asafenumber(field.BYTES, 'BYTES');
|
||||
asafenumber(field.BITS, 'BITS');
|
||||
// Runtime field implementations must expose positive byte/bit sizes; zero leaks through the
|
||||
// numeric shape checks above but still breaks encoding helpers and cached-length assumptions.
|
||||
if (field.BYTES < 1 || field.BITS < 1)
|
||||
throw new Error('invalid field: expected BYTES/BITS > 0');
|
||||
if (field.ORDER <= _1n)
|
||||
throw new Error('invalid field: expected ORDER > 1, got ' + field.ORDER);
|
||||
return field;
|
||||
}
|
||||
// Generic field functions
|
||||
/**
|
||||
* Same as `pow` but for Fp: non-constant-time.
|
||||
* Unsafe in some contexts: uses ladder, so can expose bigint bits.
|
||||
* @param Fp - Field implementation.
|
||||
* @param num - Base value.
|
||||
* @param power - Exponent value.
|
||||
* @returns Powered field element.
|
||||
* @throws If the exponent is negative. {@link Error}
|
||||
* @example
|
||||
* Raise one field element to a public exponent.
|
||||
*
|
||||
* ```ts
|
||||
* import { Field, FpPow } from '@noble/curves/abstract/modular.js';
|
||||
* const Fp = Field(17n);
|
||||
* const x = FpPow(Fp, 3n, 5n);
|
||||
* ```
|
||||
*/
|
||||
export function FpPow(Fp, num, power) {
|
||||
const F = Fp;
|
||||
if (power < _0n)
|
||||
throw new Error('invalid exponent, negatives unsupported');
|
||||
if (power === _0n)
|
||||
return F.ONE;
|
||||
if (power === _1n)
|
||||
return num;
|
||||
let p = F.ONE;
|
||||
let d = num;
|
||||
while (power > _0n) {
|
||||
if (power & _1n)
|
||||
p = F.mul(p, d);
|
||||
d = F.sqr(d);
|
||||
power >>= _1n;
|
||||
}
|
||||
return p;
|
||||
}
|
||||
/**
|
||||
* Efficiently invert an array of Field elements.
|
||||
* Exception-free. Zero-valued field elements stay `undefined` unless `passZero` is enabled.
|
||||
* @param Fp - Field implementation.
|
||||
* @param nums - Values to invert.
|
||||
* @param passZero - map 0 to 0 (instead of undefined)
|
||||
* @returns Inverted values.
|
||||
* @example
|
||||
* Invert several field elements with one shared inversion.
|
||||
*
|
||||
* ```ts
|
||||
* import { Field, FpInvertBatch } from '@noble/curves/abstract/modular.js';
|
||||
* const Fp = Field(17n);
|
||||
* const inv = FpInvertBatch(Fp, [1n, 2n, 4n]);
|
||||
* ```
|
||||
*/
|
||||
export function FpInvertBatch(Fp, nums, passZero = false) {
|
||||
const F = Fp;
|
||||
const inverted = new Array(nums.length).fill(passZero ? F.ZERO : undefined);
|
||||
// Walk from first to last, multiply them by each other MOD p
|
||||
const multipliedAcc = nums.reduce((acc, num, i) => {
|
||||
if (F.is0(num))
|
||||
return acc;
|
||||
inverted[i] = acc;
|
||||
return F.mul(acc, num);
|
||||
}, F.ONE);
|
||||
// Invert last element
|
||||
const invertedAcc = F.inv(multipliedAcc);
|
||||
// Walk from last to first, multiply them by inverted each other MOD p
|
||||
nums.reduceRight((acc, num, i) => {
|
||||
if (F.is0(num))
|
||||
return acc;
|
||||
inverted[i] = F.mul(acc, inverted[i]);
|
||||
return F.mul(acc, num);
|
||||
}, invertedAcc);
|
||||
return inverted;
|
||||
}
|
||||
/**
|
||||
* @param Fp - Field implementation.
|
||||
* @param lhs - Dividend value.
|
||||
* @param rhs - Divisor value.
|
||||
* @returns Division result.
|
||||
* @throws If the divisor is non-invertible. {@link Error}
|
||||
* @example
|
||||
* Divide one field element by another.
|
||||
*
|
||||
* ```ts
|
||||
* import { Field, FpDiv } from '@noble/curves/abstract/modular.js';
|
||||
* const Fp = Field(17n);
|
||||
* const x = FpDiv(Fp, 6n, 3n);
|
||||
* ```
|
||||
*/
|
||||
export function FpDiv(Fp, lhs, rhs) {
|
||||
const F = Fp;
|
||||
return F.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, F.ORDER) : F.inv(rhs));
|
||||
}
|
||||
/**
|
||||
* Legendre symbol.
|
||||
* Legendre constant is used to calculate Legendre symbol (a | p)
|
||||
* which denotes the value of a^((p-1)/2) (mod p).
|
||||
*
|
||||
* * (a | p) ≡ 1 if a is a square (mod p), quadratic residue
|
||||
* * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue
|
||||
* * (a | p) ≡ 0 if a ≡ 0 (mod p)
|
||||
* @param Fp - Field implementation.
|
||||
* @param n - Value to inspect.
|
||||
* @returns Legendre symbol.
|
||||
* @throws If the field returns an invalid Legendre symbol value. {@link Error}
|
||||
* @example
|
||||
* Compute the Legendre symbol of one field element.
|
||||
*
|
||||
* ```ts
|
||||
* import { Field, FpLegendre } from '@noble/curves/abstract/modular.js';
|
||||
* const Fp = Field(17n);
|
||||
* const symbol = FpLegendre(Fp, 4n);
|
||||
* ```
|
||||
*/
|
||||
export function FpLegendre(Fp, n) {
|
||||
const F = Fp;
|
||||
// We can use 3rd argument as optional cache of this value
|
||||
// but seems unneeded for now. The operation is very fast.
|
||||
const p1mod2 = (F.ORDER - _1n) / _2n;
|
||||
const powered = F.pow(n, p1mod2);
|
||||
const yes = F.eql(powered, F.ONE);
|
||||
const zero = F.eql(powered, F.ZERO);
|
||||
const no = F.eql(powered, F.neg(F.ONE));
|
||||
if (!yes && !zero && !no)
|
||||
throw new Error('invalid Legendre symbol result');
|
||||
return yes ? 1 : zero ? 0 : -1;
|
||||
}
|
||||
/**
|
||||
* @param Fp - Field implementation.
|
||||
* @param n - Value to inspect.
|
||||
* @returns `true` when `Fp.sqrt(n)` exists. This includes `0`, even though strict "quadratic
|
||||
* residue" terminology often reserves that name for the non-zero square class.
|
||||
* @throws If the field returns an invalid Legendre symbol value. {@link Error}
|
||||
* @example
|
||||
* Check whether one field element has a square root in the field.
|
||||
*
|
||||
* ```ts
|
||||
* import { Field, FpIsSquare } from '@noble/curves/abstract/modular.js';
|
||||
* const Fp = Field(17n);
|
||||
* const isSquare = FpIsSquare(Fp, 4n);
|
||||
* ```
|
||||
*/
|
||||
export function FpIsSquare(Fp, n) {
|
||||
const l = FpLegendre(Fp, n);
|
||||
// Zero is a square too: 0 = 0^2, and Fp.sqrt(0) already returns 0.
|
||||
return l !== -1;
|
||||
}
|
||||
/**
|
||||
* @param n - Curve order. Callers are expected to pass a positive order.
|
||||
* @param nBitLength - Optional cached bit length. Callers are expected to pass a positive cached
|
||||
* value when overriding the derived bit length.
|
||||
* @returns Byte and bit lengths.
|
||||
* @throws If the order or cached bit length is invalid. {@link Error}
|
||||
* @example
|
||||
* Measure the encoding sizes needed for one modulus.
|
||||
*
|
||||
* ```ts
|
||||
* nLength(255n);
|
||||
* ```
|
||||
*/
|
||||
export function nLength(n, nBitLength) {
|
||||
// Bit size, byte size of CURVE.n
|
||||
if (nBitLength !== undefined)
|
||||
anumber(nBitLength);
|
||||
if (n <= _0n)
|
||||
throw new Error('invalid n length: expected positive n, got ' + n);
|
||||
if (nBitLength !== undefined && nBitLength < 1)
|
||||
throw new Error('invalid n length: expected positive bit length, got ' + nBitLength);
|
||||
const bits = bitLen(n);
|
||||
// Cached bit lengths smaller than ORDER would truncate serialized scalars/elements and poison
|
||||
// any math that relies on the derived field metadata.
|
||||
if (nBitLength !== undefined && nBitLength < bits)
|
||||
throw new Error(`invalid n length: expected bit length (${bits}) >= n.length (${nBitLength})`);
|
||||
const _nBitLength = nBitLength !== undefined ? nBitLength : bits;
|
||||
const nByteLength = Math.ceil(_nBitLength / 8);
|
||||
return { nBitLength: _nBitLength, nByteLength };
|
||||
}
|
||||
// Keep the lazy sqrt cache off-instance so Field(...) can return a frozen object. Otherwise the
|
||||
// cached helper write would keep the field surface externally mutable.
|
||||
const FIELD_SQRT = new WeakMap();
|
||||
class _Field {
|
||||
ORDER;
|
||||
BITS;
|
||||
BYTES;
|
||||
isLE;
|
||||
ZERO = _0n;
|
||||
ONE = _1n;
|
||||
_lengths;
|
||||
_mod;
|
||||
constructor(ORDER, opts = {}) {
|
||||
// ORDER <= 1 is degenerate: ONE would not be a valid field element and helpers like pow/inv
|
||||
// would stop modeling field arithmetic.
|
||||
if (ORDER <= _1n)
|
||||
throw new Error('invalid field: expected ORDER > 1, got ' + ORDER);
|
||||
let _nbitLength = undefined;
|
||||
this.isLE = false;
|
||||
if (opts != null && typeof opts === 'object') {
|
||||
// Cached bit lengths are trusted here and should already be positive / consistent with ORDER.
|
||||
if (typeof opts.BITS === 'number')
|
||||
_nbitLength = opts.BITS;
|
||||
if (typeof opts.sqrt === 'function')
|
||||
// `_Field.prototype` is frozen below, so custom sqrt hooks must become own properties
|
||||
// explicitly instead of relying on writable prototype shadowing via assignment.
|
||||
Object.defineProperty(this, 'sqrt', { value: opts.sqrt, enumerable: true });
|
||||
if (typeof opts.isLE === 'boolean')
|
||||
this.isLE = opts.isLE;
|
||||
if (opts.allowedLengths)
|
||||
this._lengths = Object.freeze(opts.allowedLengths.slice());
|
||||
if (typeof opts.modFromBytes === 'boolean')
|
||||
this._mod = opts.modFromBytes;
|
||||
}
|
||||
const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);
|
||||
if (nByteLength > 2048)
|
||||
throw new Error('invalid field: expected ORDER of <= 2048 bytes');
|
||||
this.ORDER = ORDER;
|
||||
this.BITS = nBitLength;
|
||||
this.BYTES = nByteLength;
|
||||
Object.freeze(this);
|
||||
}
|
||||
create(num) {
|
||||
return mod(num, this.ORDER);
|
||||
}
|
||||
isValid(num) {
|
||||
if (typeof num !== 'bigint')
|
||||
throw new TypeError('invalid field element: expected bigint, got ' + typeof num);
|
||||
return _0n <= num && num < this.ORDER; // 0 is valid element, but it's not invertible
|
||||
}
|
||||
is0(num) {
|
||||
return num === _0n;
|
||||
}
|
||||
// is valid and invertible
|
||||
isValidNot0(num) {
|
||||
return !this.is0(num) && this.isValid(num);
|
||||
}
|
||||
isOdd(num) {
|
||||
return (num & _1n) === _1n;
|
||||
}
|
||||
neg(num) {
|
||||
return mod(-num, this.ORDER);
|
||||
}
|
||||
eql(lhs, rhs) {
|
||||
return lhs === rhs;
|
||||
}
|
||||
sqr(num) {
|
||||
return mod(num * num, this.ORDER);
|
||||
}
|
||||
add(lhs, rhs) {
|
||||
return mod(lhs + rhs, this.ORDER);
|
||||
}
|
||||
sub(lhs, rhs) {
|
||||
return mod(lhs - rhs, this.ORDER);
|
||||
}
|
||||
mul(lhs, rhs) {
|
||||
return mod(lhs * rhs, this.ORDER);
|
||||
}
|
||||
pow(num, power) {
|
||||
return FpPow(this, num, power);
|
||||
}
|
||||
div(lhs, rhs) {
|
||||
return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
|
||||
}
|
||||
// Same as above, but doesn't normalize
|
||||
sqrN(num) {
|
||||
return num * num;
|
||||
}
|
||||
addN(lhs, rhs) {
|
||||
return lhs + rhs;
|
||||
}
|
||||
subN(lhs, rhs) {
|
||||
return lhs - rhs;
|
||||
}
|
||||
mulN(lhs, rhs) {
|
||||
return lhs * rhs;
|
||||
}
|
||||
inv(num) {
|
||||
return invert(num, this.ORDER);
|
||||
}
|
||||
sqrt(num) {
|
||||
// Caching sqrt helpers speeds up sqrt9mod16 by 5x and Tonelli-Shanks by about 10% without keeping
|
||||
// the field instance itself mutable.
|
||||
let sqrt = FIELD_SQRT.get(this);
|
||||
if (!sqrt)
|
||||
FIELD_SQRT.set(this, (sqrt = FpSqrt(this.ORDER)));
|
||||
return sqrt(this, num);
|
||||
}
|
||||
toBytes(num) {
|
||||
// Serialize fixed-width limbs without re-validating the field range. Callers that need a
|
||||
// canonical encoding must pass a valid element; some protocols intentionally serialize raw
|
||||
// residues here and reduce or validate them elsewhere.
|
||||
return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);
|
||||
}
|
||||
fromBytes(bytes, skipValidation = false) {
|
||||
abytes(bytes);
|
||||
const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;
|
||||
if (allowedLengths) {
|
||||
// `allowedLengths` must list real positive byte lengths; otherwise empty input would get
|
||||
// padded into zero and silently decode as a field element.
|
||||
if (bytes.length < 1 || !allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
|
||||
throw new Error('Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length);
|
||||
}
|
||||
const padded = new Uint8Array(BYTES);
|
||||
// isLE add 0 to right, !isLE to the left.
|
||||
padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
|
||||
bytes = padded;
|
||||
}
|
||||
if (bytes.length !== BYTES)
|
||||
throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);
|
||||
let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
|
||||
if (modFromBytes)
|
||||
scalar = mod(scalar, ORDER);
|
||||
if (!skipValidation)
|
||||
if (!this.isValid(scalar))
|
||||
throw new Error('invalid field element: outside of range 0..ORDER');
|
||||
// Range validation is optional here because some protocols intentionally decode raw residues
|
||||
// and reduce or validate them elsewhere.
|
||||
return scalar;
|
||||
}
|
||||
// TODO: we don't need it here, move out to separate fn
|
||||
invertBatch(lst) {
|
||||
return FpInvertBatch(this, lst);
|
||||
}
|
||||
// We can't move this out because Fp6, Fp12 implement it
|
||||
// and it's unclear what to return in there.
|
||||
cmov(a, b, condition) {
|
||||
// Field elements have `isValid(...)`; the CMOV branch bit is a direct runtime input, so reject
|
||||
// non-boolean selectors here instead of letting JS truthiness silently change arithmetic.
|
||||
abool(condition, 'condition');
|
||||
return condition ? b : a;
|
||||
}
|
||||
}
|
||||
// Freeze the shared method surface too; otherwise callers can still poison every Field instance by
|
||||
// monkey-patching `_Field.prototype` even if each instance is frozen.
|
||||
Object.freeze(_Field.prototype);
|
||||
/**
|
||||
* Creates a finite field. Major performance optimizations:
|
||||
* * 1. Denormalized operations like mulN instead of mul.
|
||||
* * 2. Identical object shape: never add or remove keys.
|
||||
* * 3. Frozen stable object shape; the lazy sqrt cache lives in a module-level `WeakMap`.
|
||||
* Fragile: always run a benchmark on a change.
|
||||
* Security note: operations and low-level serializers like `toBytes` don't check `isValid` for
|
||||
* all elements for performance and protocol-flexibility reasons; callers are responsible for
|
||||
* supplying valid elements when they need canonical field behavior.
|
||||
* This is low-level code, please make sure you know what you're doing.
|
||||
*
|
||||
* Note about field properties:
|
||||
* * CHARACTERISTIC p = prime number, number of elements in main subgroup.
|
||||
* * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.
|
||||
*
|
||||
* @param ORDER - field order, probably prime, or could be composite
|
||||
* @param opts - Field options such as bit length or endianness. See {@link FieldOpts}.
|
||||
* @returns Frozen field instance with a stable object shape. This wrapper forwards `opts` straight
|
||||
* into `_Field`, so it inherits `_Field`'s assumptions about cached sizes and `allowedLengths`.
|
||||
* @example
|
||||
* Construct one prime field with optional overrides.
|
||||
*
|
||||
* ```ts
|
||||
* Field(11n);
|
||||
* ```
|
||||
*/
|
||||
export function Field(ORDER, opts = {}) {
|
||||
return new _Field(ORDER, opts);
|
||||
}
|
||||
// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?
|
||||
// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).
|
||||
// which mean we cannot force this via opts.
|
||||
// Not sure what to do with randomBytes, we can accept it inside opts if wanted.
|
||||
// Probably need to export getMinHashLength somewhere?
|
||||
// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {
|
||||
// const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;
|
||||
// if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?
|
||||
// const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
|
||||
// // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
|
||||
// const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;
|
||||
// return reduced;
|
||||
// },
|
||||
/**
|
||||
* @param Fp - Field implementation.
|
||||
* @param elm - Value to square-root.
|
||||
* @returns Odd square root when two roots exist. The special case `elm = 0` still returns `0`,
|
||||
* which is the only square root but is not odd.
|
||||
* @throws If the field lacks oddness checks or the square root does not exist. {@link Error}
|
||||
* @example
|
||||
* Select the odd square root when two roots exist.
|
||||
*
|
||||
* ```ts
|
||||
* import { Field, FpSqrtOdd } from '@noble/curves/abstract/modular.js';
|
||||
* const Fp = Field(17n);
|
||||
* const root = FpSqrtOdd(Fp, 4n);
|
||||
* ```
|
||||
*/
|
||||
export function FpSqrtOdd(Fp, elm) {
|
||||
const F = Fp;
|
||||
if (!F.isOdd)
|
||||
throw new Error("Field doesn't have isOdd");
|
||||
const root = F.sqrt(elm);
|
||||
return F.isOdd(root) ? root : F.neg(root);
|
||||
}
|
||||
/**
|
||||
* @param Fp - Field implementation.
|
||||
* @param elm - Value to square-root.
|
||||
* @returns Even square root.
|
||||
* @throws If the field lacks oddness checks or the square root does not exist. {@link Error}
|
||||
* @example
|
||||
* Select the even square root when two roots exist.
|
||||
*
|
||||
* ```ts
|
||||
* import { Field, FpSqrtEven } from '@noble/curves/abstract/modular.js';
|
||||
* const Fp = Field(17n);
|
||||
* const root = FpSqrtEven(Fp, 4n);
|
||||
* ```
|
||||
*/
|
||||
export function FpSqrtEven(Fp, elm) {
|
||||
const F = Fp;
|
||||
if (!F.isOdd)
|
||||
throw new Error("Field doesn't have isOdd");
|
||||
const root = F.sqrt(elm);
|
||||
return F.isOdd(root) ? F.neg(root) : root;
|
||||
}
|
||||
/**
|
||||
* Returns total number of bytes consumed by the field element.
|
||||
* For example, 32 bytes for usual 256-bit weierstrass curve.
|
||||
* @param fieldOrder - number of field elements, usually CURVE.n. Callers are expected to pass an
|
||||
* order greater than 1.
|
||||
* @returns byte length of field
|
||||
* @throws If the field order is not a bigint. {@link Error}
|
||||
* @example
|
||||
* Read the fixed-width byte length of one field.
|
||||
*
|
||||
* ```ts
|
||||
* getFieldBytesLength(255n);
|
||||
* ```
|
||||
*/
|
||||
export function getFieldBytesLength(fieldOrder) {
|
||||
if (typeof fieldOrder !== 'bigint')
|
||||
throw new Error('field order must be bigint');
|
||||
// Valid field elements are in 0..ORDER-1, so ORDER <= 1 would make the encoded range degenerate.
|
||||
if (fieldOrder <= _1n)
|
||||
throw new Error('field order must be greater than 1');
|
||||
// Valid field elements are < ORDER, so the maximal encoded element is ORDER - 1.
|
||||
const bitLength = bitLen(fieldOrder - _1n);
|
||||
return Math.ceil(bitLength / 8);
|
||||
}
|
||||
/**
|
||||
* Returns minimal amount of bytes that can be safely reduced
|
||||
* by field order.
|
||||
* Should be 2^-128 for 128-bit curve such as P256.
|
||||
* This is the reduction / modulo-bias lower bound; higher-level helpers may still impose a larger
|
||||
* absolute floor for policy reasons.
|
||||
* @param fieldOrder - number of field elements greater than 1, usually CURVE.n.
|
||||
* @returns byte length of target hash
|
||||
* @throws If the field order is invalid. {@link Error}
|
||||
* @example
|
||||
* Compute the minimum hash length needed for field reduction.
|
||||
*
|
||||
* ```ts
|
||||
* getMinHashLength(255n);
|
||||
* ```
|
||||
*/
|
||||
export function getMinHashLength(fieldOrder) {
|
||||
const length = getFieldBytesLength(fieldOrder);
|
||||
return length + Math.ceil(length / 2);
|
||||
}
|
||||
/**
|
||||
* "Constant-time" private key generation utility.
|
||||
* Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF
|
||||
* and convert them into private scalar, with the modulo bias being negligible.
|
||||
* Needs at least 48 bytes of input for 32-byte private key. The implementation also keeps a hard
|
||||
* 16-byte minimum even when `getMinHashLength(...)` is smaller, so toy-small inputs do not look
|
||||
* accidentally acceptable for real scalar derivation.
|
||||
* See {@link https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/ | Kudelski's modulo-bias guide},
|
||||
* {@link https://csrc.nist.gov/publications/detail/fips/186/5/final | FIPS 186-5 appendix A.2}, and
|
||||
* {@link https://www.rfc-editor.org/rfc/rfc9380#section-5 | RFC 9380 section 5}. Unlike RFC 9380
|
||||
* `hash_to_field`, this helper intentionally maps into the non-zero private-scalar range `1..n-1`.
|
||||
* @param key - Uniform input bytes.
|
||||
* @param fieldOrder - Size of subgroup.
|
||||
* @param isLE - interpret hash bytes as LE num
|
||||
* @returns valid private scalar
|
||||
* @throws If the hash length or field order is invalid for scalar reduction. {@link Error}
|
||||
* @example
|
||||
* Map hash output into a private scalar range.
|
||||
*
|
||||
* ```ts
|
||||
* mapHashToField(new Uint8Array(48).fill(1), 255n);
|
||||
* ```
|
||||
*/
|
||||
export function mapHashToField(key, fieldOrder, isLE = false) {
|
||||
abytes(key);
|
||||
const len = key.length;
|
||||
const fieldLen = getFieldBytesLength(fieldOrder);
|
||||
const minLen = Math.max(getMinHashLength(fieldOrder), 16);
|
||||
// No toy-small inputs: the helper is for real scalar derivation, not tiny test curves. No huge
|
||||
// inputs: easier to reason about JS timing / allocation behavior.
|
||||
if (len < minLen || len > 1024)
|
||||
throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);
|
||||
const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
|
||||
// `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
|
||||
const reduced = mod(num, fieldOrder - _1n) + _1n;
|
||||
return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
|
||||
}
|
||||
//# sourceMappingURL=modular.js.map
|
||||
1
node_modules/@noble/curves/abstract/modular.js.map
generated
vendored
Normal file
1
node_modules/@noble/curves/abstract/modular.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
96
node_modules/@noble/curves/abstract/montgomery.d.ts
generated
vendored
Normal file
96
node_modules/@noble/curves/abstract/montgomery.d.ts
generated
vendored
Normal file
@@ -0,0 +1,96 @@
|
||||
/**
|
||||
* Montgomery curve methods. It's not really whole montgomery curve,
|
||||
* just bunch of very specific methods for X25519 / X448 from
|
||||
* [RFC 7748](https://www.rfc-editor.org/rfc/rfc7748)
|
||||
* @module
|
||||
*/
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
import { type TArg, type TRet } from '../utils.ts';
|
||||
import { type CurveLengths } from './curve.ts';
|
||||
/** Curve-specific hooks required to build one X25519/X448 helper. */
|
||||
export type MontgomeryOpts = {
|
||||
/** Prime field modulus. */
|
||||
P: bigint;
|
||||
/** RFC 7748 variant name. */
|
||||
type: 'x25519' | 'x448';
|
||||
/**
|
||||
* Clamp or otherwise normalize one scalar byte string before use.
|
||||
* @param bytes - Raw secret scalar bytes.
|
||||
* @returns Adjusted scalar bytes ready for Montgomery multiplication.
|
||||
*/
|
||||
adjustScalarBytes: (bytes: TArg<Uint8Array>) => TRet<Uint8Array>;
|
||||
/**
|
||||
* Invert one field element with exponentiation by `p - 2`.
|
||||
* @param x - Field element to invert.
|
||||
* @returns Multiplicative inverse of `x`.
|
||||
*/
|
||||
powPminus2: (x: bigint) => bigint;
|
||||
/**
|
||||
* Optional randomness source for `keygen()` and `utils.randomSecretKey()`.
|
||||
* Receives the requested byte length and returns fresh random bytes.
|
||||
*/
|
||||
randomBytes?: (bytesLength?: number) => TRet<Uint8Array>;
|
||||
};
|
||||
/** Public X25519/X448 ECDH API built on a Montgomery ladder. */
|
||||
export type MontgomeryECDH = {
|
||||
/**
|
||||
* Multiply one scalar by one Montgomery `u` coordinate.
|
||||
* @param scalar - Secret scalar bytes.
|
||||
* @param u - Public Montgomery `u` coordinate.
|
||||
* @returns Shared point encoded as bytes.
|
||||
*/
|
||||
scalarMult: (scalar: TArg<Uint8Array>, u: TArg<Uint8Array>) => TRet<Uint8Array>;
|
||||
/**
|
||||
* Multiply one scalar by the curve base point.
|
||||
* @param scalar - Secret scalar bytes.
|
||||
* @returns Public key bytes.
|
||||
*/
|
||||
scalarMultBase: (scalar: TArg<Uint8Array>) => TRet<Uint8Array>;
|
||||
/**
|
||||
* Derive a shared secret from a local secret key and peer public key.
|
||||
* @param secretKeyA - Local secret key bytes.
|
||||
* @param publicKeyB - Peer public key bytes.
|
||||
* Rejects low-order public inputs instead of returning the all-zero shared secret.
|
||||
* @returns Shared secret bytes.
|
||||
*/
|
||||
getSharedSecret: (secretKeyA: TArg<Uint8Array>, publicKeyB: TArg<Uint8Array>) => TRet<Uint8Array>;
|
||||
/**
|
||||
* Derive one public key from a secret key.
|
||||
* @param secretKey - Secret key bytes.
|
||||
* @returns Public key bytes.
|
||||
*/
|
||||
getPublicKey: (secretKey: TArg<Uint8Array>) => TRet<Uint8Array>;
|
||||
/** Utility helpers for secret-key generation. */
|
||||
utils: {
|
||||
/** Generate one random secret key with the curve's expected byte length. */
|
||||
randomSecretKey: () => TRet<Uint8Array>;
|
||||
};
|
||||
/** Encoded Montgomery base point `u`. */
|
||||
GuBytes: TRet<Uint8Array>;
|
||||
/** Public lengths for keys and seeds. */
|
||||
lengths: CurveLengths;
|
||||
/**
|
||||
* Generate one random secret/public keypair.
|
||||
* @param seed - Optional seed bytes to use instead of random generation.
|
||||
* @returns Fresh secret/public keypair.
|
||||
*/
|
||||
keygen: (seed?: TArg<Uint8Array>) => {
|
||||
secretKey: TRet<Uint8Array>;
|
||||
publicKey: TRet<Uint8Array>;
|
||||
};
|
||||
};
|
||||
/**
|
||||
* @param curveDef - Montgomery curve definition.
|
||||
* @returns ECDH helper namespace.
|
||||
* @throws If the curve definition or derived shared point is invalid. {@link Error}
|
||||
* @example
|
||||
* Perform one X25519 key exchange through the generic Montgomery helper.
|
||||
*
|
||||
* ```ts
|
||||
* import { x25519 } from '@noble/curves/ed25519.js';
|
||||
* const alice = x25519.keygen();
|
||||
* const shared = x25519.getSharedSecret(alice.secretKey, alice.publicKey);
|
||||
* ```
|
||||
*/
|
||||
export declare function montgomery(curveDef: TArg<MontgomeryOpts>): TRet<MontgomeryECDH>;
|
||||
//# sourceMappingURL=montgomery.d.ts.map
|
||||
1
node_modules/@noble/curves/abstract/montgomery.d.ts.map
generated
vendored
Normal file
1
node_modules/@noble/curves/abstract/montgomery.d.ts.map
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"montgomery.d.ts","sourceRoot":"","sources":["../src/abstract/montgomery.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,sEAAsE;AACtE,OAAO,EASL,KAAK,IAAI,EACT,KAAK,IAAI,EACV,MAAM,aAAa,CAAC;AACrB,OAAO,EAAgB,KAAK,YAAY,EAAE,MAAM,YAAY,CAAC;AAO7D,qEAAqE;AACrE,MAAM,MAAM,cAAc,GAAG;IAC3B,2BAA2B;IAC3B,CAAC,EAAE,MAAM,CAAC;IACV,6BAA6B;IAC7B,IAAI,EAAE,QAAQ,GAAG,MAAM,CAAC;IACxB;;;;OAIG;IACH,iBAAiB,EAAE,CAAC,KAAK,EAAE,IAAI,CAAC,UAAU,CAAC,KAAK,IAAI,CAAC,UAAU,CAAC,CAAC;IACjE;;;;OAIG;IACH,UAAU,EAAE,CAAC,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;IAClC;;;OAGG;IACH,WAAW,CAAC,EAAE,CAAC,WAAW,CAAC,EAAE,MAAM,KAAK,IAAI,CAAC,UAAU,CAAC,CAAC;CAC1D,CAAC;AAEF,gEAAgE;AAChE,MAAM,MAAM,cAAc,GAAG;IAC3B;;;;;OAKG;IACH,UAAU,EAAE,CAAC,MAAM,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,UAAU,CAAC,KAAK,IAAI,CAAC,UAAU,CAAC,CAAC;IAChF;;;;OAIG;IACH,cAAc,EAAE,CAAC,MAAM,EAAE,IAAI,CAAC,UAAU,CAAC,KAAK,IAAI,CAAC,UAAU,CAAC,CAAC;IAC/D;;;;;;OAMG;IACH,eAAe,EAAE,CAAC,UAAU,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,UAAU,EAAE,IAAI,CAAC,UAAU,CAAC,KAAK,IAAI,CAAC,UAAU,CAAC,CAAC;IAClG;;;;OAIG;IACH,YAAY,EAAE,CAAC,SAAS,EAAE,IAAI,CAAC,UAAU,CAAC,KAAK,IAAI,CAAC,UAAU,CAAC,CAAC;IAChE,iDAAiD;IACjD,KAAK,EAAE;QACL,4EAA4E;QAC5E,eAAe,EAAE,MAAM,IAAI,CAAC,UAAU,CAAC,CAAC;KACzC,CAAC;IACF,yCAAyC;IACzC,OAAO,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;IAC1B,yCAAyC;IACzC,OAAO,EAAE,YAAY,CAAC;IACtB;;;;OAIG;IACH,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,UAAU,CAAC,KAAK;QACnC,SAAS,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;QAC5B,SAAS,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;KAC7B,CAAC;CACH,CAAC;AAqBF;;;;;;;;;;;;GAYG;AACH,wBAAgB,UAAU,CAAC,QAAQ,EAAE,IAAI,CAAC,cAAc,CAAC,GAAG,IAAI,CAAC,cAAc,CAAC,CA0I/E"}
|
||||
178
node_modules/@noble/curves/abstract/montgomery.js
generated
vendored
Normal file
178
node_modules/@noble/curves/abstract/montgomery.js
generated
vendored
Normal file
@@ -0,0 +1,178 @@
|
||||
/**
|
||||
* Montgomery curve methods. It's not really whole montgomery curve,
|
||||
* just bunch of very specific methods for X25519 / X448 from
|
||||
* [RFC 7748](https://www.rfc-editor.org/rfc/rfc7748)
|
||||
* @module
|
||||
*/
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
import { abytes, aInRange, bytesToNumberLE, copyBytes, numberToBytesLE, randomBytes, validateObject, } from "../utils.js";
|
||||
import { createKeygen } from "./curve.js";
|
||||
import { mod } from "./modular.js";
|
||||
const _0n = BigInt(0);
|
||||
const _1n = BigInt(1);
|
||||
const _2n = BigInt(2);
|
||||
function validateOpts(curve) {
|
||||
// Validate constructor config eagerly, but do not call user-provided hooks here:
|
||||
// `randomBytes` may be transcript-backed or otherwise contextual. Runtime type checks are
|
||||
// enough to fail fast on malformed configs without consuming user state.
|
||||
validateObject(curve, {
|
||||
P: 'bigint',
|
||||
type: 'string',
|
||||
adjustScalarBytes: 'function',
|
||||
powPminus2: 'function',
|
||||
}, {
|
||||
randomBytes: 'function',
|
||||
});
|
||||
return Object.freeze({ ...curve });
|
||||
}
|
||||
/**
|
||||
* @param curveDef - Montgomery curve definition.
|
||||
* @returns ECDH helper namespace.
|
||||
* @throws If the curve definition or derived shared point is invalid. {@link Error}
|
||||
* @example
|
||||
* Perform one X25519 key exchange through the generic Montgomery helper.
|
||||
*
|
||||
* ```ts
|
||||
* import { x25519 } from '@noble/curves/ed25519.js';
|
||||
* const alice = x25519.keygen();
|
||||
* const shared = x25519.getSharedSecret(alice.secretKey, alice.publicKey);
|
||||
* ```
|
||||
*/
|
||||
export function montgomery(curveDef) {
|
||||
const CURVE = validateOpts(curveDef);
|
||||
const { P, type, adjustScalarBytes, powPminus2, randomBytes: rand } = CURVE;
|
||||
const is25519 = type === 'x25519';
|
||||
if (!is25519 && type !== 'x448')
|
||||
throw new Error('invalid type');
|
||||
const randomBytes_ = rand === undefined ? randomBytes : rand;
|
||||
const montgomeryBits = is25519 ? 255 : 448;
|
||||
const fieldLen = is25519 ? 32 : 56;
|
||||
const Gu = is25519 ? BigInt(9) : BigInt(5);
|
||||
// RFC 7748 #5:
|
||||
// The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519 and
|
||||
// (156326 - 2) / 4 = 39081 for curve448/X448
|
||||
// const a = is25519 ? 486662n : 156326n;
|
||||
const a24 = is25519 ? BigInt(121665) : BigInt(39081);
|
||||
// RFC: x25519 "the resulting integer is of the form 2^254 plus
|
||||
// eight times a value between 0 and 2^251 - 1 (inclusive)"
|
||||
// x448: "2^447 plus four times a value between 0 and 2^445 - 1 (inclusive)"
|
||||
const minScalar = is25519 ? _2n ** BigInt(254) : _2n ** BigInt(447);
|
||||
const maxAdded = is25519
|
||||
? BigInt(8) * _2n ** BigInt(251) - _1n
|
||||
: BigInt(4) * _2n ** BigInt(445) - _1n;
|
||||
const maxScalar = minScalar + maxAdded + _1n; // (inclusive)
|
||||
const modP = (n) => mod(n, P);
|
||||
const GuBytes = encodeU(Gu);
|
||||
function encodeU(u) {
|
||||
return numberToBytesLE(modP(u), fieldLen);
|
||||
}
|
||||
function decodeU(u) {
|
||||
const _u = copyBytes(abytes(u, fieldLen, 'uCoordinate'));
|
||||
// RFC: When receiving such an array, implementations of X25519
|
||||
// (but not X448) MUST mask the most significant bit in the final byte.
|
||||
if (is25519)
|
||||
_u[31] &= 127; // 0b0111_1111
|
||||
// RFC: Implementations MUST accept non-canonical values and process them as
|
||||
// if they had been reduced modulo the field prime. The non-canonical
|
||||
// values are 2^255 - 19 through 2^255 - 1 for X25519 and 2^448 - 2^224
|
||||
// - 1 through 2^448 - 1 for X448.
|
||||
return modP(bytesToNumberLE(_u));
|
||||
}
|
||||
function decodeScalar(scalar) {
|
||||
return bytesToNumberLE(adjustScalarBytes(copyBytes(abytes(scalar, fieldLen, 'scalar'))));
|
||||
}
|
||||
function scalarMult(scalar, u) {
|
||||
const pu = montgomeryLadder(decodeU(u), decodeScalar(scalar));
|
||||
// Some public keys are useless, of low-order. Curve author doesn't think
|
||||
// it needs to be validated, but we do it nonetheless.
|
||||
// https://cr.yp.to/ecdh.html#validate
|
||||
if (pu === _0n)
|
||||
throw new Error('invalid private or public key received');
|
||||
return encodeU(pu);
|
||||
}
|
||||
// Computes public key from private. By doing scalar multiplication of base point.
|
||||
function scalarMultBase(scalar) {
|
||||
return scalarMult(scalar, GuBytes);
|
||||
}
|
||||
const getPublicKey = scalarMultBase;
|
||||
const getSharedSecret = scalarMult;
|
||||
// cswap from RFC7748 "example code"
|
||||
function cswap(swap, x_2, x_3) {
|
||||
// dummy = mask(swap) AND (x_2 XOR x_3)
|
||||
// Where mask(swap) is the all-1 or all-0 word of the same length as x_2
|
||||
// and x_3, computed, e.g., as mask(swap) = 0 - swap.
|
||||
const dummy = modP(swap * (x_2 - x_3));
|
||||
x_2 = modP(x_2 - dummy); // x_2 = x_2 XOR dummy
|
||||
x_3 = modP(x_3 + dummy); // x_3 = x_3 XOR dummy
|
||||
return { x_2, x_3 };
|
||||
}
|
||||
/**
|
||||
* Montgomery x-only multiplication ladder for the selected X25519/X448 curve.
|
||||
* @param pointU - decoded Montgomery u coordinate for the selected curve
|
||||
* @param scalar - decoded clamped scalar by which the point is multiplied
|
||||
* @returns resulting Montgomery u coordinate for the selected curve
|
||||
*/
|
||||
function montgomeryLadder(u, scalar) {
|
||||
aInRange('u', u, _0n, P);
|
||||
aInRange('scalar', scalar, minScalar, maxScalar);
|
||||
const k = scalar;
|
||||
const x_1 = u;
|
||||
let x_2 = _1n;
|
||||
let z_2 = _0n;
|
||||
let x_3 = u;
|
||||
let z_3 = _1n;
|
||||
let swap = _0n;
|
||||
for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) {
|
||||
const k_t = (k >> t) & _1n;
|
||||
swap ^= k_t;
|
||||
({ x_2, x_3 } = cswap(swap, x_2, x_3));
|
||||
({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));
|
||||
swap = k_t;
|
||||
const A = x_2 + z_2;
|
||||
const AA = modP(A * A);
|
||||
const B = x_2 - z_2;
|
||||
const BB = modP(B * B);
|
||||
const E = AA - BB;
|
||||
const C = x_3 + z_3;
|
||||
const D = x_3 - z_3;
|
||||
const DA = modP(D * A);
|
||||
const CB = modP(C * B);
|
||||
const dacb = DA + CB;
|
||||
const da_cb = DA - CB;
|
||||
x_3 = modP(dacb * dacb);
|
||||
z_3 = modP(x_1 * modP(da_cb * da_cb));
|
||||
x_2 = modP(AA * BB);
|
||||
z_2 = modP(E * (AA + modP(a24 * E)));
|
||||
}
|
||||
({ x_2, x_3 } = cswap(swap, x_2, x_3));
|
||||
({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));
|
||||
const z2 = powPminus2(z_2); // `Fp.pow(x, P - _2n)` is much slower equivalent
|
||||
return modP(x_2 * z2); // Return x_2 * (z_2^(p - 2))
|
||||
}
|
||||
const lengths = {
|
||||
secretKey: fieldLen,
|
||||
publicKey: fieldLen,
|
||||
seed: fieldLen,
|
||||
};
|
||||
const randomSecretKey = (seed) => {
|
||||
seed = seed === undefined ? randomBytes_(fieldLen) : seed;
|
||||
abytes(seed, lengths.seed, 'seed');
|
||||
// Reuse caller-supplied seed bytes verbatim; clamping is deferred until
|
||||
// decodeScalar(...) when the secret key is actually used.
|
||||
return seed;
|
||||
};
|
||||
const utils = { randomSecretKey };
|
||||
Object.freeze(lengths);
|
||||
Object.freeze(utils);
|
||||
return Object.freeze({
|
||||
keygen: createKeygen(randomSecretKey, getPublicKey),
|
||||
getSharedSecret,
|
||||
getPublicKey,
|
||||
scalarMult,
|
||||
scalarMultBase,
|
||||
utils,
|
||||
GuBytes: GuBytes.slice(),
|
||||
lengths,
|
||||
});
|
||||
}
|
||||
//# sourceMappingURL=montgomery.js.map
|
||||
1
node_modules/@noble/curves/abstract/montgomery.js.map
generated
vendored
Normal file
1
node_modules/@noble/curves/abstract/montgomery.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
355
node_modules/@noble/curves/abstract/oprf.d.ts
generated
vendored
Normal file
355
node_modules/@noble/curves/abstract/oprf.d.ts
generated
vendored
Normal file
@@ -0,0 +1,355 @@
|
||||
/**
|
||||
* RFC 9497: Oblivious Pseudorandom Functions (OPRFs) Using Prime-Order Groups.
|
||||
* https://www.rfc-editor.org/rfc/rfc9497
|
||||
*
|
||||
|
||||
OPRF allows to interactively create an `Output = PRF(Input, serverSecretKey)`:
|
||||
|
||||
- Server cannot calculate Output by itself: it doesn't know Input
|
||||
- Client cannot calculate Output by itself: it doesn't know server secretKey
|
||||
- An attacker interception the communication can't restore Input/Output/serverSecretKey and can't
|
||||
link Input to some value.
|
||||
|
||||
## Issues
|
||||
|
||||
- Low-entropy inputs (e.g. password '123') enable brute-forced dictionary attacks by the server
|
||||
(solveable by domain separation in POPRF)
|
||||
- High-level protocol needs to be constructed on top, because OPRF is low-level
|
||||
|
||||
## Use cases
|
||||
|
||||
1. **Password-Authenticated Key Exchange (PAKE):** Enables secure password login (e.g., OPAQUE)
|
||||
without revealing the password to the server.
|
||||
2. **Private Set Intersection (PSI):** Allows two parties to compute the intersection of their
|
||||
private sets without revealing non-intersecting elements.
|
||||
3. **Anonymous Credential Systems:** Supports issuance of anonymous, unlinkable credentials
|
||||
(e.g., Privacy Pass) using blind OPRF evaluation.
|
||||
4. **Private Information Retrieval (PIR):** Helps users query databases without revealing which
|
||||
item they accessed.
|
||||
5. **Encrypted Search / Secure Indexing:** Enables keyword search over encrypted data while keeping
|
||||
queries private.
|
||||
6. **Spam Prevention and Rate-Limiting:** Issues anonymous tokens to prevent abuse
|
||||
(e.g., CAPTCHA bypass) without compromising user privacy.
|
||||
|
||||
## Modes
|
||||
|
||||
- OPRF: simple mode, client doesn't need to know server public key
|
||||
- VOPRF: verifiable mode. It lets the client verify that the server used the
|
||||
secret key corresponding to a known public key
|
||||
- POPRF: partially oblivious mode, VOPRF + domain separation
|
||||
|
||||
There is also non-interactive mode (Evaluate), which creates Output
|
||||
non-interactively with knowledge of the secret key.
|
||||
|
||||
Flow:
|
||||
- (once) Server generates secret and public keys, distributes public keys to clients
|
||||
- deterministically: `deriveKeyPair` or just random: `generateKeyPair`
|
||||
- Client blinds input: `blind(secretInput)`
|
||||
- Server evaluates blinded input: `blindEvaluate` generated by client, sends result to client
|
||||
- Client creates output using result of evaluation via 'finalize'
|
||||
|
||||
* @module
|
||||
*/
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
import { randomBytes, type TArg, type TRet } from '../utils.ts';
|
||||
import { type CurvePoint, type CurvePointCons } from './curve.ts';
|
||||
import { type H2CDSTOpts } from './hash-to-curve.ts';
|
||||
/** Serialized group element passed between OPRF participants. */
|
||||
export type PointBytes = Uint8Array;
|
||||
/** Serialized scalar used for blinds and server secret keys. */
|
||||
export type ScalarBytes = Uint8Array;
|
||||
/** Arbitrary byte input or output used by the OPRF protocol. */
|
||||
export type Bytes = Uint8Array;
|
||||
/** Cryptographically secure byte generator used for blinds and proofs. */
|
||||
export type RNG = typeof randomBytes;
|
||||
/** Curve and hash hooks required to instantiate one OPRF ciphersuite. */
|
||||
export type OPRFOpts<P extends CurvePoint<any, P>> = {
|
||||
/** Human-readable suite identifier used for domain separation. */
|
||||
name: string;
|
||||
/**
|
||||
* Prime-order group used by the OPRF construction.
|
||||
* Kept generic because the suite returns serialized points.
|
||||
*/
|
||||
Point: CurvePointCons<P>;
|
||||
/**
|
||||
* Hash function used for transcripts, proofs, and outputs.
|
||||
* @param msg - Message bytes to hash.
|
||||
* @returns Digest bytes.
|
||||
*/
|
||||
hash(msg: TArg<Bytes>): TRet<Bytes>;
|
||||
/**
|
||||
* Hash arbitrary bytes into one scalar in the suite order.
|
||||
* @param msg - Message bytes to map.
|
||||
* @param options - Hash-to-field domain-separation options. See {@link H2CDSTOpts}.
|
||||
* Implementations MUST treat `msg` and `options` as read-only.
|
||||
* @returns Scalar in the suite order.
|
||||
*/
|
||||
hashToScalar(msg: TArg<Uint8Array>, options: TArg<H2CDSTOpts>): bigint;
|
||||
/**
|
||||
* Hash arbitrary bytes directly onto one curve point.
|
||||
* @param msg - Message bytes to map.
|
||||
* @param options - Hash-to-curve domain-separation options. See {@link H2CDSTOpts}.
|
||||
* Implementations MUST treat `msg` and `options` as read-only.
|
||||
* @returns Point on the suite curve.
|
||||
*/
|
||||
hashToGroup(msg: TArg<Uint8Array>, options: TArg<H2CDSTOpts>): P;
|
||||
};
|
||||
/** Server keypair for one OPRF suite. */
|
||||
export type OPRFKeys = {
|
||||
/** Secret scalar kept by the server. */
|
||||
secretKey: TRet<ScalarBytes>;
|
||||
/** Public point distributed to clients in verifiable modes. */
|
||||
publicKey: TRet<PointBytes>;
|
||||
};
|
||||
/** Result of the client-side blind step. */
|
||||
export type OPRFBlind = {
|
||||
/** Secret blind scalar that the client keeps locally. */
|
||||
blind: TRet<ScalarBytes>;
|
||||
/** Blinded group element sent to the server. */
|
||||
blinded: TRet<PointBytes>;
|
||||
};
|
||||
/** Server response for one verifiable OPRF evaluation. */
|
||||
export type OPRFBlindEval = {
|
||||
/** Evaluated group element returned by the server. */
|
||||
evaluated: TRet<PointBytes>;
|
||||
/** DLEQ proof binding the evaluation to the server public key. */
|
||||
proof: TRet<Bytes>;
|
||||
};
|
||||
/** Server response for a batch of verifiable OPRF evaluations. */
|
||||
export type OPRFBlindEvalBatch = {
|
||||
/** Evaluated group elements returned for each blinded input. */
|
||||
evaluated: TRet<PointBytes[]>;
|
||||
/** Batch proof covering all evaluated elements. */
|
||||
proof: TRet<Bytes>;
|
||||
};
|
||||
/** One finalized transcript item used by batch verification helpers. */
|
||||
export type OPRFFinalizeItem = {
|
||||
/** Original client input. */
|
||||
input: Bytes;
|
||||
/** Secret blind scalar used for the input. */
|
||||
blind: ScalarBytes;
|
||||
/** Evaluated point returned by the server. */
|
||||
evaluated: PointBytes;
|
||||
/** Blinded point originally sent to the server. */
|
||||
blinded: PointBytes;
|
||||
};
|
||||
/** Result of the POPRF client-side blind step with the tweaked server public key. */
|
||||
export type OPRFBlindTweaked = OPRFBlind & {
|
||||
tweakedKey: TRet<PointBytes>;
|
||||
};
|
||||
/**
|
||||
* Represents a full OPRF ciphersuite implementation according to RFC 9497.
|
||||
* This object bundles the three protocol variants (OPRF, VOPRF, POPRF) for a specific
|
||||
* prime-order group and hash function combination.
|
||||
*
|
||||
* @see https://www.rfc-editor.org/rfc/rfc9497.html
|
||||
*/
|
||||
export type OPRF = {
|
||||
/**
|
||||
* The unique identifier for the ciphersuite, e.g., "ristretto255-SHA512".
|
||||
* This name is used for domain separation to prevent cross-protocol attacks.
|
||||
*/
|
||||
readonly name: string;
|
||||
/**
|
||||
* The base Oblivious Pseudorandom Function (OPRF) mode (mode 0x00).
|
||||
* This is a two-party protocol between a client and a server to compute F(k, x)
|
||||
* where 'k' is the server's key and 'x' is the client's input.
|
||||
*
|
||||
* The client learns the output F(k, x) but nothing about 'k'.
|
||||
* The server learns nothing about 'x' or F(k, x).
|
||||
* This mode is NOT verifiable; the client cannot prove the server used a specific key.
|
||||
*/
|
||||
readonly oprf: {
|
||||
/**
|
||||
* (Server-side) Generates a new random private/public key pair for the server.
|
||||
* @returns A new key pair.
|
||||
*/
|
||||
generateKeyPair(): TRet<OPRFKeys>;
|
||||
/**
|
||||
* (Server-side) Deterministically derives a private/public key pair from a seed.
|
||||
* @param seed - A 32-byte cryptographically secure random seed.
|
||||
* @param keyInfo - An optional byte string for domain separation.
|
||||
* @returns The derived key pair.
|
||||
*/
|
||||
deriveKeyPair(seed: TArg<Bytes>, keyInfo: TArg<Bytes>): TRet<OPRFKeys>;
|
||||
/**
|
||||
* (Client-side) The first step of the protocol. The client blinds its private input.
|
||||
* @param input - The client's private input bytes.
|
||||
* @param rng - An optional cryptographically secure random number generator.
|
||||
* @returns An object containing the `blind` scalar (which the client MUST keep secret)
|
||||
* and the `blinded` element (which the client sends to the server).
|
||||
*/
|
||||
blind(input: TArg<Bytes>, rng?: RNG): TRet<OPRFBlind>;
|
||||
/**
|
||||
* (Server-side) The second step. The server evaluates the client's blinded element
|
||||
* using its secret key.
|
||||
* @param secretKey - The server's private key.
|
||||
* @param blinded - The blinded group element received from the client.
|
||||
* @returns The evaluated group element, to be sent back to the client.
|
||||
*/
|
||||
blindEvaluate(secretKey: TArg<ScalarBytes>, blinded: TArg<PointBytes>): TRet<PointBytes>;
|
||||
/**
|
||||
* (Client-side) The final step. The client unblinds the server's response to
|
||||
* compute the final OPRF output.
|
||||
* @param input - The original private input from the `blind` step.
|
||||
* @param blind - The secret scalar from the `blind` step.
|
||||
* @param evaluated - The evaluated group element received from the server.
|
||||
* @returns The final OPRF output, `Hash(len(input)||input||len(unblinded)||unblinded||"Finalize")`.
|
||||
*/
|
||||
finalize(input: TArg<Bytes>, blind: TArg<ScalarBytes>, evaluated: TArg<PointBytes>): TRet<Bytes>;
|
||||
};
|
||||
/**
|
||||
* The Verifiable Oblivious Pseudorandom Function (VOPRF) mode (mode 0x01).
|
||||
* This mode extends the base OPRF by providing a proof that the server used the
|
||||
* secret key corresponding to its known public key.
|
||||
*/
|
||||
readonly voprf: {
|
||||
/** (Server-side) Generates a key pair for the VOPRF mode. */
|
||||
generateKeyPair(): TRet<OPRFKeys>;
|
||||
/** (Server-side) Deterministically derives a key pair for the VOPRF mode. */
|
||||
deriveKeyPair(seed: TArg<Bytes>, keyInfo: TArg<Bytes>): TRet<OPRFKeys>;
|
||||
/** (Client-side) Blinds the client's private input for the VOPRF protocol. */
|
||||
blind(input: TArg<Bytes>, rng?: RNG): TRet<OPRFBlind>;
|
||||
/**
|
||||
* (Server-side) Evaluates the client's blinded element and generates a DLEQ proof
|
||||
* of correctness.
|
||||
* @param secretKey - The server's private key.
|
||||
* @param publicKey - The server's public key, used in proof generation.
|
||||
* @param blinded - The blinded group element received from the client.
|
||||
* @param rng - An optional cryptographically secure random number generator for the proof.
|
||||
* @returns The evaluated element and a proof of correct computation.
|
||||
*/
|
||||
blindEvaluate(secretKey: TArg<ScalarBytes>, publicKey: TArg<PointBytes>, blinded: TArg<PointBytes>, rng?: RNG): TRet<OPRFBlindEval>;
|
||||
/**
|
||||
* (Server-side) An optimized batch version of `blindEvaluate`. It evaluates multiple
|
||||
* blinded elements and produces a single, constant-size proof for the entire batch,
|
||||
* amortizing the cost of proof generation.
|
||||
* @param secretKey - The server's private key.
|
||||
* @param publicKey - The server's public key.
|
||||
* @param blinded - An array of blinded group elements from one or more clients.
|
||||
* @param rng - An optional cryptographically secure random number generator for the proof.
|
||||
* @returns An array of evaluated elements and a single proof for the batch.
|
||||
*/
|
||||
blindEvaluateBatch(secretKey: TArg<ScalarBytes>, publicKey: TArg<PointBytes>, blinded: TArg<PointBytes[]>, rng?: RNG): TRet<OPRFBlindEvalBatch>;
|
||||
/**
|
||||
* (Client-side) The final step. The client verifies the server's proof, and if valid,
|
||||
* unblinds the result to compute the final VOPRF output.
|
||||
* @param input - The original private input.
|
||||
* @param blind - The secret scalar from the `blind` step.
|
||||
* @param evaluated - The evaluated element from the server.
|
||||
* @param blinded - The blinded element sent to the server (needed for proof verification).
|
||||
* @param publicKey - The server's public key against which the proof is verified.
|
||||
* @param proof - The DLEQ proof from the server.
|
||||
* @returns The final VOPRF output.
|
||||
* @throws If the proof verification fails. {@link Error}
|
||||
*/
|
||||
finalize(input: TArg<Bytes>, blind: TArg<ScalarBytes>, evaluated: TArg<PointBytes>, blinded: TArg<PointBytes>, publicKey: TArg<PointBytes>, proof: TArg<Bytes>): TRet<Bytes>;
|
||||
/**
|
||||
* (Client-side) The batch-aware version of `finalize`. It verifies a single batch proof
|
||||
* against a list of corresponding inputs and outputs.
|
||||
* @param items - An array of objects, each containing the parameters for a single finalization.
|
||||
* @param publicKey - The server's public key.
|
||||
* @param proof - The single DLEQ proof for the entire batch.
|
||||
* @returns An array of final VOPRF outputs, one for each item in the input.
|
||||
* @throws If the proof verification fails. {@link Error}
|
||||
*/
|
||||
finalizeBatch(items: TArg<OPRFFinalizeItem[]>, publicKey: TArg<PointBytes>, proof: TArg<Bytes>): TRet<Bytes[]>;
|
||||
};
|
||||
/**
|
||||
* A factory for the Partially Oblivious Pseudorandom Function (POPRF) mode (mode 0x02).
|
||||
* This mode extends VOPRF to include a public `info` parameter, known to both client and
|
||||
* server, which is cryptographically bound to the final output.
|
||||
* This is useful for domain separation at the application level.
|
||||
* @param info - A public byte string to be mixed into the computation.
|
||||
* @returns An object with the POPRF protocol functions.
|
||||
*/
|
||||
readonly poprf: (info: TArg<Bytes>) => {
|
||||
/** (Server-side) Generates a key pair for the POPRF mode. */
|
||||
generateKeyPair(): TRet<OPRFKeys>;
|
||||
/** (Server-side) Deterministically derives a key pair for the POPRF mode. */
|
||||
deriveKeyPair(seed: TArg<Bytes>, keyInfo: TArg<Bytes>): TRet<OPRFKeys>;
|
||||
/**
|
||||
* (Client-side) Blinds the client's private input and computes the "tweaked key".
|
||||
* The tweaked key is a public value derived from the server's public key and the public `info`.
|
||||
* @param input - The client's private input.
|
||||
* @param publicKey - The server's public key.
|
||||
* @param rng - An optional cryptographically secure random number generator.
|
||||
* @returns The `blind`, `blinded` element, and the `tweakedKey`
|
||||
* the client uses for verification.
|
||||
*/
|
||||
blind(input: TArg<Bytes>, publicKey: TArg<PointBytes>, rng?: RNG): TRet<OPRFBlindTweaked>;
|
||||
/**
|
||||
* (Server-side) Evaluates the blinded element using a key derived from
|
||||
* its secret key and the public `info`.
|
||||
* It generates a DLEQ proof against the tweaked key.
|
||||
* @param secretKey - The server's private key.
|
||||
* @param blinded - The blinded element from the client.
|
||||
* @param rng - An optional RNG for the proof.
|
||||
* @returns The evaluated element and a proof of correct computation.
|
||||
*/
|
||||
blindEvaluate(secretKey: TArg<ScalarBytes>, blinded: TArg<PointBytes>, rng?: RNG): TRet<OPRFBlindEval>;
|
||||
/**
|
||||
* (Server-side) A batch-aware version of `blindEvaluate` for the POPRF mode.
|
||||
* @param secretKey - The server's private key.
|
||||
* @param blinded - An array of blinded elements.
|
||||
* @param rng - An optional RNG for the proof.
|
||||
* @returns An array of evaluated elements and a single proof for the batch.
|
||||
*/
|
||||
blindEvaluateBatch(secretKey: TArg<ScalarBytes>, blinded: TArg<PointBytes[]>, rng: RNG): TRet<OPRFBlindEvalBatch>;
|
||||
/**
|
||||
* (Client-side) A batch-aware version of `finalize` for the POPRF mode.
|
||||
* It verifies the proof against the tweaked key.
|
||||
* @param items - An array containing the parameters for each finalization.
|
||||
* @param proof - The single DLEQ proof for the batch.
|
||||
* @param tweakedKey - The tweaked key corresponding to the proof.
|
||||
* All items must share the same `info` and `publicKey`.
|
||||
* @returns An array of final POPRF outputs.
|
||||
* @throws If proof verification fails. {@link Error}
|
||||
*/
|
||||
finalizeBatch(items: TArg<OPRFFinalizeItem[]>, proof: TArg<Bytes>, tweakedKey: TArg<PointBytes>): TRet<Bytes[]>;
|
||||
/**
|
||||
* (Client-side) Finalizes the POPRF protocol. It verifies the server's proof against the
|
||||
* `tweakedKey` computed in the `blind` step. The final output is bound to the public `info`.
|
||||
* @param input - The original private input.
|
||||
* @param blind - The secret scalar.
|
||||
* @param evaluated - The evaluated element from the server.
|
||||
* @param blinded - The blinded element sent to the server.
|
||||
* @param proof - The DLEQ proof from the server.
|
||||
* @param tweakedKey - The public tweaked key computed by the client during the `blind` step.
|
||||
* @returns The final POPRF output.
|
||||
* @throws If proof verification fails. {@link Error}
|
||||
*/
|
||||
finalize(input: TArg<Bytes>, blind: TArg<ScalarBytes>, evaluated: TArg<PointBytes>, blinded: TArg<PointBytes>, proof: TArg<Bytes>, tweakedKey: TArg<PointBytes>): TRet<Bytes>;
|
||||
/**
|
||||
* A non-interactive evaluation function for an entity that knows all inputs.
|
||||
* Computes the final POPRF output directly. Useful for testing or specific applications
|
||||
* where the server needs to compute the output for a known input.
|
||||
* @param secretKey - The server's private key.
|
||||
* @param input - The client's private input.
|
||||
* @returns The final POPRF output.
|
||||
*/
|
||||
evaluate(secretKey: TArg<ScalarBytes>, input: TArg<Bytes>): TRet<Bytes>;
|
||||
};
|
||||
};
|
||||
/**
|
||||
* @param opts - OPRF ciphersuite options. See {@link OPRFOpts}.
|
||||
* @returns OPRF helper namespace.
|
||||
* @example
|
||||
* Instantiate an OPRF suite from curve-specific hashing hooks.
|
||||
*
|
||||
* ```ts
|
||||
* import { createOPRF } from '@noble/curves/abstract/oprf.js';
|
||||
* import { p256, p256_hasher } from '@noble/curves/nist.js';
|
||||
* import { sha256 } from '@noble/hashes/sha2.js';
|
||||
* const oprf = createOPRF({
|
||||
* name: 'P256-SHA256',
|
||||
* Point: p256.Point,
|
||||
* hash: sha256,
|
||||
* hashToGroup: p256_hasher.hashToCurve,
|
||||
* hashToScalar: p256_hasher.hashToScalar,
|
||||
* });
|
||||
* const keys = oprf.oprf.generateKeyPair();
|
||||
* ```
|
||||
*/
|
||||
export declare function createOPRF<P extends CurvePoint<any, P>>(opts: OPRFOpts<P>): TRet<OPRF>;
|
||||
//# sourceMappingURL=oprf.d.ts.map
|
||||
1
node_modules/@noble/curves/abstract/oprf.d.ts.map
generated
vendored
Normal file
1
node_modules/@noble/curves/abstract/oprf.d.ts.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
356
node_modules/@noble/curves/abstract/oprf.js
generated
vendored
Normal file
356
node_modules/@noble/curves/abstract/oprf.js
generated
vendored
Normal file
@@ -0,0 +1,356 @@
|
||||
/**
|
||||
* RFC 9497: Oblivious Pseudorandom Functions (OPRFs) Using Prime-Order Groups.
|
||||
* https://www.rfc-editor.org/rfc/rfc9497
|
||||
*
|
||||
|
||||
OPRF allows to interactively create an `Output = PRF(Input, serverSecretKey)`:
|
||||
|
||||
- Server cannot calculate Output by itself: it doesn't know Input
|
||||
- Client cannot calculate Output by itself: it doesn't know server secretKey
|
||||
- An attacker interception the communication can't restore Input/Output/serverSecretKey and can't
|
||||
link Input to some value.
|
||||
|
||||
## Issues
|
||||
|
||||
- Low-entropy inputs (e.g. password '123') enable brute-forced dictionary attacks by the server
|
||||
(solveable by domain separation in POPRF)
|
||||
- High-level protocol needs to be constructed on top, because OPRF is low-level
|
||||
|
||||
## Use cases
|
||||
|
||||
1. **Password-Authenticated Key Exchange (PAKE):** Enables secure password login (e.g., OPAQUE)
|
||||
without revealing the password to the server.
|
||||
2. **Private Set Intersection (PSI):** Allows two parties to compute the intersection of their
|
||||
private sets without revealing non-intersecting elements.
|
||||
3. **Anonymous Credential Systems:** Supports issuance of anonymous, unlinkable credentials
|
||||
(e.g., Privacy Pass) using blind OPRF evaluation.
|
||||
4. **Private Information Retrieval (PIR):** Helps users query databases without revealing which
|
||||
item they accessed.
|
||||
5. **Encrypted Search / Secure Indexing:** Enables keyword search over encrypted data while keeping
|
||||
queries private.
|
||||
6. **Spam Prevention and Rate-Limiting:** Issues anonymous tokens to prevent abuse
|
||||
(e.g., CAPTCHA bypass) without compromising user privacy.
|
||||
|
||||
## Modes
|
||||
|
||||
- OPRF: simple mode, client doesn't need to know server public key
|
||||
- VOPRF: verifiable mode. It lets the client verify that the server used the
|
||||
secret key corresponding to a known public key
|
||||
- POPRF: partially oblivious mode, VOPRF + domain separation
|
||||
|
||||
There is also non-interactive mode (Evaluate), which creates Output
|
||||
non-interactively with knowledge of the secret key.
|
||||
|
||||
Flow:
|
||||
- (once) Server generates secret and public keys, distributes public keys to clients
|
||||
- deterministically: `deriveKeyPair` or just random: `generateKeyPair`
|
||||
- Client blinds input: `blind(secretInput)`
|
||||
- Server evaluates blinded input: `blindEvaluate` generated by client, sends result to client
|
||||
- Client creates output using result of evaluation via 'finalize'
|
||||
|
||||
* @module
|
||||
*/
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
import { abytes, asciiToBytes, bytesToNumberBE, bytesToNumberLE, concatBytes, numberToBytesBE, randomBytes, validateObject, } from "../utils.js";
|
||||
import { pippenger, validatePointCons } from "./curve.js";
|
||||
import { _DST_scalar } from "./hash-to-curve.js";
|
||||
import { getMinHashLength, mapHashToField } from "./modular.js";
|
||||
const _DST_scalarBytes = /* @__PURE__ */ asciiToBytes(_DST_scalar);
|
||||
// welcome to generic hell
|
||||
/**
|
||||
* @param opts - OPRF ciphersuite options. See {@link OPRFOpts}.
|
||||
* @returns OPRF helper namespace.
|
||||
* @example
|
||||
* Instantiate an OPRF suite from curve-specific hashing hooks.
|
||||
*
|
||||
* ```ts
|
||||
* import { createOPRF } from '@noble/curves/abstract/oprf.js';
|
||||
* import { p256, p256_hasher } from '@noble/curves/nist.js';
|
||||
* import { sha256 } from '@noble/hashes/sha2.js';
|
||||
* const oprf = createOPRF({
|
||||
* name: 'P256-SHA256',
|
||||
* Point: p256.Point,
|
||||
* hash: sha256,
|
||||
* hashToGroup: p256_hasher.hashToCurve,
|
||||
* hashToScalar: p256_hasher.hashToScalar,
|
||||
* });
|
||||
* const keys = oprf.oprf.generateKeyPair();
|
||||
* ```
|
||||
*/
|
||||
export function createOPRF(opts) {
|
||||
validateObject(opts, {
|
||||
name: 'string',
|
||||
hash: 'function',
|
||||
hashToScalar: 'function',
|
||||
hashToGroup: 'function',
|
||||
});
|
||||
// Cheap constructor-surface sanity check only: this verifies the generic static hooks/fields that
|
||||
// OPRF consumes, but it does not certify point semantics like BASE/ZERO correctness.
|
||||
validatePointCons(opts.Point);
|
||||
const { name, Point, hash } = opts;
|
||||
const { Fn } = Point;
|
||||
const hashToGroup = (msg, ctx) => opts.hashToGroup(msg, {
|
||||
DST: concatBytes(asciiToBytes('HashToGroup-'), ctx),
|
||||
});
|
||||
const hashToScalarPrefixed = (msg, ctx) => opts.hashToScalar(msg, { DST: concatBytes(_DST_scalarBytes, ctx) });
|
||||
const randomScalar = (rng = randomBytes) => {
|
||||
// RFC 9497 §2.1 defines RandomScalar as nonzero; blind inversion and generated public keys
|
||||
// both rely on keeping this helper in the `1..n-1` range.
|
||||
const t = mapHashToField(rng(getMinHashLength(Fn.ORDER)), Fn.ORDER, Fn.isLE);
|
||||
// We cannot use Fn.fromBytes here, because field
|
||||
// can have different number of bytes (like ed448)
|
||||
return Fn.isLE ? bytesToNumberLE(t) : bytesToNumberBE(t);
|
||||
};
|
||||
const msm = (points, scalars) => pippenger(Point, points, scalars);
|
||||
const getCtx = (mode) => concatBytes(asciiToBytes('OPRFV1-'), new Uint8Array([mode]), asciiToBytes('-' + name));
|
||||
const ctxOPRF = getCtx(0x00);
|
||||
const ctxVOPRF = getCtx(0x01);
|
||||
const ctxPOPRF = getCtx(0x02);
|
||||
function encode(...args) {
|
||||
const res = [];
|
||||
for (const a of args) {
|
||||
if (typeof a === 'number')
|
||||
res.push(numberToBytesBE(a, 2));
|
||||
else if (typeof a === 'string')
|
||||
res.push(asciiToBytes(a));
|
||||
else {
|
||||
abytes(a);
|
||||
res.push(numberToBytesBE(a.length, 2), a);
|
||||
}
|
||||
}
|
||||
// No wipe here, since will modify actual bytes
|
||||
return concatBytes(...res);
|
||||
}
|
||||
const inputBytes = (title, bytes) => {
|
||||
abytes(bytes, undefined, title);
|
||||
// RFC 9497 §1.2 limits PrivateInput/PublicInput to 2^16 - 1 bytes because these values are
|
||||
// length-prefixed with two bytes before use throughout the protocol.
|
||||
if (bytes.length > 0xffff)
|
||||
throw new Error(`"${title}" expected Uint8Array of length <= 65535, got length=${bytes.length}`);
|
||||
return bytes;
|
||||
};
|
||||
const hashInput = (...bytes) => hash(encode(...bytes, 'Finalize'));
|
||||
function getTranscripts(B, C, D, ctx) {
|
||||
const Bm = B.toBytes();
|
||||
const seed = hash(encode(Bm, concatBytes(asciiToBytes('Seed-'), ctx)));
|
||||
const res = [];
|
||||
for (let i = 0; i < C.length; i++) {
|
||||
const Ci = C[i].toBytes();
|
||||
const Di = D[i].toBytes();
|
||||
const di = hashToScalarPrefixed(encode(seed, i, Ci, Di, 'Composite'), ctx);
|
||||
res.push(di);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
function computeComposites(B, C, D, ctx) {
|
||||
const T = getTranscripts(B, C, D, ctx);
|
||||
const M = msm(C, T);
|
||||
const Z = msm(D, T);
|
||||
return { M, Z };
|
||||
}
|
||||
function computeCompositesFast(k, B, C, D, ctx) {
|
||||
const T = getTranscripts(B, C, D, ctx);
|
||||
const M = msm(C, T);
|
||||
// RFC 9497 §2.2.1 ComputeCompositesFast derives weights from both C and D in getTranscripts(),
|
||||
// then uses the server shortcut Z = k * M instead of a second MSM over D.
|
||||
const Z = M.multiply(k);
|
||||
return { M, Z };
|
||||
}
|
||||
function challengeTranscript(B, M, Z, t2, t3, ctx) {
|
||||
const [Bm, a0, a1, a2, a3] = [B, M, Z, t2, t3].map((i) => i.toBytes());
|
||||
return hashToScalarPrefixed(encode(Bm, a0, a1, a2, a3, 'Challenge'), ctx);
|
||||
}
|
||||
function generateProof(ctx, k, B, C, D, rng) {
|
||||
const { M, Z } = computeCompositesFast(k, B, C, D, ctx);
|
||||
const r = randomScalar(rng);
|
||||
const t2 = Point.BASE.multiply(r);
|
||||
const t3 = M.multiply(r);
|
||||
const c = challengeTranscript(B, M, Z, t2, t3, ctx);
|
||||
const s = Fn.sub(r, Fn.mul(c, k)); // r - c*k
|
||||
return concatBytes(...[c, s].map((i) => Fn.toBytes(i)));
|
||||
}
|
||||
function verifyProof(ctx, B, C, D, proof) {
|
||||
abytes(proof, 2 * Fn.BYTES);
|
||||
const { M, Z } = computeComposites(B, C, D, ctx);
|
||||
const [c, s] = [proof.subarray(0, Fn.BYTES), proof.subarray(Fn.BYTES)].map((f) => Fn.fromBytes(f));
|
||||
const t2 = Point.BASE.multiply(s).add(B.multiply(c)); // s*G + c*B
|
||||
const t3 = M.multiply(s).add(Z.multiply(c)); // s*M + c*Z
|
||||
const expectedC = challengeTranscript(B, M, Z, t2, t3, ctx);
|
||||
if (!Fn.eql(c, expectedC))
|
||||
throw new Error('proof verification failed');
|
||||
}
|
||||
function generateKeyPair() {
|
||||
const skS = randomScalar();
|
||||
const pkS = Point.BASE.multiply(skS);
|
||||
return { secretKey: Fn.toBytes(skS), publicKey: pkS.toBytes() };
|
||||
}
|
||||
function deriveKeyPair(ctx, seed, info) {
|
||||
// RFC 9497 §3.2.1 defines `seed[32]`; reject other sizes here because this public API already
|
||||
// documents a 32-byte seed instead of generic input keying material.
|
||||
abytes(seed, 32, 'seed');
|
||||
info = inputBytes('keyInfo', info);
|
||||
const dst = concatBytes(asciiToBytes('DeriveKeyPair'), ctx);
|
||||
const msg = concatBytes(seed, encode(info), Uint8Array.of(0));
|
||||
for (let counter = 0; counter <= 255; counter++) {
|
||||
msg[msg.length - 1] = counter;
|
||||
const skS = opts.hashToScalar(msg, { DST: dst });
|
||||
if (Fn.is0(skS))
|
||||
continue; // should not happen
|
||||
return {
|
||||
secretKey: Fn.toBytes(skS),
|
||||
publicKey: Point.BASE.multiply(skS).toBytes(),
|
||||
};
|
||||
}
|
||||
throw new Error('Cannot derive key');
|
||||
}
|
||||
const wirePoint = (label, bytes) => {
|
||||
const point = Point.fromBytes(bytes);
|
||||
// RFC 9497 §3.3 says applications MUST reject group-identity Elements received over the wire
|
||||
// after deserialization, even if the suite decoder itself accepts the identity encoding.
|
||||
if (point.equals(Point.ZERO))
|
||||
throw new Error(label + ' point at infinity');
|
||||
return point;
|
||||
};
|
||||
function blind(ctx, input, rng = randomBytes) {
|
||||
input = inputBytes('input', input);
|
||||
const blind = randomScalar(rng);
|
||||
const inputPoint = hashToGroup(input, ctx);
|
||||
if (inputPoint.equals(Point.ZERO))
|
||||
throw new Error('Input point at infinity');
|
||||
const blinded = inputPoint.multiply(blind);
|
||||
return { blind: Fn.toBytes(blind), blinded: blinded.toBytes() };
|
||||
}
|
||||
function evaluate(ctx, secretKey, input) {
|
||||
input = inputBytes('input', input);
|
||||
const skS = Fn.fromBytes(secretKey);
|
||||
const inputPoint = hashToGroup(input, ctx);
|
||||
if (inputPoint.equals(Point.ZERO))
|
||||
throw new Error('Input point at infinity');
|
||||
const unblinded = inputPoint.multiply(skS).toBytes();
|
||||
return hashInput(input, unblinded);
|
||||
}
|
||||
const oprf = Object.freeze({
|
||||
generateKeyPair,
|
||||
deriveKeyPair: (seed, keyInfo) => deriveKeyPair(ctxOPRF, seed, keyInfo),
|
||||
blind: (input, rng = randomBytes) => blind(ctxOPRF, input, rng),
|
||||
blindEvaluate(secretKey, blindedPoint) {
|
||||
const skS = Fn.fromBytes(secretKey);
|
||||
const elm = wirePoint('blinded', blindedPoint);
|
||||
return elm.multiply(skS).toBytes();
|
||||
},
|
||||
finalize(input, blindBytes, evaluatedBytes) {
|
||||
input = inputBytes('input', input);
|
||||
const blind = Fn.fromBytes(blindBytes);
|
||||
const evalPoint = wirePoint('evaluated', evaluatedBytes);
|
||||
const unblinded = evalPoint.multiply(Fn.inv(blind)).toBytes();
|
||||
return hashInput(input, unblinded);
|
||||
},
|
||||
evaluate: (secretKey, input) => evaluate(ctxOPRF, secretKey, input),
|
||||
});
|
||||
const voprf = Object.freeze({
|
||||
generateKeyPair,
|
||||
deriveKeyPair: (seed, keyInfo) => deriveKeyPair(ctxVOPRF, seed, keyInfo),
|
||||
blind: (input, rng = randomBytes) => blind(ctxVOPRF, input, rng),
|
||||
blindEvaluateBatch(secretKey, publicKey, blinded, rng = randomBytes) {
|
||||
if (!Array.isArray(blinded))
|
||||
throw new Error('expected array');
|
||||
const skS = Fn.fromBytes(secretKey);
|
||||
const pkS = wirePoint('public key', publicKey);
|
||||
const blindedPoints = blinded.map((i) => wirePoint('blinded', i));
|
||||
const evaluated = blindedPoints.map((i) => i.multiply(skS));
|
||||
const proof = generateProof(ctxVOPRF, skS, pkS, blindedPoints, evaluated, rng);
|
||||
return { evaluated: evaluated.map((i) => i.toBytes()), proof };
|
||||
},
|
||||
blindEvaluate(secretKey, publicKey, blinded, rng = randomBytes) {
|
||||
const res = this.blindEvaluateBatch(secretKey, publicKey, [blinded], rng);
|
||||
return { evaluated: res.evaluated[0], proof: res.proof };
|
||||
},
|
||||
finalizeBatch(items, publicKey, proof) {
|
||||
if (!Array.isArray(items))
|
||||
throw new Error('expected array');
|
||||
const pkS = wirePoint('public key', publicKey);
|
||||
const blindedPoints = items.map((i) => wirePoint('blinded', i.blinded));
|
||||
const evalPoints = items.map((i) => wirePoint('evaluated', i.evaluated));
|
||||
verifyProof(ctxVOPRF, pkS, blindedPoints, evalPoints, proof);
|
||||
return items.map((i) => oprf.finalize(i.input, i.blind, i.evaluated));
|
||||
},
|
||||
finalize(input, blind, evaluated, blinded, publicKey, proof) {
|
||||
return this.finalizeBatch([{ input, blind, evaluated, blinded }], publicKey, proof)[0];
|
||||
},
|
||||
evaluate: (secretKey, input) => evaluate(ctxVOPRF, secretKey, input),
|
||||
});
|
||||
// NOTE: info is domain separation
|
||||
const poprf = (info) => {
|
||||
info = inputBytes('info', info);
|
||||
const m = hashToScalarPrefixed(encode('Info', info), ctxPOPRF);
|
||||
const T = Point.BASE.multiply(m);
|
||||
return Object.freeze({
|
||||
generateKeyPair,
|
||||
deriveKeyPair: (seed, keyInfo) => deriveKeyPair(ctxPOPRF, seed, keyInfo),
|
||||
blind(input, publicKey, rng = randomBytes) {
|
||||
input = inputBytes('input', input);
|
||||
const pkS = wirePoint('public key', publicKey);
|
||||
const tweakedKey = T.add(pkS);
|
||||
if (tweakedKey.equals(Point.ZERO))
|
||||
throw new Error('tweakedKey point at infinity');
|
||||
const blind = randomScalar(rng);
|
||||
const inputPoint = hashToGroup(input, ctxPOPRF);
|
||||
if (inputPoint.equals(Point.ZERO))
|
||||
throw new Error('Input point at infinity');
|
||||
const blindedPoint = inputPoint.multiply(blind);
|
||||
return {
|
||||
blind: Fn.toBytes(blind),
|
||||
blinded: blindedPoint.toBytes(),
|
||||
tweakedKey: tweakedKey.toBytes(),
|
||||
};
|
||||
},
|
||||
blindEvaluateBatch(secretKey, blinded, rng = randomBytes) {
|
||||
if (!Array.isArray(blinded))
|
||||
throw new Error('expected array');
|
||||
const skS = Fn.fromBytes(secretKey);
|
||||
const t = Fn.add(skS, m);
|
||||
// "Hence, this error can be a signal for the server to replace its
|
||||
// private key". We throw inside; this should be impossible.
|
||||
const invT = Fn.inv(t);
|
||||
const blindedPoints = blinded.map((i) => wirePoint('blinded', i));
|
||||
const evalPoints = blindedPoints.map((i) => i.multiply(invT));
|
||||
const tweakedKey = Point.BASE.multiply(t);
|
||||
const proof = generateProof(ctxPOPRF, t, tweakedKey, evalPoints, blindedPoints, rng);
|
||||
return { evaluated: evalPoints.map((i) => i.toBytes()), proof };
|
||||
},
|
||||
blindEvaluate(secretKey, blinded, rng = randomBytes) {
|
||||
const res = this.blindEvaluateBatch(secretKey, [blinded], rng);
|
||||
return { evaluated: res.evaluated[0], proof: res.proof };
|
||||
},
|
||||
finalizeBatch(items, proof, tweakedKey) {
|
||||
if (!Array.isArray(items))
|
||||
throw new Error('expected array');
|
||||
const inputs = items.map((i) => inputBytes('input', i.input));
|
||||
const evalPoints = items.map((i) => wirePoint('evaluated', i.evaluated));
|
||||
verifyProof(ctxPOPRF, wirePoint('tweakedKey', tweakedKey), evalPoints, items.map((i) => wirePoint('blinded', i.blinded)), proof);
|
||||
return items.map((i, j) => {
|
||||
const blind = Fn.fromBytes(i.blind);
|
||||
const point = evalPoints[j].multiply(Fn.inv(blind)).toBytes();
|
||||
return hashInput(inputs[j], info, point);
|
||||
});
|
||||
},
|
||||
finalize(input, blind, evaluated, blinded, proof, tweakedKey) {
|
||||
return this.finalizeBatch([{ input, blind, evaluated, blinded }], proof, tweakedKey)[0];
|
||||
},
|
||||
evaluate(secretKey, input) {
|
||||
input = inputBytes('input', input);
|
||||
const skS = Fn.fromBytes(secretKey);
|
||||
const inputPoint = hashToGroup(input, ctxPOPRF);
|
||||
if (inputPoint.equals(Point.ZERO))
|
||||
throw new Error('Input point at infinity');
|
||||
const t = Fn.add(skS, m);
|
||||
const invT = Fn.inv(t);
|
||||
const unblinded = inputPoint.multiply(invT).toBytes();
|
||||
return hashInput(input, info, unblinded);
|
||||
},
|
||||
});
|
||||
};
|
||||
const res = { name, oprf, voprf, poprf, __tests: Object.freeze({ Fn }) };
|
||||
return Object.freeze(res);
|
||||
}
|
||||
//# sourceMappingURL=oprf.js.map
|
||||
1
node_modules/@noble/curves/abstract/oprf.js.map
generated
vendored
Normal file
1
node_modules/@noble/curves/abstract/oprf.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
199
node_modules/@noble/curves/abstract/poseidon.d.ts
generated
vendored
Normal file
199
node_modules/@noble/curves/abstract/poseidon.d.ts
generated
vendored
Normal file
@@ -0,0 +1,199 @@
|
||||
/**
|
||||
* Implements [Poseidon](https://www.poseidon-hash.info) ZK-friendly hash.
|
||||
*
|
||||
* There are many poseidon variants with different constants.
|
||||
* We don't provide them: you should construct them manually.
|
||||
* Check out [micro-starknet](https://github.com/paulmillr/micro-starknet) package for a proper example.
|
||||
* @module
|
||||
*/
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
import { type TArg, type TRet } from '../utils.ts';
|
||||
import { type IField } from './modular.ts';
|
||||
/** Core Poseidon permutation parameters shared by all variants. */
|
||||
export type PoseidonBasicOpts = {
|
||||
/** Prime field used by the permutation. */
|
||||
Fp: IField<bigint>;
|
||||
/** Poseidon width `t = rate + capacity`. */
|
||||
t: number;
|
||||
/** Number of full S-box rounds. */
|
||||
roundsFull: number;
|
||||
/** Number of partial S-box rounds. */
|
||||
roundsPartial: number;
|
||||
/** Whether to use the inverse S-box variant. */
|
||||
isSboxInverse?: boolean;
|
||||
};
|
||||
/** Poseidon settings used by the Grain-LFSR constant generator. */
|
||||
export type PoseidonGrainOpts = PoseidonBasicOpts & {
|
||||
/** S-box power used while generating constants. */
|
||||
sboxPower?: number;
|
||||
};
|
||||
type PoseidonConstants = {
|
||||
mds: bigint[][];
|
||||
roundConstants: bigint[][];
|
||||
};
|
||||
/**
|
||||
* @param opts - Poseidon grain options. See {@link PoseidonGrainOpts}.
|
||||
* @param skipMDS - Number of MDS samples to skip.
|
||||
* @returns Generated constants.
|
||||
* @throws If the generated MDS matrix contains a zero denominator. {@link Error}
|
||||
* @example
|
||||
* Generate Poseidon round constants and an MDS matrix from the Grain LFSR.
|
||||
*
|
||||
* ```ts
|
||||
* import { grainGenConstants } from '@noble/curves/abstract/poseidon.js';
|
||||
* import { Field } from '@noble/curves/abstract/modular.js';
|
||||
* const Fp = Field(17n);
|
||||
* const constants = grainGenConstants({ Fp, t: 2, roundsFull: 8, roundsPartial: 8 });
|
||||
* ```
|
||||
*/
|
||||
export declare function grainGenConstants(opts: TArg<PoseidonGrainOpts>, skipMDS?: number): PoseidonConstants;
|
||||
/** Fully specified Poseidon permutation options with explicit constants. */
|
||||
export type PoseidonOpts = PoseidonBasicOpts & PoseidonConstants & {
|
||||
/** S-box power used by the permutation. */
|
||||
sboxPower?: number;
|
||||
/** Whether to reverse the partial-round S-box index. */
|
||||
reversePartialPowIdx?: boolean;
|
||||
};
|
||||
/**
|
||||
* @param opts - Poseidon options. See {@link PoseidonOpts}.
|
||||
* @returns Normalized poseidon options.
|
||||
* @throws If the Poseidon options, constants, or MDS matrix are invalid. {@link Error}
|
||||
* @example
|
||||
* Validate generated constants before constructing a permutation.
|
||||
*
|
||||
* ```ts
|
||||
* import { grainGenConstants, validateOpts } from '@noble/curves/abstract/poseidon.js';
|
||||
* import { Field } from '@noble/curves/abstract/modular.js';
|
||||
* const Fp = Field(17n);
|
||||
* const constants = grainGenConstants({ Fp, t: 2, roundsFull: 8, roundsPartial: 8 });
|
||||
* const opts = validateOpts({ ...constants, Fp, t: 2, roundsFull: 8, roundsPartial: 8, sboxPower: 3 });
|
||||
* ```
|
||||
*/
|
||||
export declare function validateOpts(opts: TArg<PoseidonOpts>): TRet<Readonly<{
|
||||
rounds: number;
|
||||
sboxFn: (n: bigint) => bigint;
|
||||
roundConstants: bigint[][];
|
||||
mds: bigint[][];
|
||||
Fp: IField<bigint>;
|
||||
t: number;
|
||||
roundsFull: number;
|
||||
roundsPartial: number;
|
||||
sboxPower?: number;
|
||||
reversePartialPowIdx?: boolean;
|
||||
}>>;
|
||||
/**
|
||||
* @param rc - Flattened round constants.
|
||||
* @param t - Poseidon width.
|
||||
* @returns Constants grouped by round.
|
||||
* @throws If the width or flattened constant array is invalid. {@link Error}
|
||||
* @example
|
||||
* Regroup a flat constant list into per-round chunks.
|
||||
*
|
||||
* ```ts
|
||||
* const rounds = splitConstants([1n, 2n, 3n, 4n], 2);
|
||||
* ```
|
||||
*/
|
||||
export declare function splitConstants(rc: bigint[], t: number): bigint[][];
|
||||
/**
|
||||
* Poseidon permutation callable.
|
||||
* @param values - Poseidon state vector. Non-canonical bigints are normalized with `Fp.create(...)`.
|
||||
* @returns Permuted state vector.
|
||||
*/
|
||||
export type PoseidonFn = {
|
||||
(values: bigint[]): bigint[];
|
||||
/** Round constants captured by the permutation instance. */
|
||||
roundConstants: bigint[][];
|
||||
};
|
||||
/** Poseidon NTT-friendly hash. */
|
||||
/**
|
||||
* @param opts - Poseidon options. See {@link PoseidonOpts}.
|
||||
* @returns Poseidon permutation.
|
||||
* @throws If the Poseidon options or state vector are invalid. {@link Error}
|
||||
* @example
|
||||
* Build a Poseidon permutation from validated parameters and constants.
|
||||
*
|
||||
* ```ts
|
||||
* import { grainGenConstants, poseidon } from '@noble/curves/abstract/poseidon.js';
|
||||
* import { Field } from '@noble/curves/abstract/modular.js';
|
||||
* const Fp = Field(17n);
|
||||
* const constants = grainGenConstants({ Fp, t: 2, roundsFull: 8, roundsPartial: 8 });
|
||||
* const hash = poseidon({ ...constants, Fp, t: 2, roundsFull: 8, roundsPartial: 8, sboxPower: 3 });
|
||||
* const state = hash([1n, 2n]);
|
||||
* ```
|
||||
*/
|
||||
export declare function poseidon(opts: TArg<PoseidonOpts>): PoseidonFn;
|
||||
/**
|
||||
* @param Fp - Field implementation.
|
||||
* @param rate - Sponge rate.
|
||||
* @param capacity - Sponge capacity.
|
||||
* @param hash - Poseidon permutation.
|
||||
* @example
|
||||
* Wrap one Poseidon permutation in a sponge interface.
|
||||
*
|
||||
* ```ts
|
||||
* import { PoseidonSponge, grainGenConstants, poseidon } from '@noble/curves/abstract/poseidon.js';
|
||||
* import { Field } from '@noble/curves/abstract/modular.js';
|
||||
* const Fp = Field(17n);
|
||||
* const constants = grainGenConstants({ Fp, t: 2, roundsFull: 8, roundsPartial: 8 });
|
||||
* const hash = poseidon({ ...constants, Fp, t: 2, roundsFull: 8, roundsPartial: 8, sboxPower: 3 });
|
||||
* const sponge = new PoseidonSponge(Fp, 1, 1, hash);
|
||||
* sponge.absorb([1n]);
|
||||
* const out = sponge.squeeze(1);
|
||||
* ```
|
||||
*/
|
||||
export declare class PoseidonSponge {
|
||||
private Fp;
|
||||
readonly rate: number;
|
||||
readonly capacity: number;
|
||||
readonly hash: PoseidonFn;
|
||||
private state;
|
||||
private pos;
|
||||
private isAbsorbing;
|
||||
constructor(Fp: IField<bigint>, rate: number, capacity: number, hash: PoseidonFn);
|
||||
private process;
|
||||
absorb(input: bigint[]): void;
|
||||
squeeze(count: number): bigint[];
|
||||
clean(): void;
|
||||
clone(): PoseidonSponge;
|
||||
}
|
||||
/** Options for the non-standard but commonly used Poseidon sponge wrapper. */
|
||||
export type PoseidonSpongeOpts = Omit<PoseidonOpts, 't'> & {
|
||||
/** Sponge rate. */
|
||||
rate: number;
|
||||
/** Sponge capacity. */
|
||||
capacity: number;
|
||||
};
|
||||
/**
|
||||
* The method is not defined in spec, but nevertheless used often.
|
||||
* Check carefully for compatibility: there are many edge cases, like absorbing an empty array.
|
||||
* We cross-test against:
|
||||
* - {@link https://github.com/ProvableHQ/snarkVM/tree/staging/algorithms | snarkVM algorithms}
|
||||
* - {@link https://github.com/arkworks-rs/crypto-primitives/tree/main | arkworks crypto-primitives}
|
||||
* @param opts - Sponge options. See {@link PoseidonSpongeOpts}.
|
||||
* @returns Factory for sponge instances.
|
||||
* @throws If the sponge dimensions or backing permutation options are invalid. {@link Error}
|
||||
* @example
|
||||
* Use the sponge helper to absorb several field elements and squeeze one digest.
|
||||
*
|
||||
* ```ts
|
||||
* import { grainGenConstants, poseidonSponge } from '@noble/curves/abstract/poseidon.js';
|
||||
* import { Field } from '@noble/curves/abstract/modular.js';
|
||||
* const Fp = Field(17n);
|
||||
* const constants = grainGenConstants({ Fp, t: 2, roundsFull: 8, roundsPartial: 8 });
|
||||
* const makeSponge = poseidonSponge({
|
||||
* ...constants,
|
||||
* Fp,
|
||||
* rate: 1,
|
||||
* capacity: 1,
|
||||
* roundsFull: 8,
|
||||
* roundsPartial: 8,
|
||||
* sboxPower: 3,
|
||||
* });
|
||||
* const sponge = makeSponge();
|
||||
* sponge.absorb([1n]);
|
||||
* const out = sponge.squeeze(1);
|
||||
* ```
|
||||
*/
|
||||
export declare function poseidonSponge(opts: TArg<PoseidonSpongeOpts>): TRet<() => PoseidonSponge>;
|
||||
export {};
|
||||
//# sourceMappingURL=poseidon.d.ts.map
|
||||
1
node_modules/@noble/curves/abstract/poseidon.d.ts.map
generated
vendored
Normal file
1
node_modules/@noble/curves/abstract/poseidon.d.ts.map
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"poseidon.d.ts","sourceRoot":"","sources":["../src/abstract/poseidon.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,sEAAsE;AACtE,OAAO,EAAuC,KAAK,IAAI,EAAE,KAAK,IAAI,EAAE,MAAM,aAAa,CAAC;AACxF,OAAO,EAAwB,KAAK,MAAM,EAAiB,MAAM,cAAc,CAAC;AA2BhF,mEAAmE;AACnE,MAAM,MAAM,iBAAiB,GAAG;IAC9B,2CAA2C;IAC3C,EAAE,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;IACnB,4CAA4C;IAC5C,CAAC,EAAE,MAAM,CAAC;IACV,mCAAmC;IACnC,UAAU,EAAE,MAAM,CAAC;IACnB,sCAAsC;IACtC,aAAa,EAAE,MAAM,CAAC;IACtB,gDAAgD;IAChD,aAAa,CAAC,EAAE,OAAO,CAAC;CACzB,CAAC;AAkEF,mEAAmE;AACnE,MAAM,MAAM,iBAAiB,GAAG,iBAAiB,GAAG;IAClD,mDAAmD;IACnD,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB,CAAC;AAEF,KAAK,iBAAiB,GAAG;IAAE,GAAG,EAAE,MAAM,EAAE,EAAE,CAAC;IAAC,cAAc,EAAE,MAAM,EAAE,EAAE,CAAA;CAAE,CAAC;AAIzE;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,iBAAiB,CAC/B,IAAI,EAAE,IAAI,CAAC,iBAAiB,CAAC,EAC7B,OAAO,GAAE,MAAU,GAClB,iBAAiB,CA4BnB;AAED,4EAA4E;AAC5E,MAAM,MAAM,YAAY,GAAG,iBAAiB,GAC1C,iBAAiB,GAAG;IAClB,2CAA2C;IAC3C,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,wDAAwD;IACxD,oBAAoB,CAAC,EAAE,OAAO,CAAC;CAChC,CAAC;AAEJ;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,IAAI,CAAC,YAAY,CAAC,GAAG,IAAI,CAC1D,QAAQ,CAAC;IACP,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,CAAC,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;IAC9B,cAAc,EAAE,MAAM,EAAE,EAAE,CAAC;IAC3B,GAAG,EAAE,MAAM,EAAE,EAAE,CAAC;IAChB,EAAE,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;IACnB,CAAC,EAAE,MAAM,CAAC;IACV,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,EAAE,MAAM,CAAC;IACtB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,oBAAoB,CAAC,EAAE,OAAO,CAAC;CAChC,CAAC,CACH,CAkEA;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,cAAc,CAAC,EAAE,EAAE,MAAM,EAAE,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,EAAE,CAgBlE;AAED;;;;GAIG;AACH,MAAM,MAAM,UAAU,GAAG;IACvB,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,CAAC;IAC7B,4DAA4D;IAC5D,cAAc,EAAE,MAAM,EAAE,EAAE,CAAC;CAC5B,CAAC;AACF,kCAAkC;AAClC;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,YAAY,CAAC,GAAG,UAAU,CAyC7D;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,qBAAa,cAAc;IACzB,OAAO,CAAC,EAAE,CAAiB;IAC3B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,IAAI,EAAE,UAAU,CAAC;IAC1B,OAAO,CAAC,KAAK,CAAW;IACxB,OAAO,CAAC,GAAG,CAAK;IAChB,OAAO,CAAC,WAAW,CAAQ;gBAEf,EAAE,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,UAAU;IAgBhF,OAAO,CAAC,OAAO;IAKf,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,IAAI;IAgB7B,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE;IAiBhC,KAAK,IAAI,IAAI;IAKb,KAAK,IAAI,cAAc;CAOxB;AAED,8EAA8E;AAC9E,MAAM,MAAM,kBAAkB,GAAG,IAAI,CAAC,YAAY,EAAE,GAAG,CAAC,GAAG;IACzD,mBAAmB;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,uBAAuB;IACvB,QAAQ,EAAE,MAAM,CAAC;CAClB,CAAC;AAaF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,IAAI,CAAC,kBAAkB,CAAC,GAAG,IAAI,CAAC,MAAM,cAAc,CAAC,CAQzF"}
|
||||
463
node_modules/@noble/curves/abstract/poseidon.js
generated
vendored
Normal file
463
node_modules/@noble/curves/abstract/poseidon.js
generated
vendored
Normal file
@@ -0,0 +1,463 @@
|
||||
/**
|
||||
* Implements [Poseidon](https://www.poseidon-hash.info) ZK-friendly hash.
|
||||
*
|
||||
* There are many poseidon variants with different constants.
|
||||
* We don't provide them: you should construct them manually.
|
||||
* Check out [micro-starknet](https://github.com/paulmillr/micro-starknet) package for a proper example.
|
||||
* @module
|
||||
*/
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
import { asafenumber, bitGet, validateObject } from "../utils.js";
|
||||
import { FpInvertBatch, FpPow, validateField } from "./modular.js";
|
||||
// Grain LFSR (Linear-Feedback Shift Register): https://eprint.iacr.org/2009/109.pdf
|
||||
function grainLFSR(state) {
|
||||
// Advances the caller-provided 80-entry state array in place; only the length
|
||||
// is checked here, so entries are assumed to already be bits.
|
||||
let pos = 0;
|
||||
if (state.length !== 80)
|
||||
throw new Error('grainLFRS: wrong state length, should be 80 bits');
|
||||
const getBit = () => {
|
||||
const r = (offset) => state[(pos + offset) % 80];
|
||||
const bit = r(62) ^ r(51) ^ r(38) ^ r(23) ^ r(13) ^ r(0);
|
||||
state[pos] = bit;
|
||||
pos = ++pos % 80;
|
||||
return !!bit;
|
||||
};
|
||||
for (let i = 0; i < 160; i++)
|
||||
getBit();
|
||||
return () => {
|
||||
// https://en.wikipedia.org/wiki/Shrinking_generator
|
||||
while (true) {
|
||||
const b1 = getBit();
|
||||
const b2 = getBit();
|
||||
if (!b1)
|
||||
continue;
|
||||
return b2;
|
||||
}
|
||||
};
|
||||
}
|
||||
function assertValidPosOpts(opts) {
|
||||
const { Fp, roundsFull } = opts;
|
||||
validateField(Fp);
|
||||
validateObject(opts, {
|
||||
t: 'number',
|
||||
roundsFull: 'number',
|
||||
roundsPartial: 'number',
|
||||
}, {
|
||||
isSboxInverse: 'boolean',
|
||||
});
|
||||
for (const k of ['t', 'roundsFull', 'roundsPartial']) {
|
||||
asafenumber(opts[k], k);
|
||||
if (opts[k] < 1)
|
||||
throw new Error('invalid number ' + k);
|
||||
}
|
||||
// Poseidon splits full rounds as `R_F / 2`, then partial rounds, then `R_F / 2` again.
|
||||
if (roundsFull & 1)
|
||||
throw new Error('roundsFull is not even' + roundsFull);
|
||||
}
|
||||
function poseidonGrain(opts) {
|
||||
assertValidPosOpts(opts);
|
||||
const { Fp } = opts;
|
||||
const state = Array(80).fill(1);
|
||||
let pos = 0;
|
||||
const writeBits = (value, bitCount) => {
|
||||
for (let i = bitCount - 1; i >= 0; i--)
|
||||
state[pos++] = Number(bitGet(value, i));
|
||||
};
|
||||
const _0n = BigInt(0);
|
||||
const _1n = BigInt(1);
|
||||
// The Grain seed layout is fixed-width: `Fp.BITS` and `t` use 12 bits,
|
||||
// `roundsFull` and `roundsPartial` use 10, so larger values are truncated here.
|
||||
// This is intentional for compatibility with snarkVM / arkworks PoseidonGrainLFSR:
|
||||
// they write the same fixed-width seed fields without range checks, then still consume
|
||||
// the LFSR using the caller-provided round count for ARK/MDS generation.
|
||||
// Normalizing or rejecting here would diverge from those implementations.
|
||||
writeBits(_1n, 2); // prime field
|
||||
writeBits(opts.isSboxInverse ? _1n : _0n, 4); // b2..b5
|
||||
writeBits(BigInt(Fp.BITS), 12); // b6..b17
|
||||
writeBits(BigInt(opts.t), 12); // b18..b29
|
||||
writeBits(BigInt(opts.roundsFull), 10); // b30..b39
|
||||
writeBits(BigInt(opts.roundsPartial), 10); // b40..b49
|
||||
const getBit = grainLFSR(state);
|
||||
return (count, reject) => {
|
||||
const res = [];
|
||||
for (let i = 0; i < count; i++) {
|
||||
while (true) {
|
||||
let num = _0n;
|
||||
for (let i = 0; i < Fp.BITS; i++) {
|
||||
num <<= _1n;
|
||||
if (getBit())
|
||||
num |= _1n;
|
||||
}
|
||||
if (reject && num >= Fp.ORDER)
|
||||
continue; // rejection sampling
|
||||
res.push(Fp.create(num));
|
||||
break;
|
||||
}
|
||||
}
|
||||
return res;
|
||||
};
|
||||
}
|
||||
// NOTE: this is not standard but used often for constant generation for poseidon
|
||||
// (grain LFRS-like structure)
|
||||
/**
|
||||
* @param opts - Poseidon grain options. See {@link PoseidonGrainOpts}.
|
||||
* @param skipMDS - Number of MDS samples to skip.
|
||||
* @returns Generated constants.
|
||||
* @throws If the generated MDS matrix contains a zero denominator. {@link Error}
|
||||
* @example
|
||||
* Generate Poseidon round constants and an MDS matrix from the Grain LFSR.
|
||||
*
|
||||
* ```ts
|
||||
* import { grainGenConstants } from '@noble/curves/abstract/poseidon.js';
|
||||
* import { Field } from '@noble/curves/abstract/modular.js';
|
||||
* const Fp = Field(17n);
|
||||
* const constants = grainGenConstants({ Fp, t: 2, roundsFull: 8, roundsPartial: 8 });
|
||||
* ```
|
||||
*/
|
||||
export function grainGenConstants(opts, skipMDS = 0) {
|
||||
const { Fp, t, roundsFull, roundsPartial } = opts;
|
||||
// `skipMDS` counts how many candidate matrices to discard before taking one.
|
||||
asafenumber(skipMDS, 'skipMDS');
|
||||
if (skipMDS < 0)
|
||||
throw new Error('invalid number skipMDS');
|
||||
const rounds = roundsFull + roundsPartial;
|
||||
// `sboxPower` is carried in the opts shape for Poseidon compatibility, but
|
||||
// Grain constant generation here only depends on field/size/round counts/inverse flag.
|
||||
const sample = poseidonGrain(opts);
|
||||
const roundConstants = [];
|
||||
for (let r = 0; r < rounds; r++)
|
||||
roundConstants.push(sample(t, true));
|
||||
if (skipMDS > 0)
|
||||
for (let i = 0; i < skipMDS; i++)
|
||||
sample(2 * t, false);
|
||||
const xs = sample(t, false);
|
||||
const ys = sample(t, false);
|
||||
// Construct MDS Matrix M[i][j] = 1 / (xs[i] + ys[j])
|
||||
const mds = [];
|
||||
for (let i = 0; i < t; i++) {
|
||||
const row = [];
|
||||
for (let j = 0; j < t; j++) {
|
||||
const xy = Fp.add(xs[i], ys[j]);
|
||||
if (Fp.is0(xy))
|
||||
throw new Error(`Error generating MDS matrix: xs[${i}] + ys[${j}] resulted in zero.`);
|
||||
row.push(xy);
|
||||
}
|
||||
mds.push(FpInvertBatch(Fp, row));
|
||||
}
|
||||
return { roundConstants, mds };
|
||||
}
|
||||
/**
|
||||
* @param opts - Poseidon options. See {@link PoseidonOpts}.
|
||||
* @returns Normalized poseidon options.
|
||||
* @throws If the Poseidon options, constants, or MDS matrix are invalid. {@link Error}
|
||||
* @example
|
||||
* Validate generated constants before constructing a permutation.
|
||||
*
|
||||
* ```ts
|
||||
* import { grainGenConstants, validateOpts } from '@noble/curves/abstract/poseidon.js';
|
||||
* import { Field } from '@noble/curves/abstract/modular.js';
|
||||
* const Fp = Field(17n);
|
||||
* const constants = grainGenConstants({ Fp, t: 2, roundsFull: 8, roundsPartial: 8 });
|
||||
* const opts = validateOpts({ ...constants, Fp, t: 2, roundsFull: 8, roundsPartial: 8, sboxPower: 3 });
|
||||
* ```
|
||||
*/
|
||||
export function validateOpts(opts) {
|
||||
// This only normalizes shapes and field membership for the provided constants;
|
||||
// it does not prove the stronger MDS/security criteria discussed in the specs.
|
||||
assertValidPosOpts(opts);
|
||||
const { Fp, mds, reversePartialPowIdx: rev, roundConstants: rc } = opts;
|
||||
const { roundsFull, roundsPartial, sboxPower, t } = opts;
|
||||
// MDS is TxT matrix
|
||||
if (!Array.isArray(mds) || mds.length !== t)
|
||||
throw new Error('Poseidon: invalid MDS matrix');
|
||||
const _mds = mds.map((mdsRow) => {
|
||||
if (!Array.isArray(mdsRow) || mdsRow.length !== t)
|
||||
throw new Error('invalid MDS matrix row: ' + mdsRow);
|
||||
return mdsRow.map((i) => {
|
||||
if (typeof i !== 'bigint')
|
||||
throw new Error('invalid MDS matrix bigint: ' + i);
|
||||
// Hardcoded Poseidon MDS matrices often use signed entries like `-1`;
|
||||
// accept bigint representatives here and reduce them into the field.
|
||||
return Fp.create(i);
|
||||
});
|
||||
});
|
||||
if (rev !== undefined && typeof rev !== 'boolean')
|
||||
throw new Error('invalid param reversePartialPowIdx=' + rev);
|
||||
if (roundsFull & 1)
|
||||
throw new Error('roundsFull is not even' + roundsFull);
|
||||
const rounds = roundsFull + roundsPartial;
|
||||
if (!Array.isArray(rc) || rc.length !== rounds)
|
||||
throw new Error('Poseidon: invalid round constants');
|
||||
const roundConstants = rc.map((rc) => {
|
||||
if (!Array.isArray(rc) || rc.length !== t)
|
||||
throw new Error('invalid round constants');
|
||||
return rc.map((i) => {
|
||||
if (typeof i !== 'bigint' || !Fp.isValid(i))
|
||||
throw new Error('invalid round constant');
|
||||
return Fp.create(i);
|
||||
});
|
||||
});
|
||||
// Freeze nested constants so exported handles cannot retune a live permutation instance.
|
||||
const freezeRows = (rows) => Object.freeze(rows.map((row) => Object.freeze(row)));
|
||||
if (!sboxPower || ![3, 5, 7, 17].includes(sboxPower))
|
||||
throw new Error('invalid sboxPower');
|
||||
const _sboxPower = BigInt(sboxPower);
|
||||
let sboxFn = (n) => FpPow(Fp, n, _sboxPower);
|
||||
// Unwrapped sbox power for common cases (195->142μs)
|
||||
if (sboxPower === 3)
|
||||
sboxFn = (n) => Fp.mul(Fp.sqrN(n), n);
|
||||
else if (sboxPower === 5)
|
||||
sboxFn = (n) => Fp.mul(Fp.sqrN(Fp.sqrN(n)), n);
|
||||
return Object.freeze({
|
||||
...opts,
|
||||
rounds,
|
||||
sboxFn,
|
||||
roundConstants: freezeRows(roundConstants),
|
||||
mds: freezeRows(_mds),
|
||||
});
|
||||
}
|
||||
/**
|
||||
* @param rc - Flattened round constants.
|
||||
* @param t - Poseidon width.
|
||||
* @returns Constants grouped by round.
|
||||
* @throws If the width or flattened constant array is invalid. {@link Error}
|
||||
* @example
|
||||
* Regroup a flat constant list into per-round chunks.
|
||||
*
|
||||
* ```ts
|
||||
* const rounds = splitConstants([1n, 2n, 3n, 4n], 2);
|
||||
* ```
|
||||
*/
|
||||
export function splitConstants(rc, t) {
|
||||
asafenumber(t, 't');
|
||||
if (t < 1)
|
||||
throw new Error('poseidonSplitConstants: invalid t');
|
||||
if (!Array.isArray(rc) || rc.length % t)
|
||||
throw new Error('poseidonSplitConstants: invalid rc');
|
||||
const res = [];
|
||||
let tmp = [];
|
||||
for (let i = 0; i < rc.length; i++) {
|
||||
const c = rc[i];
|
||||
if (typeof c !== 'bigint')
|
||||
throw new Error('invalid bigint=' + c);
|
||||
tmp.push(c);
|
||||
if (tmp.length === t) {
|
||||
res.push(tmp);
|
||||
tmp = [];
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
/** Poseidon NTT-friendly hash. */
|
||||
/**
|
||||
* @param opts - Poseidon options. See {@link PoseidonOpts}.
|
||||
* @returns Poseidon permutation.
|
||||
* @throws If the Poseidon options or state vector are invalid. {@link Error}
|
||||
* @example
|
||||
* Build a Poseidon permutation from validated parameters and constants.
|
||||
*
|
||||
* ```ts
|
||||
* import { grainGenConstants, poseidon } from '@noble/curves/abstract/poseidon.js';
|
||||
* import { Field } from '@noble/curves/abstract/modular.js';
|
||||
* const Fp = Field(17n);
|
||||
* const constants = grainGenConstants({ Fp, t: 2, roundsFull: 8, roundsPartial: 8 });
|
||||
* const hash = poseidon({ ...constants, Fp, t: 2, roundsFull: 8, roundsPartial: 8, sboxPower: 3 });
|
||||
* const state = hash([1n, 2n]);
|
||||
* ```
|
||||
*/
|
||||
export function poseidon(opts) {
|
||||
const _opts = validateOpts(opts);
|
||||
const { Fp, mds, roundConstants, rounds: totalRounds, roundsPartial, sboxFn, t } = _opts;
|
||||
const halfRoundsFull = _opts.roundsFull / 2;
|
||||
const partialIdx = _opts.reversePartialPowIdx ? t - 1 : 0;
|
||||
const poseidonRound = (values, isFull, idx) => {
|
||||
values = values.map((i, j) => Fp.add(i, roundConstants[idx][j]));
|
||||
if (isFull)
|
||||
values = values.map((i) => sboxFn(i));
|
||||
else
|
||||
values[partialIdx] = sboxFn(values[partialIdx]);
|
||||
// Matrix multiplication
|
||||
values = mds.map((i) => i.reduce((acc, i, j) => Fp.add(acc, Fp.mulN(i, values[j])), Fp.ZERO));
|
||||
return values;
|
||||
};
|
||||
const poseidonHash = function poseidonHash(values) {
|
||||
if (!Array.isArray(values) || values.length !== t)
|
||||
throw new Error('invalid values, expected array of bigints with length ' + t);
|
||||
// `.map()` skips sparse holes, which would leak `undefined` into round math below.
|
||||
values = values.slice();
|
||||
for (let j = 0; j < values.length; j++) {
|
||||
const i = values[j];
|
||||
if (typeof i !== 'bigint')
|
||||
throw new Error('invalid bigint=' + i);
|
||||
values[j] = Fp.create(i);
|
||||
}
|
||||
let lastRound = 0;
|
||||
// Apply r_f/2 full rounds.
|
||||
for (let i = 0; i < halfRoundsFull; i++)
|
||||
values = poseidonRound(values, true, lastRound++);
|
||||
// Apply r_p partial rounds.
|
||||
for (let i = 0; i < roundsPartial; i++)
|
||||
values = poseidonRound(values, false, lastRound++);
|
||||
// Apply r_f/2 full rounds.
|
||||
for (let i = 0; i < halfRoundsFull; i++)
|
||||
values = poseidonRound(values, true, lastRound++);
|
||||
if (lastRound !== totalRounds)
|
||||
throw new Error('invalid number of rounds');
|
||||
return values;
|
||||
};
|
||||
// For verification in tests
|
||||
Object.defineProperty(poseidonHash, 'roundConstants', {
|
||||
value: roundConstants,
|
||||
enumerable: true,
|
||||
});
|
||||
return poseidonHash;
|
||||
}
|
||||
/**
|
||||
* @param Fp - Field implementation.
|
||||
* @param rate - Sponge rate.
|
||||
* @param capacity - Sponge capacity.
|
||||
* @param hash - Poseidon permutation.
|
||||
* @example
|
||||
* Wrap one Poseidon permutation in a sponge interface.
|
||||
*
|
||||
* ```ts
|
||||
* import { PoseidonSponge, grainGenConstants, poseidon } from '@noble/curves/abstract/poseidon.js';
|
||||
* import { Field } from '@noble/curves/abstract/modular.js';
|
||||
* const Fp = Field(17n);
|
||||
* const constants = grainGenConstants({ Fp, t: 2, roundsFull: 8, roundsPartial: 8 });
|
||||
* const hash = poseidon({ ...constants, Fp, t: 2, roundsFull: 8, roundsPartial: 8, sboxPower: 3 });
|
||||
* const sponge = new PoseidonSponge(Fp, 1, 1, hash);
|
||||
* sponge.absorb([1n]);
|
||||
* const out = sponge.squeeze(1);
|
||||
* ```
|
||||
*/
|
||||
export class PoseidonSponge {
|
||||
Fp;
|
||||
rate;
|
||||
capacity;
|
||||
hash;
|
||||
state; // [...capacity, ...rate]
|
||||
pos = 0;
|
||||
isAbsorbing = true;
|
||||
constructor(Fp, rate, capacity, hash) {
|
||||
const width = spongeShape(rate, capacity);
|
||||
// The direct constructor accepts an arbitrary permutation hook, but callers still
|
||||
// need to preserve the `PoseidonFn.roundConstants` width metadata. Reject width
|
||||
// mismatches here instead of deferring them until the first `process()` call.
|
||||
if (width !== hash.roundConstants[0]?.length)
|
||||
throw new Error(`invalid sponge width: expected ${hash.roundConstants[0]?.length}, got ${width}`);
|
||||
this.Fp = Fp;
|
||||
this.hash = hash;
|
||||
this.rate = rate;
|
||||
this.capacity = capacity;
|
||||
this.state = new Array(width);
|
||||
this.clean();
|
||||
}
|
||||
process() {
|
||||
// The permutation is expected to return an owned state array. If callers inject a custom
|
||||
// hook that reuses external storage, `clean()` will zero that shared buffer too.
|
||||
this.state = this.hash(this.state);
|
||||
}
|
||||
absorb(input) {
|
||||
for (const i of input)
|
||||
if (typeof i !== 'bigint' || !this.Fp.isValid(i))
|
||||
throw new Error('invalid input: ' + i);
|
||||
for (let i = 0; i < input.length;) {
|
||||
if (!this.isAbsorbing || this.pos === this.rate) {
|
||||
this.process();
|
||||
this.pos = 0;
|
||||
this.isAbsorbing = true;
|
||||
}
|
||||
const chunk = Math.min(this.rate - this.pos, input.length - i);
|
||||
for (let j = 0; j < chunk; j++) {
|
||||
const idx = this.capacity + this.pos++;
|
||||
this.state[idx] = this.Fp.add(this.state[idx], input[i++]);
|
||||
}
|
||||
}
|
||||
}
|
||||
squeeze(count) {
|
||||
// Rust oracles use unsigned counts. In JS we keep `squeeze(0) => []` for
|
||||
// compatibility, but still reject negative/fractional counts explicitly.
|
||||
asafenumber(count, 'count');
|
||||
if (count < 0)
|
||||
throw new Error('invalid number count');
|
||||
const res = [];
|
||||
while (res.length < count) {
|
||||
if (this.isAbsorbing || this.pos === this.rate) {
|
||||
this.process();
|
||||
this.pos = 0;
|
||||
this.isAbsorbing = false;
|
||||
}
|
||||
const chunk = Math.min(this.rate - this.pos, count - res.length);
|
||||
for (let i = 0; i < chunk; i++)
|
||||
res.push(this.state[this.capacity + this.pos++]);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
clean() {
|
||||
this.state.fill(this.Fp.ZERO);
|
||||
this.isAbsorbing = true;
|
||||
this.pos = 0;
|
||||
}
|
||||
clone() {
|
||||
const c = new PoseidonSponge(this.Fp, this.rate, this.capacity, this.hash);
|
||||
c.pos = this.pos;
|
||||
c.isAbsorbing = this.isAbsorbing;
|
||||
c.state = [...this.state];
|
||||
return c;
|
||||
}
|
||||
}
|
||||
const spongeShape = (rate, capacity) => {
|
||||
asafenumber(rate, 'rate');
|
||||
asafenumber(capacity, 'capacity');
|
||||
// A sponge with zero rate cannot absorb or squeeze any field elements.
|
||||
if (rate < 1)
|
||||
throw new Error('invalid number rate');
|
||||
// Negative capacity can accidentally keep `rate + capacity` coherent while still
|
||||
// producing a nonsensical sponge shape.
|
||||
if (capacity < 0)
|
||||
throw new Error('invalid number capacity');
|
||||
return rate + capacity;
|
||||
};
|
||||
/**
|
||||
* The method is not defined in spec, but nevertheless used often.
|
||||
* Check carefully for compatibility: there are many edge cases, like absorbing an empty array.
|
||||
* We cross-test against:
|
||||
* - {@link https://github.com/ProvableHQ/snarkVM/tree/staging/algorithms | snarkVM algorithms}
|
||||
* - {@link https://github.com/arkworks-rs/crypto-primitives/tree/main | arkworks crypto-primitives}
|
||||
* @param opts - Sponge options. See {@link PoseidonSpongeOpts}.
|
||||
* @returns Factory for sponge instances.
|
||||
* @throws If the sponge dimensions or backing permutation options are invalid. {@link Error}
|
||||
* @example
|
||||
* Use the sponge helper to absorb several field elements and squeeze one digest.
|
||||
*
|
||||
* ```ts
|
||||
* import { grainGenConstants, poseidonSponge } from '@noble/curves/abstract/poseidon.js';
|
||||
* import { Field } from '@noble/curves/abstract/modular.js';
|
||||
* const Fp = Field(17n);
|
||||
* const constants = grainGenConstants({ Fp, t: 2, roundsFull: 8, roundsPartial: 8 });
|
||||
* const makeSponge = poseidonSponge({
|
||||
* ...constants,
|
||||
* Fp,
|
||||
* rate: 1,
|
||||
* capacity: 1,
|
||||
* roundsFull: 8,
|
||||
* roundsPartial: 8,
|
||||
* sboxPower: 3,
|
||||
* });
|
||||
* const sponge = makeSponge();
|
||||
* sponge.absorb([1n]);
|
||||
* const out = sponge.squeeze(1);
|
||||
* ```
|
||||
*/
|
||||
export function poseidonSponge(opts) {
|
||||
const { rate, capacity } = opts;
|
||||
const t = spongeShape(rate, capacity);
|
||||
// Re-use one hash instance between sponge instances; isolation depends on
|
||||
// poseidon(...) itself staying immutable and not carrying mutable call state.
|
||||
const hash = poseidon({ ...opts, t });
|
||||
const { Fp } = opts;
|
||||
return (() => new PoseidonSponge(Fp, rate, capacity, hash));
|
||||
}
|
||||
//# sourceMappingURL=poseidon.js.map
|
||||
1
node_modules/@noble/curves/abstract/poseidon.js.map
generated
vendored
Normal file
1
node_modules/@noble/curves/abstract/poseidon.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
214
node_modules/@noble/curves/abstract/tower.d.ts
generated
vendored
Normal file
214
node_modules/@noble/curves/abstract/tower.d.ts
generated
vendored
Normal file
@@ -0,0 +1,214 @@
|
||||
/**
|
||||
* Towered extension fields.
|
||||
* Rather than implementing a massive 12th-degree extension directly, it is more efficient
|
||||
* to build it up from smaller extensions: a tower of extensions.
|
||||
*
|
||||
* For BLS12-381, the Fp12 field is implemented as a quadratic (degree two) extension,
|
||||
* on top of a cubic (degree three) extension, on top of a quadratic extension of Fp.
|
||||
*
|
||||
* For more info: "Pairings for beginners" by Costello, section 7.3.
|
||||
* @module
|
||||
*/
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
import { type TArg, type TRet } from '../utils.ts';
|
||||
import * as mod from './modular.ts';
|
||||
import type { WeierstrassPoint, WeierstrassPointCons } from './weierstrass.ts';
|
||||
/** Pair of bigints used for quadratic-extension tuples. */
|
||||
export type BigintTuple = [bigint, bigint];
|
||||
/** Prime-field element. */
|
||||
export type Fp = bigint;
|
||||
/** Quadratic-extension field element `c0 + c1 * u`. */
|
||||
export type Fp2 = {
|
||||
/** Real component. */
|
||||
c0: bigint;
|
||||
/** Imaginary component. */
|
||||
c1: bigint;
|
||||
};
|
||||
/** Six bigints used for sextic-extension tuples. */
|
||||
export type BigintSix = [bigint, bigint, bigint, bigint, bigint, bigint];
|
||||
/** Sextic-extension field element `c0 + c1 * v + c2 * v^2`. */
|
||||
export type Fp6 = {
|
||||
/** Constant coefficient. */
|
||||
c0: Fp2;
|
||||
/** Linear coefficient. */
|
||||
c1: Fp2;
|
||||
/** Quadratic coefficient. */
|
||||
c2: Fp2;
|
||||
};
|
||||
/**
|
||||
* Degree-12 extension field element `c0 + c1 * w`.
|
||||
* Fp₁₂ = Fp₆² over Fp₂³, with Fp₆(w) / (w² - γ) where γ = v.
|
||||
*/
|
||||
export type Fp12 = {
|
||||
/** Constant coefficient. */
|
||||
c0: Fp6;
|
||||
/** Linear coefficient. */
|
||||
c1: Fp6;
|
||||
};
|
||||
/** Twelve bigints used for degree-12 extension tuples. */
|
||||
export type BigintTwelve = [
|
||||
bigint,
|
||||
bigint,
|
||||
bigint,
|
||||
bigint,
|
||||
bigint,
|
||||
bigint,
|
||||
bigint,
|
||||
bigint,
|
||||
bigint,
|
||||
bigint,
|
||||
bigint,
|
||||
bigint
|
||||
];
|
||||
/** BLS-friendly helpers on top of the quadratic extension field. */
|
||||
export type Fp2Bls = mod.IField<Fp2> & {
|
||||
/** Underlying prime field. */
|
||||
Fp: mod.IField<Fp>;
|
||||
/** Apply one Frobenius map. */
|
||||
frobeniusMap(num: Fp2, power: number): Fp2;
|
||||
/** Build one field element from a raw bigint tuple. */
|
||||
fromBigTuple(num: BigintTuple): Fp2;
|
||||
/** Multiply by the curve `b` constant. */
|
||||
mulByB: (num: Fp2) => Fp2;
|
||||
/** Multiply by the quadratic non-residue. */
|
||||
mulByNonresidue: (num: Fp2) => Fp2;
|
||||
/** Split one quadratic element into real and imaginary components. */
|
||||
reim: (num: Fp2) => {
|
||||
re: Fp;
|
||||
im: Fp;
|
||||
};
|
||||
/** Specialized helper used by sextic squaring formulas. */
|
||||
Fp4Square: (a: Fp2, b: Fp2) => {
|
||||
first: Fp2;
|
||||
second: Fp2;
|
||||
};
|
||||
/** Quadratic non-residue used by the extension. */
|
||||
NONRESIDUE: Fp2;
|
||||
};
|
||||
/** BLS-friendly helpers on top of the sextic extension field. */
|
||||
export type Fp6Bls = mod.IField<Fp6> & {
|
||||
/** Underlying quadratic extension field. */
|
||||
Fp2: Fp2Bls;
|
||||
/** Apply one Frobenius map. */
|
||||
frobeniusMap(num: Fp6, power: number): Fp6;
|
||||
/** Build one field element from a raw six-bigint tuple. */
|
||||
fromBigSix: (tuple: BigintSix) => Fp6;
|
||||
/** Multiply by a sparse `(0, b1, 0)` sextic element. */
|
||||
mul1(num: Fp6, b1: Fp2): Fp6;
|
||||
/** Multiply by a sparse `(b0, b1, 0)` sextic element. */
|
||||
mul01(num: Fp6, b0: Fp2, b1: Fp2): Fp6;
|
||||
/** Multiply by one quadratic-extension element. */
|
||||
mulByFp2(lhs: Fp6, rhs: Fp2): Fp6;
|
||||
/** Multiply by the sextic non-residue. */
|
||||
mulByNonresidue: (num: Fp6) => Fp6;
|
||||
};
|
||||
/** BLS-friendly helpers on top of the degree-12 extension field. */
|
||||
export type Fp12Bls = mod.IField<Fp12> & {
|
||||
/** Underlying sextic extension field. */
|
||||
Fp6: Fp6Bls;
|
||||
/** Apply one Frobenius map. */
|
||||
frobeniusMap(num: Fp12, power: number): Fp12;
|
||||
/** Build one field element from a raw twelve-bigint tuple. */
|
||||
fromBigTwelve: (t: BigintTwelve) => Fp12;
|
||||
/** Multiply by a sparse `(o0, o1, 0, 0, o4, 0)` element. */
|
||||
mul014(num: Fp12, o0: Fp2, o1: Fp2, o4: Fp2): Fp12;
|
||||
/** Multiply by a sparse `(o0, 0, 0, o3, o4, 0)` element. */
|
||||
mul034(num: Fp12, o0: Fp2, o3: Fp2, o4: Fp2): Fp12;
|
||||
/** Multiply by one quadratic-extension element. */
|
||||
mulByFp2(lhs: Fp12, rhs: Fp2): Fp12;
|
||||
/** Conjugate one degree-12 element. */
|
||||
conjugate(num: Fp12): Fp12;
|
||||
/** Apply the final exponentiation from pairing arithmetic. */
|
||||
finalExponentiate(num: Fp12): Fp12;
|
||||
/** Apply one cyclotomic square. */
|
||||
_cyclotomicSquare(num: Fp12): Fp12;
|
||||
/** Apply one cyclotomic exponentiation. */
|
||||
_cyclotomicExp(num: Fp12, n: bigint): Fp12;
|
||||
};
|
||||
declare function calcFrobeniusCoefficients<T>(Fp: TArg<mod.IField<T>>, nonResidue: T, modulus: bigint, degree: number, num?: number, divisor?: number): T[][];
|
||||
export declare const __TEST: {
|
||||
calcFrobeniusCoefficients: typeof calcFrobeniusCoefficients;
|
||||
};
|
||||
/**
|
||||
* @param Fp - Base field implementation.
|
||||
* @param Fp2 - Quadratic extension field.
|
||||
* @param base - Twist-specific Frobenius base whose powers yield the `c1` / `c2` constants.
|
||||
* BLS12-381 uses `1 / NONRESIDUE`; BN254 uses `NONRESIDUE`.
|
||||
* @returns Frobenius endomorphism helpers.
|
||||
* @throws If the derived Frobenius constants are inconsistent for the tower. {@link Error}
|
||||
* @example
|
||||
* Build Frobenius endomorphism helpers for a BLS extension tower.
|
||||
*
|
||||
* ```ts
|
||||
* import { psiFrobenius } from '@noble/curves/abstract/tower.js';
|
||||
* import { bls12_381 } from '@noble/curves/bls12-381.js';
|
||||
* const Fp = bls12_381.fields.Fp;
|
||||
* const Fp2 = bls12_381.fields.Fp2;
|
||||
* const frob = psiFrobenius(Fp, Fp2, Fp2.div(Fp2.ONE, Fp2.NONRESIDUE));
|
||||
* const point = frob.G2psi(bls12_381.G2.Point, bls12_381.G2.Point.BASE);
|
||||
* ```
|
||||
*/
|
||||
export declare function psiFrobenius(Fp: TArg<mod.IField<Fp>>, Fp2: TArg<Fp2Bls>, base: TArg<Fp2>): {
|
||||
psi: (x: Fp2, y: Fp2) => [Fp2, Fp2];
|
||||
psi2: (x: Fp2, y: Fp2) => [Fp2, Fp2];
|
||||
G2psi: (c: WeierstrassPointCons<Fp2>, P: WeierstrassPoint<Fp2>) => WeierstrassPoint<Fp2>;
|
||||
G2psi2: (c: WeierstrassPointCons<Fp2>, P: WeierstrassPoint<Fp2>) => WeierstrassPoint<Fp2>;
|
||||
PSI_X: Fp2;
|
||||
PSI_Y: Fp2;
|
||||
PSI2_X: Fp2;
|
||||
PSI2_Y: Fp2;
|
||||
};
|
||||
/** Construction options for the BLS-style degree-12 tower. */
|
||||
export type Tower12Opts = {
|
||||
/** Prime-field order. */
|
||||
ORDER: bigint;
|
||||
/** Bit length of the BLS parameter `x`. */
|
||||
X_LEN: number;
|
||||
/** Prime-field non-residue used by the quadratic extension. */
|
||||
NONRESIDUE?: Fp;
|
||||
/** Quadratic-extension non-residue used by the sextic tower. */
|
||||
FP2_NONRESIDUE: BigintTuple;
|
||||
/**
|
||||
* Optional custom quadratic square-root helper.
|
||||
* Receives one quadratic-extension element and returns one square root.
|
||||
*/
|
||||
Fp2sqrt?: (num: Fp2) => Fp2;
|
||||
/**
|
||||
* Multiply one quadratic element by the curve `b` constant.
|
||||
* @param num - Quadratic-extension element to scale.
|
||||
* @returns Product by the curve `b` constant.
|
||||
*/
|
||||
Fp2mulByB: (num: Fp2) => Fp2;
|
||||
/**
|
||||
* Final exponentiation used by pairing arithmetic.
|
||||
* @param num - Degree-12 field element to exponentiate.
|
||||
* @returns Pairing result after final exponentiation.
|
||||
*/
|
||||
Fp12finalExponentiate: (num: Fp12) => Fp12;
|
||||
};
|
||||
/**
|
||||
* @param opts - Tower construction options. See {@link Tower12Opts}.
|
||||
* @returns BLS tower fields.
|
||||
* @throws If the tower options or derived Frobenius helpers are invalid. {@link Error}
|
||||
* @example
|
||||
* Construct the Fp2/Fp6/Fp12 tower used by a pairing-friendly curve.
|
||||
*
|
||||
* ```ts
|
||||
* const fields = tower12({
|
||||
* ORDER: 17n,
|
||||
* X_LEN: 4,
|
||||
* FP2_NONRESIDUE: [1n, 1n],
|
||||
* Fp2mulByB: (num) => num,
|
||||
* Fp12finalExponentiate: (num) => num,
|
||||
* });
|
||||
* const fp12 = fields.Fp12.ONE;
|
||||
* ```
|
||||
*/
|
||||
export declare function tower12(opts: TArg<Tower12Opts>): TRet<{
|
||||
Fp: Readonly<mod.IField<bigint> & Required<Pick<mod.IField<bigint>, 'isOdd'>>>;
|
||||
Fp2: Fp2Bls;
|
||||
Fp6: Fp6Bls;
|
||||
Fp12: Fp12Bls;
|
||||
}>;
|
||||
export {};
|
||||
//# sourceMappingURL=tower.d.ts.map
|
||||
1
node_modules/@noble/curves/abstract/tower.d.ts.map
generated
vendored
Normal file
1
node_modules/@noble/curves/abstract/tower.d.ts.map
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"tower.d.ts","sourceRoot":"","sources":["../src/abstract/tower.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,sEAAsE;AACtE,OAAO,EASL,KAAK,IAAI,EACT,KAAK,IAAI,EACV,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,GAAG,MAAM,cAAc,CAAC;AACpC,OAAO,KAAK,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AAO/E,2DAA2D;AAC3D,MAAM,MAAM,WAAW,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;AAC3C,2BAA2B;AAC3B,MAAM,MAAM,EAAE,GAAG,MAAM,CAAC;AAGxB,uDAAuD;AACvD,MAAM,MAAM,GAAG,GAAG;IAChB,sBAAsB;IACtB,EAAE,EAAE,MAAM,CAAC;IACX,2BAA2B;IAC3B,EAAE,EAAE,MAAM,CAAC;CACZ,CAAC;AACF,oDAAoD;AACpD,MAAM,MAAM,SAAS,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;AACzE,+DAA+D;AAC/D,MAAM,MAAM,GAAG,GAAG;IAChB,4BAA4B;IAC5B,EAAE,EAAE,GAAG,CAAC;IACR,0BAA0B;IAC1B,EAAE,EAAE,GAAG,CAAC;IACR,6BAA6B;IAC7B,EAAE,EAAE,GAAG,CAAC;CACT,CAAC;AACF;;;GAGG;AACH,MAAM,MAAM,IAAI,GAAG;IACjB,4BAA4B;IAC5B,EAAE,EAAE,GAAG,CAAC;IACR,0BAA0B;IAC1B,EAAE,EAAE,GAAG,CAAC;CACT,CAAC;AAEF,0DAA0D;AAC1D,MAAM,MAAM,YAAY,GAAG;IACzB,MAAM;IAAE,MAAM;IAAE,MAAM;IAAE,MAAM;IAAE,MAAM;IAAE,MAAM;IAC9C,MAAM;IAAE,MAAM;IAAE,MAAM;IAAE,MAAM;IAAE,MAAM;IAAE,MAAM;CAC/C,CAAC;AAKF,oEAAoE;AACpE,MAAM,MAAM,MAAM,GAAG,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG;IACrC,8BAA8B;IAC9B,EAAE,EAAE,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;IACnB,+BAA+B;IAC/B,YAAY,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,GAAG,GAAG,CAAC;IAC3C,uDAAuD;IACvD,YAAY,CAAC,GAAG,EAAE,WAAW,GAAG,GAAG,CAAC;IACpC,0CAA0C;IAC1C,MAAM,EAAE,CAAC,GAAG,EAAE,GAAG,KAAK,GAAG,CAAC;IAC1B,6CAA6C;IAC7C,eAAe,EAAE,CAAC,GAAG,EAAE,GAAG,KAAK,GAAG,CAAC;IACnC,sEAAsE;IACtE,IAAI,EAAE,CAAC,GAAG,EAAE,GAAG,KAAK;QAAE,EAAE,EAAE,EAAE,CAAC;QAAC,EAAE,EAAE,EAAE,CAAA;KAAE,CAAC;IACvC,2DAA2D;IAC3D,SAAS,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,GAAG,KAAK;QAAE,KAAK,EAAE,GAAG,CAAC;QAAC,MAAM,EAAE,GAAG,CAAA;KAAE,CAAC;IAC3D,mDAAmD;IACnD,UAAU,EAAE,GAAG,CAAC;CACjB,CAAC;AAEF,iEAAiE;AACjE,MAAM,MAAM,MAAM,GAAG,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG;IACrC,4CAA4C;IAC5C,GAAG,EAAE,MAAM,CAAC;IACZ,+BAA+B;IAC/B,YAAY,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,GAAG,GAAG,CAAC;IAC3C,2DAA2D;IAC3D,UAAU,EAAE,CAAC,KAAK,EAAE,SAAS,KAAK,GAAG,CAAC;IACtC,wDAAwD;IACxD,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,GAAG,GAAG,CAAC;IAC7B,yDAAyD;IACzD,KAAK,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,GAAG,GAAG,CAAC;IACvC,mDAAmD;IACnD,QAAQ,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,GAAG,GAAG,CAAC;IAClC,0CAA0C;IAC1C,eAAe,EAAE,CAAC,GAAG,EAAE,GAAG,KAAK,GAAG,CAAC;CACpC,CAAC;AAEF,oEAAoE;AACpE,MAAM,MAAM,OAAO,GAAG,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG;IACvC,yCAAyC;IACzC,GAAG,EAAE,MAAM,CAAC;IACZ,+BAA+B;IAC/B,YAAY,CAAC,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7C,8DAA8D;IAC9D,aAAa,EAAE,CAAC,CAAC,EAAE,YAAY,KAAK,IAAI,CAAC;IACzC,4DAA4D;IAC5D,MAAM,CAAC,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,GAAG,IAAI,CAAC;IACnD,4DAA4D;IAC5D,MAAM,CAAC,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,GAAG,IAAI,CAAC;IACnD,mDAAmD;IACnD,QAAQ,CAAC,GAAG,EAAE,IAAI,EAAE,GAAG,EAAE,GAAG,GAAG,IAAI,CAAC;IACpC,uCAAuC;IACvC,SAAS,CAAC,GAAG,EAAE,IAAI,GAAG,IAAI,CAAC;IAC3B,8DAA8D;IAC9D,iBAAiB,CAAC,GAAG,EAAE,IAAI,GAAG,IAAI,CAAC;IACnC,mCAAmC;IACnC,iBAAiB,CAAC,GAAG,EAAE,IAAI,GAAG,IAAI,CAAC;IACnC,2CAA2C;IAC3C,cAAc,CAAC,GAAG,EAAE,IAAI,EAAE,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC5C,CAAC;AAEF,iBAAS,yBAAyB,CAAC,CAAC,EAClC,EAAE,EAAE,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EACvB,UAAU,EAAE,CAAC,EACb,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,MAAM,EACd,GAAG,GAAE,MAAU,EACf,OAAO,CAAC,EAAE,MAAM,GACf,CAAC,EAAE,EAAE,CA2BP;AAED,eAAO,MAAM,MAAM,EAAE;IAAE,yBAAyB,EAAE,OAAO,yBAAyB,CAAA;CAG9E,CAAC;AAGL;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,YAAY,CAC1B,EAAE,EAAE,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,EACxB,GAAG,EAAE,IAAI,CAAC,MAAM,CAAC,EACjB,IAAI,EAAE,IAAI,CAAC,GAAG,CAAC,GACd;IACD,GAAG,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,GAAG,KAAK,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;IACpC,IAAI,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,GAAG,KAAK,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;IACrC,KAAK,EAAE,CAAC,CAAC,EAAE,oBAAoB,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,gBAAgB,CAAC,GAAG,CAAC,KAAK,gBAAgB,CAAC,GAAG,CAAC,CAAC;IACzF,MAAM,EAAE,CAAC,CAAC,EAAE,oBAAoB,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,gBAAgB,CAAC,GAAG,CAAC,KAAK,gBAAgB,CAAC,GAAG,CAAC,CAAC;IAC1F,KAAK,EAAE,GAAG,CAAC;IACX,KAAK,EAAE,GAAG,CAAC;IACX,MAAM,EAAE,GAAG,CAAC;IACZ,MAAM,EAAE,GAAG,CAAC;CACb,CA8BA;AAED,8DAA8D;AAC9D,MAAM,MAAM,WAAW,GAAG;IACxB,yBAAyB;IACzB,KAAK,EAAE,MAAM,CAAC;IACd,2CAA2C;IAC3C,KAAK,EAAE,MAAM,CAAC;IACd,+DAA+D;IAC/D,UAAU,CAAC,EAAE,EAAE,CAAC;IAChB,gEAAgE;IAChE,cAAc,EAAE,WAAW,CAAC;IAC5B;;;OAGG;IACH,OAAO,CAAC,EAAE,CAAC,GAAG,EAAE,GAAG,KAAK,GAAG,CAAC;IAC5B;;;;OAIG;IACH,SAAS,EAAE,CAAC,GAAG,EAAE,GAAG,KAAK,GAAG,CAAC;IAC7B;;;;OAIG;IACH,qBAAqB,EAAE,CAAC,GAAG,EAAE,IAAI,KAAK,IAAI,CAAC;CAC5C,CAAC;AAyyBF;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,OAAO,CAAC,IAAI,EAAE,IAAI,CAAC,WAAW,CAAC,GAAG,IAAI,CAAC;IACrD,EAAE,EAAE,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC;IAC/E,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,OAAO,CAAC;CACf,CAAC,CA6BD"}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user