feat: Passwordless cross-device authentication

- Arkitektur: docs/auth/passwordless-architecture.md
- Backend: iom/quixzoom-auth-service/ (FastAPI + Redis)
- Webb: quixzoom-market-pages/se/login/ (QR-kod + polling)
- App: iom/quixzoom-app/src/features/auth/ (push + deep links)

Flöde: QR-kod → app-godkännande → webb-inloggad
This commit is contained in:
Bernt
2026-07-07 07:11:50 +00:00
parent 4aa984ad74
commit 6989a98d75
61843 changed files with 5491611 additions and 872231 deletions
+45
View File
@@ -0,0 +1,45 @@
# LandveX Admin v2
## Vad detta är
En **adapter-baserad admin-konsol** som kopplar ihop dina befintliga system — inte ett nytt system.
## Arkitektur
```
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Din │────▶│ Admin v2 │────▶│ aamos- │
│ Webbläsare│ │ Adapter │ │ ledger │
│ │ │ (3456) │ │ (3250) │
└─────────────┘ └─────────────┘ └─────────────┘
┌─────────────┐
│ ouroboros- │
│ finance │
│ (3202) │
└─────────────┘
```
## Starta
```bash
cd /home/bernt/.openclaw/workspace/landvex-admin-v2
npm install
node src/index.mjs
```
## Endpoints
- `GET /health` — Systemstatus
- `GET /api/finance/overview` — Kopplingsstatus
- `GET /api/finance/balance` — Bankbalans (USD)
- `GET /api/finance/ledger?period=2026-06` — Verifikat
## Nästa steg
1. [ ] Koppla CRM (aamos-crm)
2. [ ] Koppla Support (aamos-incidents)
3. [ ] Koppla AI/ML (ai-gateway)
4. [ ] Lägg till autentisering
5. [ ] Deploya till admin.landvex.com
+22
View File
@@ -0,0 +1,22 @@
# LandveX Admin v2 — Nginx config
# Lägg till i /etc/nginx/conf.d/ eller inkludera
server {
listen 80;
server_name admin.landvex.com;
# API — proxy till admin-backend
location /api/ {
proxy_pass http://localhost:3456;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
# Static files — serve UI
location / {
root /home/bernt/.openclaw/workspace/landvex-admin-v2/ui;
index index.html;
try_files $uri $uri/ /index.html;
}
}
+1
View File
@@ -0,0 +1 @@
../@puppeteer/browsers/lib/main-cli.js
+1
View File
@@ -0,0 +1 @@
../mime/cli.js
+1
View File
@@ -0,0 +1 @@
../prebuild-install/bin.js
+1
View File
@@ -0,0 +1 @@
../puppeteer/lib/puppeteer/node/cli.js
Generated Vendored Symlink
+1
View File
@@ -0,0 +1 @@
../rc/cli.js
+1
View File
@@ -0,0 +1 @@
../semver/bin/semver.js
+1944
View File
@@ -0,0 +1,1944 @@
{
"name": "landvex-admin-v2",
"version": "2.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"node_modules/@kurkle/color": {
"version": "0.3.4",
"resolved": "https://registry.npmjs.org/@kurkle/color/-/color-0.3.4.tgz",
"integrity": "sha512-M5UknZPHRu3DEDWoipU6sE8PdkZ6Z/S+v4dD+Ke8IaNlpdSQah50lz1KtcFBa2vsdOnwbbnxJwVM4wty6udA5w==",
"license": "MIT"
},
"node_modules/@noble/ciphers": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-1.3.0.tgz",
"integrity": "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==",
"license": "MIT",
"engines": {
"node": "^14.21.3 || >=16"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@noble/hashes": {
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz",
"integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==",
"license": "MIT",
"engines": {
"node": "^14.21.3 || >=16"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@puppeteer/browsers": {
"version": "3.0.6",
"resolved": "https://registry.npmjs.org/@puppeteer/browsers/-/browsers-3.0.6.tgz",
"integrity": "sha512-B/gKoqlFkzhvzsI6jo9K1cZz9o5ypviVv/xu8CwA4grZzyVwN+XfkT+tu8T1zrauuEXv6VhS2oGX+6NL95WcKA==",
"license": "Apache-2.0",
"dependencies": {
"modern-tar": "^0.7.6",
"yargs": "^18.0.0"
},
"bin": {
"browsers": "lib/main-cli.js"
},
"engines": {
"node": ">=22.12.0"
},
"peerDependencies": {
"proxy-agent": ">=8.0.1",
"yauzl": "^2.10.0 || ^3.4.0"
},
"peerDependenciesMeta": {
"proxy-agent": {
"optional": true
},
"yauzl": {
"optional": true
}
}
},
"node_modules/@swc/helpers": {
"version": "0.5.23",
"resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.23.tgz",
"integrity": "sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw==",
"license": "Apache-2.0",
"dependencies": {
"tslib": "^2.8.0"
}
},
"node_modules/accepts": {
"version": "1.3.8",
"resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz",
"integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==",
"license": "MIT",
"dependencies": {
"mime-types": "~2.1.34",
"negotiator": "0.6.3"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/ansi-regex": {
"version": "6.2.2",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz",
"integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==",
"license": "MIT",
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/chalk/ansi-regex?sponsor=1"
}
},
"node_modules/ansi-styles": {
"version": "6.2.3",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz",
"integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==",
"license": "MIT",
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
}
},
"node_modules/array-flatten": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
"integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==",
"license": "MIT"
},
"node_modules/base64-js": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
"integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT"
},
"node_modules/bl": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz",
"integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==",
"license": "MIT",
"dependencies": {
"buffer": "^5.5.0",
"inherits": "^2.0.4",
"readable-stream": "^3.4.0"
}
},
"node_modules/body-parser": {
"version": "1.20.5",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.5.tgz",
"integrity": "sha512-3grm+/2tUOvu2cjJkvsIxrv/wVpfXQW4PsQHYm7yk4vfpu7Ekl6nEsYBoJUL6qDwZUx8wUhQ8tR2qz+ad9c9OA==",
"license": "MIT",
"dependencies": {
"bytes": "~3.1.2",
"content-type": "~1.0.5",
"debug": "2.6.9",
"depd": "2.0.0",
"destroy": "~1.2.0",
"http-errors": "~2.0.1",
"iconv-lite": "~0.4.24",
"on-finished": "~2.4.1",
"qs": "~6.15.1",
"raw-body": "~2.5.3",
"type-is": "~1.6.18",
"unpipe": "~1.0.0"
},
"engines": {
"node": ">= 0.8",
"npm": "1.2.8000 || >= 1.4.16"
}
},
"node_modules/braces": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz",
"integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==",
"license": "MIT",
"dependencies": {
"fill-range": "^7.1.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/brotli": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/brotli/-/brotli-1.3.3.tgz",
"integrity": "sha512-oTKjJdShmDuGW94SyyaoQvAjf30dZaHnjJ8uAF+u2/vGJkJbJPJAT1gDiOJP5v1Zb6f9KEyW/1HpuaWIXtGHPg==",
"license": "MIT",
"dependencies": {
"base64-js": "^1.1.2"
}
},
"node_modules/browserify-zlib": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/browserify-zlib/-/browserify-zlib-0.2.0.tgz",
"integrity": "sha512-Z942RysHXmJrhqk88FmKBVq/v5tqmSkDz7p54G/MGyjMnCFFnC79XWNbg+Vta8W6Wb2qtSZTSxIGkJrRpCFEiA==",
"license": "MIT",
"dependencies": {
"pako": "~1.0.5"
}
},
"node_modules/buffer": {
"version": "5.7.1",
"resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz",
"integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT",
"dependencies": {
"base64-js": "^1.3.1",
"ieee754": "^1.1.13"
}
},
"node_modules/bytes": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
"integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/call-bind-apply-helpers": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
"integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"function-bind": "^1.1.2"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/call-bound": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz",
"integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.2",
"get-intrinsic": "^1.3.0"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/canvas": {
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/canvas/-/canvas-3.2.3.tgz",
"integrity": "sha512-PzE5nJZPz72YUAfo8oTp0u3fqqY7IzlTubneAihqDYAUcBk7ryeCmBbdJBEdaH0bptSOe2VT2Zwcb3UaFyaSWw==",
"hasInstallScript": true,
"license": "MIT",
"dependencies": {
"node-addon-api": "^7.0.0",
"prebuild-install": "^7.1.3"
},
"engines": {
"node": "^18.12.0 || >= 20.9.0"
}
},
"node_modules/chart.js": {
"version": "4.5.1",
"resolved": "https://registry.npmjs.org/chart.js/-/chart.js-4.5.1.tgz",
"integrity": "sha512-GIjfiT9dbmHRiYi6Nl2yFCq7kkwdkp1W/lp2J99rX0yo9tgJGn3lKQATztIjb5tVtevcBtIdICNWqlq5+E8/Pw==",
"license": "MIT",
"dependencies": {
"@kurkle/color": "^0.3.0"
},
"engines": {
"pnpm": ">=8"
}
},
"node_modules/chartjs-node-canvas": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/chartjs-node-canvas/-/chartjs-node-canvas-5.0.0.tgz",
"integrity": "sha512-+Lc5phRWjb+UxAIiQpKgvOaG6Mw276YQx2jl2BrxoUtI3A4RYTZuGM5Dq+s4ReYmCY42WEPSR6viF3lDSTxpvw==",
"license": "MIT",
"dependencies": {
"canvas": "^3.1.0",
"tslib": "^2.8.1"
},
"peerDependencies": {
"chart.js": "^4.4.8"
}
},
"node_modules/chownr": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz",
"integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==",
"license": "ISC"
},
"node_modules/chromium-bidi": {
"version": "16.0.1",
"resolved": "https://registry.npmjs.org/chromium-bidi/-/chromium-bidi-16.0.1.tgz",
"integrity": "sha512-J63PGu/9PpeCwLIcKYyzWP6yaVL5pxuBc0shlYCYM8BaAkmlwiQboXO1iNbOgSDbVklEyYFfNEcHD8oOAWacUA==",
"license": "Apache-2.0",
"dependencies": {
"mitt": "^3.0.1",
"zod": "^3.24.1"
},
"engines": {
"node": ">=20.19.0 <22.0.0 || >=22.12.0"
},
"peerDependencies": {
"devtools-protocol": "*"
}
},
"node_modules/cliui": {
"version": "9.0.1",
"resolved": "https://registry.npmjs.org/cliui/-/cliui-9.0.1.tgz",
"integrity": "sha512-k7ndgKhwoQveBL+/1tqGJYNz097I7WOvwbmmU2AR5+magtbjPWQTS1C5vzGkBC8Ym8UWRzfKUzUUqFLypY4Q+w==",
"license": "ISC",
"dependencies": {
"string-width": "^7.2.0",
"strip-ansi": "^7.1.0",
"wrap-ansi": "^9.0.0"
},
"engines": {
"node": ">=20"
}
},
"node_modules/clone": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/clone/-/clone-2.1.2.tgz",
"integrity": "sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w==",
"license": "MIT",
"engines": {
"node": ">=0.8"
}
},
"node_modules/content-disposition": {
"version": "0.5.4",
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz",
"integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==",
"license": "MIT",
"dependencies": {
"safe-buffer": "5.2.1"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/content-type": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",
"integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/cookie": {
"version": "0.7.2",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",
"integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/cookie-signature": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.7.tgz",
"integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==",
"license": "MIT"
},
"node_modules/cors": {
"version": "2.8.6",
"resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz",
"integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==",
"license": "MIT",
"dependencies": {
"object-assign": "^4",
"vary": "^1"
},
"engines": {
"node": ">= 0.10"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/debug": {
"version": "2.6.9",
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
"integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
"license": "MIT",
"dependencies": {
"ms": "2.0.0"
}
},
"node_modules/decompress-response": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz",
"integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==",
"license": "MIT",
"dependencies": {
"mimic-response": "^3.1.0"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/deep-extend": {
"version": "0.6.0",
"resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz",
"integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==",
"license": "MIT",
"engines": {
"node": ">=4.0.0"
}
},
"node_modules/depd": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
"integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/destroy": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz",
"integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==",
"license": "MIT",
"engines": {
"node": ">= 0.8",
"npm": "1.2.8000 || >= 1.4.16"
}
},
"node_modules/detect-libc": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
"integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
"license": "Apache-2.0",
"engines": {
"node": ">=8"
}
},
"node_modules/devtools-protocol": {
"version": "0.0.1638949",
"resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1638949.tgz",
"integrity": "sha512-mXwg4Fqnv0WR4iuAT/gYUmctNkjILwXFHyZ+m7Ty1dfr0ezZt2U3gnrrJTfRobJTHoXf+IbuFvFITzLrLFjwJA==",
"license": "BSD-3-Clause"
},
"node_modules/dfa": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/dfa/-/dfa-1.2.0.tgz",
"integrity": "sha512-ED3jP8saaweFTjeGX8HQPjeC1YYyZs98jGNZx6IiBvxW7JG5v492kamAQB3m2wop07CvU/RQmzcKr6bgcC5D/Q==",
"license": "MIT"
},
"node_modules/dunder-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
"integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.1",
"es-errors": "^1.3.0",
"gopd": "^1.2.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/ee-first": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
"integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",
"license": "MIT"
},
"node_modules/emoji-regex": {
"version": "10.6.0",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz",
"integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==",
"license": "MIT"
},
"node_modules/encodeurl": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",
"integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/end-of-stream": {
"version": "1.4.5",
"resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz",
"integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==",
"license": "MIT",
"dependencies": {
"once": "^1.4.0"
}
},
"node_modules/es-define-property": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
"integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/es-errors": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
"integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/es-object-atoms": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz",
"integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/escalade": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
"integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",
"license": "MIT",
"engines": {
"node": ">=6"
}
},
"node_modules/escape-html": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
"integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",
"license": "MIT"
},
"node_modules/etag": {
"version": "1.8.1",
"resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
"integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/expand-template": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz",
"integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==",
"license": "(MIT OR WTFPL)",
"engines": {
"node": ">=6"
}
},
"node_modules/express": {
"version": "4.22.2",
"resolved": "https://registry.npmjs.org/express/-/express-4.22.2.tgz",
"integrity": "sha512-IuL+Elrou2ZvCFHs18/CIzy2Nzvo25nZ1/D2eIZlz7c+QUayAcYoiM2BthCjs+EBHVpjYjcuLDAiCWgeIX3X1Q==",
"license": "MIT",
"dependencies": {
"accepts": "~1.3.8",
"array-flatten": "1.1.1",
"body-parser": "~1.20.5",
"content-disposition": "~0.5.4",
"content-type": "~1.0.4",
"cookie": "~0.7.1",
"cookie-signature": "~1.0.6",
"debug": "2.6.9",
"depd": "2.0.0",
"encodeurl": "~2.0.0",
"escape-html": "~1.0.3",
"etag": "~1.8.1",
"finalhandler": "~1.3.1",
"fresh": "~0.5.2",
"http-errors": "~2.0.0",
"merge-descriptors": "1.0.3",
"methods": "~1.1.2",
"on-finished": "~2.4.1",
"parseurl": "~1.3.3",
"path-to-regexp": "~0.1.12",
"proxy-addr": "~2.0.7",
"qs": "~6.15.1",
"range-parser": "~1.2.1",
"safe-buffer": "5.2.1",
"send": "~0.19.0",
"serve-static": "~1.16.2",
"setprototypeof": "1.2.0",
"statuses": "~2.0.1",
"type-is": "~1.6.18",
"utils-merge": "1.0.1",
"vary": "~1.1.2"
},
"engines": {
"node": ">= 0.10.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/fast-deep-equal": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
"license": "MIT"
},
"node_modules/fill-range": {
"version": "7.1.1",
"resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz",
"integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==",
"license": "MIT",
"dependencies": {
"to-regex-range": "^5.0.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/finalhandler": {
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.2.tgz",
"integrity": "sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg==",
"license": "MIT",
"dependencies": {
"debug": "2.6.9",
"encodeurl": "~2.0.0",
"escape-html": "~1.0.3",
"on-finished": "~2.4.1",
"parseurl": "~1.3.3",
"statuses": "~2.0.2",
"unpipe": "~1.0.0"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/fontkit": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/fontkit/-/fontkit-2.0.4.tgz",
"integrity": "sha512-syetQadaUEDNdxdugga9CpEYVaQIxOwk7GlwZWWZ19//qW4zE5bknOKeMBDYAASwnpaSHKJITRLMF9m1fp3s6g==",
"license": "MIT",
"dependencies": {
"@swc/helpers": "^0.5.12",
"brotli": "^1.3.2",
"clone": "^2.1.2",
"dfa": "^1.2.0",
"fast-deep-equal": "^3.1.3",
"restructure": "^3.0.0",
"tiny-inflate": "^1.0.3",
"unicode-properties": "^1.4.0",
"unicode-trie": "^2.0.0"
}
},
"node_modules/forwarded": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
"integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/fresh": {
"version": "0.5.2",
"resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz",
"integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/fs-constants": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz",
"integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==",
"license": "MIT"
},
"node_modules/function-bind": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
"integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/get-caller-file": {
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",
"integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",
"license": "ISC",
"engines": {
"node": "6.* || 8.* || >= 10.*"
}
},
"node_modules/get-east-asian-width": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.6.0.tgz",
"integrity": "sha512-QRbvDIbx6YklUe6RxeTeleMR0yv3cYH6PsPZHcnVn7xv7zO1BHN8r0XETu8n6Ye3Q+ahtSarc3WgtNWmehIBfA==",
"license": "MIT",
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/get-intrinsic": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
"integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.2",
"es-define-property": "^1.0.1",
"es-errors": "^1.3.0",
"es-object-atoms": "^1.1.1",
"function-bind": "^1.1.2",
"get-proto": "^1.0.1",
"gopd": "^1.2.0",
"has-symbols": "^1.1.0",
"hasown": "^2.0.2",
"math-intrinsics": "^1.1.0"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/get-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
"integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
"license": "MIT",
"dependencies": {
"dunder-proto": "^1.0.1",
"es-object-atoms": "^1.0.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/github-from-package": {
"version": "0.0.0",
"resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz",
"integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==",
"license": "MIT"
},
"node_modules/gopd": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
"integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/has-symbols": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
"integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/hasown": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz",
"integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==",
"license": "MIT",
"dependencies": {
"function-bind": "^1.1.2"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/http-errors": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",
"integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==",
"license": "MIT",
"dependencies": {
"depd": "~2.0.0",
"inherits": "~2.0.4",
"setprototypeof": "~1.2.0",
"statuses": "~2.0.2",
"toidentifier": "~1.0.1"
},
"engines": {
"node": ">= 0.8"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/http-proxy-middleware": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/http-proxy-middleware/-/http-proxy-middleware-4.2.0.tgz",
"integrity": "sha512-ZA+oNOoM+GLoFTIzhkJptVQov73Srep2LBqhF8hG8CIPKO3nam1jonXVQ/QUH8RbwsmaaVz2SOJdzBNBHNtKbw==",
"license": "MIT",
"dependencies": {
"debug": "^4.4.3",
"httpxy": "^0.5.4",
"is-glob": "^4.0.3",
"is-plain-obj": "^4.1.0",
"micromatch": "^4.0.8"
},
"engines": {
"node": "^22.15.0 || ^24.0.0 || >=26.0.0"
}
},
"node_modules/http-proxy-middleware/node_modules/debug": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
"license": "MIT",
"dependencies": {
"ms": "^2.1.3"
},
"engines": {
"node": ">=6.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
}
},
"node_modules/http-proxy-middleware/node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
"node_modules/httpxy": {
"version": "0.5.4",
"resolved": "https://registry.npmjs.org/httpxy/-/httpxy-0.5.4.tgz",
"integrity": "sha512-URfeibL0kTH6VuIxxaJDXWQWEk8fKr+9L8MGv6CuAiNy0fGnoVhWbXBvJR1mkdsvCDUxvhX9cW60k2AhtH5s6w==",
"license": "MIT"
},
"node_modules/iconv-lite": {
"version": "0.4.24",
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz",
"integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==",
"license": "MIT",
"dependencies": {
"safer-buffer": ">= 2.1.2 < 3"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/ieee754": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
"integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "BSD-3-Clause"
},
"node_modules/inherits": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
"license": "ISC"
},
"node_modules/ini": {
"version": "1.3.8",
"resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz",
"integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==",
"license": "ISC"
},
"node_modules/ipaddr.js": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
"integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",
"license": "MIT",
"engines": {
"node": ">= 0.10"
}
},
"node_modules/is-extglob": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",
"integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/is-glob": {
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz",
"integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==",
"license": "MIT",
"dependencies": {
"is-extglob": "^2.1.1"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/is-number": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz",
"integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==",
"license": "MIT",
"engines": {
"node": ">=0.12.0"
}
},
"node_modules/is-plain-obj": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-4.1.0.tgz",
"integrity": "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==",
"license": "MIT",
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/js-md5": {
"version": "0.8.3",
"resolved": "https://registry.npmjs.org/js-md5/-/js-md5-0.8.3.tgz",
"integrity": "sha512-qR0HB5uP6wCuRMrWPTrkMaev7MJZwJuuw4fnwAzRgP4J4/F8RwtodOKpGp4XpqsLBFzzgqIO42efFAyz2Et6KQ==",
"license": "MIT"
},
"node_modules/lilconfig": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.3.tgz",
"integrity": "sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==",
"license": "MIT",
"engines": {
"node": ">=14"
},
"funding": {
"url": "https://github.com/sponsors/antonk52"
}
},
"node_modules/linebreak": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/linebreak/-/linebreak-1.1.0.tgz",
"integrity": "sha512-MHp03UImeVhB7XZtjd0E4n6+3xr5Dq/9xI/5FptGk5FrbDR3zagPa2DS6U8ks/3HjbKWG9Q1M2ufOzxV2qLYSQ==",
"license": "MIT",
"dependencies": {
"base64-js": "0.0.8",
"unicode-trie": "^2.0.0"
}
},
"node_modules/linebreak/node_modules/base64-js": {
"version": "0.0.8",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-0.0.8.tgz",
"integrity": "sha512-3XSA2cR/h/73EzlXXdU6YNycmYI7+kicTxks4eJg2g39biHR84slg2+des+p7iHYhbRg/udIS4TD53WabcOUkw==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/math-intrinsics": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
"integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/media-typer": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
"integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/merge-descriptors": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz",
"integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/methods": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz",
"integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/micromatch": {
"version": "4.0.8",
"resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz",
"integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==",
"license": "MIT",
"dependencies": {
"braces": "^3.0.3",
"picomatch": "^2.3.1"
},
"engines": {
"node": ">=8.6"
}
},
"node_modules/mime": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz",
"integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==",
"license": "MIT",
"bin": {
"mime": "cli.js"
},
"engines": {
"node": ">=4"
}
},
"node_modules/mime-db": {
"version": "1.52.0",
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
"integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/mime-types": {
"version": "2.1.35",
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
"integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
"license": "MIT",
"dependencies": {
"mime-db": "1.52.0"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/mimic-response": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz",
"integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==",
"license": "MIT",
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/minimist": {
"version": "1.2.8",
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
"integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/mitt": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz",
"integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==",
"license": "MIT"
},
"node_modules/mkdirp-classic": {
"version": "0.5.3",
"resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz",
"integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==",
"license": "MIT"
},
"node_modules/modern-tar": {
"version": "0.7.6",
"resolved": "https://registry.npmjs.org/modern-tar/-/modern-tar-0.7.6.tgz",
"integrity": "sha512-sweCIVXzx1aIGTCdzcMlSZt1h8k5Tmk08VNAuRk3IU28XamGiOH5ypi11g6De2CH7PhYqSSnGy2A/EFhbWnVKg==",
"license": "MIT",
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
"license": "MIT"
},
"node_modules/napi-build-utils": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz",
"integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==",
"license": "MIT"
},
"node_modules/negotiator": {
"version": "0.6.3",
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz",
"integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/node-abi": {
"version": "3.94.0",
"resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.94.0.tgz",
"integrity": "sha512-W5ZNO5KRPB5TkYmGVD9F6YqhsglXJzE6etpbmT+f6EQElhiX/UTG551cnsRGvLG3fyZEg9HwaDmNmj5nwJ4z9g==",
"license": "MIT",
"dependencies": {
"semver": "^7.3.5"
},
"engines": {
"node": ">=10"
}
},
"node_modules/node-addon-api": {
"version": "7.1.1",
"resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-7.1.1.tgz",
"integrity": "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==",
"license": "MIT"
},
"node_modules/object-assign": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
"integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/object-inspect": {
"version": "1.13.4",
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
"integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/on-finished": {
"version": "2.4.1",
"resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",
"integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",
"license": "MIT",
"dependencies": {
"ee-first": "1.1.1"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/once": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
"integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
"license": "ISC",
"dependencies": {
"wrappy": "1"
}
},
"node_modules/pako": {
"version": "1.0.11",
"resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz",
"integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==",
"license": "(MIT AND Zlib)"
},
"node_modules/parseurl": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
"integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/path-to-regexp": {
"version": "0.1.13",
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.13.tgz",
"integrity": "sha512-A/AGNMFN3c8bOlvV9RreMdrv7jsmF9XIfDeCd87+I8RNg6s78BhJxMu69NEMHBSJFxKidViTEdruRwEk/WIKqA==",
"license": "MIT"
},
"node_modules/pdfkit": {
"version": "0.19.1",
"resolved": "https://registry.npmjs.org/pdfkit/-/pdfkit-0.19.1.tgz",
"integrity": "sha512-6Gzk+wDwTs4VSxsR5rCMTnIl5nlmkye1oWB0l2hDB1EX6ZNSIBroKQEv+2+fPPn+stVjyqzmsqRJVDfB9fo5DA==",
"license": "MIT",
"dependencies": {
"@noble/ciphers": "^1.0.0",
"@noble/hashes": "^1.6.0",
"fontkit": "^2.0.4",
"js-md5": "^0.8.3",
"linebreak": "^1.1.0",
"png-js": "^1.1.0"
}
},
"node_modules/picomatch": {
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz",
"integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==",
"license": "MIT",
"engines": {
"node": ">=8.6"
},
"funding": {
"url": "https://github.com/sponsors/jonschlinkert"
}
},
"node_modules/png-js": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/png-js/-/png-js-1.1.0.tgz",
"integrity": "sha512-PM/uYGzGdNSzqeOgly68+6wKQDL1SY0a/N+OEa/+br6LnHWOAJB0Npiamnodfq3jd2LS/i2fMeOKSAILjA+m5Q==",
"dependencies": {
"browserify-zlib": "^0.2.0"
}
},
"node_modules/prebuild-install": {
"version": "7.1.3",
"resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz",
"integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==",
"deprecated": "No longer maintained. Please contact the author of the relevant native addon; alternatives are available.",
"license": "MIT",
"dependencies": {
"detect-libc": "^2.0.0",
"expand-template": "^2.0.3",
"github-from-package": "0.0.0",
"minimist": "^1.2.3",
"mkdirp-classic": "^0.5.3",
"napi-build-utils": "^2.0.0",
"node-abi": "^3.3.0",
"pump": "^3.0.0",
"rc": "^1.2.7",
"simple-get": "^4.0.0",
"tar-fs": "^2.0.0",
"tunnel-agent": "^0.6.0"
},
"bin": {
"prebuild-install": "bin.js"
},
"engines": {
"node": ">=10"
}
},
"node_modules/proxy-addr": {
"version": "2.0.7",
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
"integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==",
"license": "MIT",
"dependencies": {
"forwarded": "0.2.0",
"ipaddr.js": "1.9.1"
},
"engines": {
"node": ">= 0.10"
}
},
"node_modules/pump": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz",
"integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==",
"license": "MIT",
"dependencies": {
"end-of-stream": "^1.1.0",
"once": "^1.3.1"
}
},
"node_modules/puppeteer": {
"version": "25.3.0",
"resolved": "https://registry.npmjs.org/puppeteer/-/puppeteer-25.3.0.tgz",
"integrity": "sha512-O1tx8S315aw8eI99HZ5ZNcVEzJ9+jKF//eO5UvfZ3cXJ6okZ5sX3Y50u7DJaM+ewEK4LqXP068tBhfRaWikj+g==",
"hasInstallScript": true,
"license": "Apache-2.0",
"dependencies": {
"@puppeteer/browsers": "3.0.6",
"chromium-bidi": "16.0.1",
"devtools-protocol": "0.0.1638949",
"lilconfig": "^3.1.3",
"puppeteer-core": "25.3.0",
"typed-query-selector": "^2.12.2"
},
"bin": {
"puppeteer": "lib/puppeteer/node/cli.js"
},
"engines": {
"node": ">=22.12.0"
}
},
"node_modules/puppeteer-core": {
"version": "25.3.0",
"resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-25.3.0.tgz",
"integrity": "sha512-fm+wpUr2oigH1PXZvwgATrM2tYWHMDG8ASzTEe9uukCye4X5Ldx1K5BTHPFKITrIWvQQAQ256d1NpbEveBcKjA==",
"license": "Apache-2.0",
"dependencies": {
"@puppeteer/browsers": "3.0.6",
"chromium-bidi": "16.0.1",
"devtools-protocol": "0.0.1638949",
"typed-query-selector": "^2.12.2",
"webdriver-bidi-protocol": "0.4.2",
"ws": "^8.21.0"
},
"engines": {
"node": ">=22.12.0"
}
},
"node_modules/qs": {
"version": "6.15.3",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.15.3.tgz",
"integrity": "sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A==",
"license": "BSD-3-Clause",
"dependencies": {
"es-define-property": "^1.0.1",
"side-channel": "^1.1.1"
},
"engines": {
"node": ">=0.6"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/range-parser": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
"integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/raw-body": {
"version": "2.5.3",
"resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.3.tgz",
"integrity": "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==",
"license": "MIT",
"dependencies": {
"bytes": "~3.1.2",
"http-errors": "~2.0.1",
"iconv-lite": "~0.4.24",
"unpipe": "~1.0.0"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/rc": {
"version": "1.2.8",
"resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz",
"integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==",
"license": "(BSD-2-Clause OR MIT OR Apache-2.0)",
"dependencies": {
"deep-extend": "^0.6.0",
"ini": "~1.3.0",
"minimist": "^1.2.0",
"strip-json-comments": "~2.0.1"
},
"bin": {
"rc": "cli.js"
}
},
"node_modules/readable-stream": {
"version": "3.6.2",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
"integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
"license": "MIT",
"dependencies": {
"inherits": "^2.0.3",
"string_decoder": "^1.1.1",
"util-deprecate": "^1.0.1"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/restructure": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/restructure/-/restructure-3.0.2.tgz",
"integrity": "sha512-gSfoiOEA0VPE6Tukkrr7I0RBdE0s7H1eFCDBk05l1KIQT1UIKNc5JZy6jdyW6eYH3aR3g5b3PuL77rq0hvwtAw==",
"license": "MIT"
},
"node_modules/safe-buffer": {
"version": "5.2.1",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
"integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT"
},
"node_modules/safer-buffer": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
"license": "MIT"
},
"node_modules/semver": {
"version": "7.8.5",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
"integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
"license": "ISC",
"bin": {
"semver": "bin/semver.js"
},
"engines": {
"node": ">=10"
}
},
"node_modules/send": {
"version": "0.19.2",
"resolved": "https://registry.npmjs.org/send/-/send-0.19.2.tgz",
"integrity": "sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg==",
"license": "MIT",
"dependencies": {
"debug": "2.6.9",
"depd": "2.0.0",
"destroy": "1.2.0",
"encodeurl": "~2.0.0",
"escape-html": "~1.0.3",
"etag": "~1.8.1",
"fresh": "~0.5.2",
"http-errors": "~2.0.1",
"mime": "1.6.0",
"ms": "2.1.3",
"on-finished": "~2.4.1",
"range-parser": "~1.2.1",
"statuses": "~2.0.2"
},
"engines": {
"node": ">= 0.8.0"
}
},
"node_modules/send/node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
"node_modules/serve-static": {
"version": "1.16.3",
"resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.3.tgz",
"integrity": "sha512-x0RTqQel6g5SY7Lg6ZreMmsOzncHFU7nhnRWkKgWuMTu5NN0DR5oruckMqRvacAN9d5w6ARnRBXl9xhDCgfMeA==",
"license": "MIT",
"dependencies": {
"encodeurl": "~2.0.0",
"escape-html": "~1.0.3",
"parseurl": "~1.3.3",
"send": "~0.19.1"
},
"engines": {
"node": ">= 0.8.0"
}
},
"node_modules/setprototypeof": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
"integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",
"license": "ISC"
},
"node_modules/side-channel": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz",
"integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"object-inspect": "^1.13.4",
"side-channel-list": "^1.0.1",
"side-channel-map": "^1.0.1",
"side-channel-weakmap": "^1.0.2"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/side-channel-list": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz",
"integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"object-inspect": "^1.13.4"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/side-channel-map": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",
"integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",
"license": "MIT",
"dependencies": {
"call-bound": "^1.0.2",
"es-errors": "^1.3.0",
"get-intrinsic": "^1.2.5",
"object-inspect": "^1.13.3"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/side-channel-weakmap": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",
"integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",
"license": "MIT",
"dependencies": {
"call-bound": "^1.0.2",
"es-errors": "^1.3.0",
"get-intrinsic": "^1.2.5",
"object-inspect": "^1.13.3",
"side-channel-map": "^1.0.1"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/simple-concat": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz",
"integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT"
},
"node_modules/simple-get": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz",
"integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT",
"dependencies": {
"decompress-response": "^6.0.0",
"once": "^1.3.1",
"simple-concat": "^1.0.0"
}
},
"node_modules/statuses": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
"integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/string_decoder": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
"integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
"license": "MIT",
"dependencies": {
"safe-buffer": "~5.2.0"
}
},
"node_modules/string-width": {
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz",
"integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==",
"license": "MIT",
"dependencies": {
"emoji-regex": "^10.3.0",
"get-east-asian-width": "^1.0.0",
"strip-ansi": "^7.1.0"
},
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/strip-ansi": {
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz",
"integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==",
"license": "MIT",
"dependencies": {
"ansi-regex": "^6.2.2"
},
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/chalk/strip-ansi?sponsor=1"
}
},
"node_modules/strip-json-comments": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz",
"integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/tar-fs": {
"version": "2.1.5",
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.5.tgz",
"integrity": "sha512-OboTd8mmMhZDNPV+UjQcK9yKAatXu2aJ+r1w4im1Otd4M4fl2hwvdoXUxIYHFTHWK/3y3FarBP70v3vwmGlOxw==",
"license": "MIT",
"dependencies": {
"chownr": "^1.1.1",
"mkdirp-classic": "^0.5.2",
"pump": "^3.0.0",
"tar-stream": "^2.1.4"
}
},
"node_modules/tar-stream": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz",
"integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==",
"license": "MIT",
"dependencies": {
"bl": "^4.0.3",
"end-of-stream": "^1.4.1",
"fs-constants": "^1.0.0",
"inherits": "^2.0.3",
"readable-stream": "^3.1.1"
},
"engines": {
"node": ">=6"
}
},
"node_modules/tiny-inflate": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/tiny-inflate/-/tiny-inflate-1.0.3.tgz",
"integrity": "sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==",
"license": "MIT"
},
"node_modules/to-regex-range": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
"integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==",
"license": "MIT",
"dependencies": {
"is-number": "^7.0.0"
},
"engines": {
"node": ">=8.0"
}
},
"node_modules/toidentifier": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
"integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",
"license": "MIT",
"engines": {
"node": ">=0.6"
}
},
"node_modules/tslib": {
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"license": "0BSD"
},
"node_modules/tunnel-agent": {
"version": "0.6.0",
"resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz",
"integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==",
"license": "Apache-2.0",
"dependencies": {
"safe-buffer": "^5.0.1"
},
"engines": {
"node": "*"
}
},
"node_modules/type-is": {
"version": "1.6.18",
"resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz",
"integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==",
"license": "MIT",
"dependencies": {
"media-typer": "0.3.0",
"mime-types": "~2.1.24"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/typed-query-selector": {
"version": "2.12.2",
"resolved": "https://registry.npmjs.org/typed-query-selector/-/typed-query-selector-2.12.2.tgz",
"integrity": "sha512-EOPFbyIub4ngnEdqi2yOcNeDLaX/0jcE1JoAXQDDMIthap7FoN795lc/SHfIq2d416VufXpM8z/lD+WRm2gfOQ==",
"license": "MIT"
},
"node_modules/unicode-properties": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/unicode-properties/-/unicode-properties-1.4.1.tgz",
"integrity": "sha512-CLjCCLQ6UuMxWnbIylkisbRj31qxHPAurvena/0iwSVbQ2G1VY5/HjV0IRabOEbDHlzZlRdCrD4NhB0JtU40Pg==",
"license": "MIT",
"dependencies": {
"base64-js": "^1.3.0",
"unicode-trie": "^2.0.0"
}
},
"node_modules/unicode-trie": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/unicode-trie/-/unicode-trie-2.0.0.tgz",
"integrity": "sha512-x7bc76x0bm4prf1VLg79uhAzKw8DVboClSN5VxJuQ+LKDOVEW9CdH+VY7SP+vX7xCYQqzzgQpFqz15zeLvAtZQ==",
"license": "MIT",
"dependencies": {
"pako": "^0.2.5",
"tiny-inflate": "^1.0.0"
}
},
"node_modules/unicode-trie/node_modules/pako": {
"version": "0.2.9",
"resolved": "https://registry.npmjs.org/pako/-/pako-0.2.9.tgz",
"integrity": "sha512-NUcwaKxUxWrZLpDG+z/xZaCgQITkA/Dv4V/T6bw7VON6l1Xz/VnrBqrYjZQ12TamKHzITTfOEIYUj48y2KXImA==",
"license": "MIT"
},
"node_modules/unpipe": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
"integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/util-deprecate": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
"license": "MIT"
},
"node_modules/utils-merge": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
"integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==",
"license": "MIT",
"engines": {
"node": ">= 0.4.0"
}
},
"node_modules/vary": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
"integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/webdriver-bidi-protocol": {
"version": "0.4.2",
"resolved": "https://registry.npmjs.org/webdriver-bidi-protocol/-/webdriver-bidi-protocol-0.4.2.tgz",
"integrity": "sha512-VSV+fzfChirL3e7jay2yUC7B4HQCGtEWEg/MSSQbK+qWbqeGlRLlXTzPpYr3XGUvbpDHumWZBJxgesg4N7dbtA==",
"license": "Apache-2.0"
},
"node_modules/wrap-ansi": {
"version": "9.0.2",
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz",
"integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==",
"license": "MIT",
"dependencies": {
"ansi-styles": "^6.2.1",
"string-width": "^7.0.0",
"strip-ansi": "^7.1.0"
},
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/chalk/wrap-ansi?sponsor=1"
}
},
"node_modules/wrappy": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
"license": "ISC"
},
"node_modules/ws": {
"version": "8.21.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz",
"integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
},
"node_modules/y18n": {
"version": "5.0.8",
"resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",
"integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==",
"license": "ISC",
"engines": {
"node": ">=10"
}
},
"node_modules/yargs": {
"version": "18.0.0",
"resolved": "https://registry.npmjs.org/yargs/-/yargs-18.0.0.tgz",
"integrity": "sha512-4UEqdc2RYGHZc7Doyqkrqiln3p9X2DZVxaGbwhn2pi7MrRagKaOcIKe8L3OxYcbhXLgLFUS3zAYuQjKBQgmuNg==",
"license": "MIT",
"dependencies": {
"cliui": "^9.0.1",
"escalade": "^3.1.1",
"get-caller-file": "^2.0.5",
"string-width": "^7.2.0",
"y18n": "^5.0.5",
"yargs-parser": "^22.0.0"
},
"engines": {
"node": "^20.19.0 || ^22.12.0 || >=23"
}
},
"node_modules/yargs-parser": {
"version": "22.0.0",
"resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-22.0.0.tgz",
"integrity": "sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw==",
"license": "ISC",
"engines": {
"node": "^20.19.0 || ^22.12.0 || >=23"
}
},
"node_modules/zod": {
"version": "3.25.76",
"resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
"integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
}
}
}
+9
View File
@@ -0,0 +1,9 @@
The MIT License (MIT)
Copyright (c) 2018-2024 Jukka Kurkela
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.
+79
View File
@@ -0,0 +1,79 @@
# @kurkle/color
[![npm](https://img.shields.io/npm/v/@kurkle/color?style=plastic)](https://www.npmjs.com/package/@kurkle/color) [![release](https://img.shields.io/github/release/kurkle/color.svg?style=plastic)](https://github.com/kurkle/color/releases/latest) [![npm bundle size](https://img.shields.io/bundlephobia/minzip/@kurkle/color?style=plastic)](https://www.npmjs.com/package/@kurkle/color) [![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/kurkle/color/ci.yml?style=plastic)](https://github.com/kurkle/color) [![GitHub](https://img.shields.io/github/license/kurkle/color?style=plastic)](https://github.com/kurkle/color/blob/main/LICENSE.md)
## Overview
Fast and small CSS color parsing and manipulation library.
## Parsing
Supported formats:
- named
```text
blue
transparent
```
- hex
```text
#aaa
#bbba
#1A2b3c
#f1f2f388
```
- rgb(a)
```text
rgb(255, 255, 255)
rgb(255, 0, 0, 0.5)
rgb(50%, 50%, 50%, 50%)
rgb(0 0 100% / 80%)
rgba(200, 20, 233, 0.2)
rgba(200, 20, 233, 2e-1)
```
- hsl(a)
```text
hsl(240deg, 100%, 50.5%)
hsl(0deg 100% 50%)
hsla(12, 10%, 50%, .3)
hsla(-1.2, 10.2%, 50.9%, 0.4)
```
- hwb
```text
hwb(240, 100%, 50.5%)
hwb(244, 100%, 100%, 0.6)
```
- hsv
```text
hsv(240, 100%, 50.5%)
hsv(244, 100%, 100%, 0.6)
```
## Docs
[typedocs](https://kurkle.github.io/color/)
**note** The docs are for the ESM module. UMD module only exports the [default export](https://kurkle.github.io/color/modules.html#default)
## Benchmarks
[benchmarks](https://kurkle.github.io/color/dev/bench/)
## Size visualization
[color.min.js](https://kurkle.github.io/color/stats.html)
## License
`@kurkle/color` is available under the [MIT license](https://github.com/kurkle/color/blob/main/LICENSE.md).
+624
View File
@@ -0,0 +1,624 @@
/*!
* @kurkle/color v0.3.4
* https://github.com/kurkle/color#readme
* (c) 2024 Jukka Kurkela
* Released under the MIT License
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global["@kurkle/color"] = factory());
})(this, (function () { 'use strict';
function round(v) {
return v + 0.5 | 0;
}
const lim = (v, l, h) => Math.max(Math.min(v, h), l);
function p2b(v) {
return lim(round(v * 2.55), 0, 255);
}
function b2p(v) {
return lim(round(v / 2.55), 0, 100);
}
function n2b(v) {
return lim(round(v * 255), 0, 255);
}
function b2n(v) {
return lim(round(v / 2.55) / 100, 0, 1);
}
function n2p(v) {
return lim(round(v * 100), 0, 100);
}
const map$1 = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, A: 10, B: 11, C: 12, D: 13, E: 14, F: 15, a: 10, b: 11, c: 12, d: 13, e: 14, f: 15};
const hex = [...'0123456789ABCDEF'];
const h1 = b => hex[b & 0xF];
const h2 = b => hex[(b & 0xF0) >> 4] + hex[b & 0xF];
const eq = b => ((b & 0xF0) >> 4) === (b & 0xF);
const isShort = v => eq(v.r) && eq(v.g) && eq(v.b) && eq(v.a);
function hexParse(str) {
var len = str.length;
var ret;
if (str[0] === '#') {
if (len === 4 || len === 5) {
ret = {
r: 255 & map$1[str[1]] * 17,
g: 255 & map$1[str[2]] * 17,
b: 255 & map$1[str[3]] * 17,
a: len === 5 ? map$1[str[4]] * 17 : 255
};
} else if (len === 7 || len === 9) {
ret = {
r: map$1[str[1]] << 4 | map$1[str[2]],
g: map$1[str[3]] << 4 | map$1[str[4]],
b: map$1[str[5]] << 4 | map$1[str[6]],
a: len === 9 ? (map$1[str[7]] << 4 | map$1[str[8]]) : 255
};
}
}
return ret;
}
const alpha = (a, f) => a < 255 ? f(a) : '';
function hexString(v) {
var f = isShort(v) ? h1 : h2;
return v
? '#' + f(v.r) + f(v.g) + f(v.b) + alpha(v.a, f)
: undefined;
}
const HUE_RE = /^(hsla?|hwb|hsv)\(\s*([-+.e\d]+)(?:deg)?[\s,]+([-+.e\d]+)%[\s,]+([-+.e\d]+)%(?:[\s,]+([-+.e\d]+)(%)?)?\s*\)$/;
function hsl2rgbn(h, s, l) {
const a = s * Math.min(l, 1 - l);
const f = (n, k = (n + h / 30) % 12) => l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
return [f(0), f(8), f(4)];
}
function hsv2rgbn(h, s, v) {
const f = (n, k = (n + h / 60) % 6) => v - v * s * Math.max(Math.min(k, 4 - k, 1), 0);
return [f(5), f(3), f(1)];
}
function hwb2rgbn(h, w, b) {
const rgb = hsl2rgbn(h, 1, 0.5);
let i;
if (w + b > 1) {
i = 1 / (w + b);
w *= i;
b *= i;
}
for (i = 0; i < 3; i++) {
rgb[i] *= 1 - w - b;
rgb[i] += w;
}
return rgb;
}
function hueValue(r, g, b, d, max) {
if (r === max) {
return ((g - b) / d) + (g < b ? 6 : 0);
}
if (g === max) {
return (b - r) / d + 2;
}
return (r - g) / d + 4;
}
function rgb2hsl(v) {
const range = 255;
const r = v.r / range;
const g = v.g / range;
const b = v.b / range;
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
const l = (max + min) / 2;
let h, s, d;
if (max !== min) {
d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
h = hueValue(r, g, b, d, max);
h = h * 60 + 0.5;
}
return [h | 0, s || 0, l];
}
function calln(f, a, b, c) {
return (
Array.isArray(a)
? f(a[0], a[1], a[2])
: f(a, b, c)
).map(n2b);
}
function hsl2rgb(h, s, l) {
return calln(hsl2rgbn, h, s, l);
}
function hwb2rgb(h, w, b) {
return calln(hwb2rgbn, h, w, b);
}
function hsv2rgb(h, s, v) {
return calln(hsv2rgbn, h, s, v);
}
function hue(h) {
return (h % 360 + 360) % 360;
}
function hueParse(str) {
const m = HUE_RE.exec(str);
let a = 255;
let v;
if (!m) {
return;
}
if (m[5] !== v) {
a = m[6] ? p2b(+m[5]) : n2b(+m[5]);
}
const h = hue(+m[2]);
const p1 = +m[3] / 100;
const p2 = +m[4] / 100;
if (m[1] === 'hwb') {
v = hwb2rgb(h, p1, p2);
} else if (m[1] === 'hsv') {
v = hsv2rgb(h, p1, p2);
} else {
v = hsl2rgb(h, p1, p2);
}
return {
r: v[0],
g: v[1],
b: v[2],
a: a
};
}
function rotate(v, deg) {
var h = rgb2hsl(v);
h[0] = hue(h[0] + deg);
h = hsl2rgb(h);
v.r = h[0];
v.g = h[1];
v.b = h[2];
}
function hslString(v) {
if (!v) {
return;
}
const a = rgb2hsl(v);
const h = a[0];
const s = n2p(a[1]);
const l = n2p(a[2]);
return v.a < 255
? `hsla(${h}, ${s}%, ${l}%, ${b2n(v.a)})`
: `hsl(${h}, ${s}%, ${l}%)`;
}
const map = {
x: 'dark',
Z: 'light',
Y: 're',
X: 'blu',
W: 'gr',
V: 'medium',
U: 'slate',
A: 'ee',
T: 'ol',
S: 'or',
B: 'ra',
C: 'lateg',
D: 'ights',
R: 'in',
Q: 'turquois',
E: 'hi',
P: 'ro',
O: 'al',
N: 'le',
M: 'de',
L: 'yello',
F: 'en',
K: 'ch',
G: 'arks',
H: 'ea',
I: 'ightg',
J: 'wh'
};
const names$1 = {
OiceXe: 'f0f8ff',
antiquewEte: 'faebd7',
aqua: 'ffff',
aquamarRe: '7fffd4',
azuY: 'f0ffff',
beige: 'f5f5dc',
bisque: 'ffe4c4',
black: '0',
blanKedOmond: 'ffebcd',
Xe: 'ff',
XeviTet: '8a2be2',
bPwn: 'a52a2a',
burlywood: 'deb887',
caMtXe: '5f9ea0',
KartYuse: '7fff00',
KocTate: 'd2691e',
cSO: 'ff7f50',
cSnflowerXe: '6495ed',
cSnsilk: 'fff8dc',
crimson: 'dc143c',
cyan: 'ffff',
xXe: '8b',
xcyan: '8b8b',
xgTMnPd: 'b8860b',
xWay: 'a9a9a9',
xgYF: '6400',
xgYy: 'a9a9a9',
xkhaki: 'bdb76b',
xmagFta: '8b008b',
xTivegYF: '556b2f',
xSange: 'ff8c00',
xScEd: '9932cc',
xYd: '8b0000',
xsOmon: 'e9967a',
xsHgYF: '8fbc8f',
xUXe: '483d8b',
xUWay: '2f4f4f',
xUgYy: '2f4f4f',
xQe: 'ced1',
xviTet: '9400d3',
dAppRk: 'ff1493',
dApskyXe: 'bfff',
dimWay: '696969',
dimgYy: '696969',
dodgerXe: '1e90ff',
fiYbrick: 'b22222',
flSOwEte: 'fffaf0',
foYstWAn: '228b22',
fuKsia: 'ff00ff',
gaRsbSo: 'dcdcdc',
ghostwEte: 'f8f8ff',
gTd: 'ffd700',
gTMnPd: 'daa520',
Way: '808080',
gYF: '8000',
gYFLw: 'adff2f',
gYy: '808080',
honeyMw: 'f0fff0',
hotpRk: 'ff69b4',
RdianYd: 'cd5c5c',
Rdigo: '4b0082',
ivSy: 'fffff0',
khaki: 'f0e68c',
lavFMr: 'e6e6fa',
lavFMrXsh: 'fff0f5',
lawngYF: '7cfc00',
NmoncEffon: 'fffacd',
ZXe: 'add8e6',
ZcSO: 'f08080',
Zcyan: 'e0ffff',
ZgTMnPdLw: 'fafad2',
ZWay: 'd3d3d3',
ZgYF: '90ee90',
ZgYy: 'd3d3d3',
ZpRk: 'ffb6c1',
ZsOmon: 'ffa07a',
ZsHgYF: '20b2aa',
ZskyXe: '87cefa',
ZUWay: '778899',
ZUgYy: '778899',
ZstAlXe: 'b0c4de',
ZLw: 'ffffe0',
lime: 'ff00',
limegYF: '32cd32',
lRF: 'faf0e6',
magFta: 'ff00ff',
maPon: '800000',
VaquamarRe: '66cdaa',
VXe: 'cd',
VScEd: 'ba55d3',
VpurpN: '9370db',
VsHgYF: '3cb371',
VUXe: '7b68ee',
VsprRggYF: 'fa9a',
VQe: '48d1cc',
VviTetYd: 'c71585',
midnightXe: '191970',
mRtcYam: 'f5fffa',
mistyPse: 'ffe4e1',
moccasR: 'ffe4b5',
navajowEte: 'ffdead',
navy: '80',
Tdlace: 'fdf5e6',
Tive: '808000',
TivedBb: '6b8e23',
Sange: 'ffa500',
SangeYd: 'ff4500',
ScEd: 'da70d6',
pOegTMnPd: 'eee8aa',
pOegYF: '98fb98',
pOeQe: 'afeeee',
pOeviTetYd: 'db7093',
papayawEp: 'ffefd5',
pHKpuff: 'ffdab9',
peru: 'cd853f',
pRk: 'ffc0cb',
plum: 'dda0dd',
powMrXe: 'b0e0e6',
purpN: '800080',
YbeccapurpN: '663399',
Yd: 'ff0000',
Psybrown: 'bc8f8f',
PyOXe: '4169e1',
saddNbPwn: '8b4513',
sOmon: 'fa8072',
sandybPwn: 'f4a460',
sHgYF: '2e8b57',
sHshell: 'fff5ee',
siFna: 'a0522d',
silver: 'c0c0c0',
skyXe: '87ceeb',
UXe: '6a5acd',
UWay: '708090',
UgYy: '708090',
snow: 'fffafa',
sprRggYF: 'ff7f',
stAlXe: '4682b4',
tan: 'd2b48c',
teO: '8080',
tEstN: 'd8bfd8',
tomato: 'ff6347',
Qe: '40e0d0',
viTet: 'ee82ee',
JHt: 'f5deb3',
wEte: 'ffffff',
wEtesmoke: 'f5f5f5',
Lw: 'ffff00',
LwgYF: '9acd32'
};
function unpack() {
const unpacked = {};
const keys = Object.keys(names$1);
const tkeys = Object.keys(map);
let i, j, k, ok, nk;
for (i = 0; i < keys.length; i++) {
ok = nk = keys[i];
for (j = 0; j < tkeys.length; j++) {
k = tkeys[j];
nk = nk.replace(k, map[k]);
}
k = parseInt(names$1[ok], 16);
unpacked[nk] = [k >> 16 & 0xFF, k >> 8 & 0xFF, k & 0xFF];
}
return unpacked;
}
let names;
function nameParse(str) {
if (!names) {
names = unpack();
names.transparent = [0, 0, 0, 0];
}
const a = names[str.toLowerCase()];
return a && {
r: a[0],
g: a[1],
b: a[2],
a: a.length === 4 ? a[3] : 255
};
}
const RGB_RE = /^rgba?\(\s*([-+.\d]+)(%)?[\s,]+([-+.e\d]+)(%)?[\s,]+([-+.e\d]+)(%)?(?:[\s,/]+([-+.e\d]+)(%)?)?\s*\)$/;
function rgbParse(str) {
const m = RGB_RE.exec(str);
let a = 255;
let r, g, b;
if (!m) {
return;
}
if (m[7] !== r) {
const v = +m[7];
a = m[8] ? p2b(v) : lim(v * 255, 0, 255);
}
r = +m[1];
g = +m[3];
b = +m[5];
r = 255 & (m[2] ? p2b(r) : lim(r, 0, 255));
g = 255 & (m[4] ? p2b(g) : lim(g, 0, 255));
b = 255 & (m[6] ? p2b(b) : lim(b, 0, 255));
return {
r: r,
g: g,
b: b,
a: a
};
}
function rgbString(v) {
return v && (
v.a < 255
? `rgba(${v.r}, ${v.g}, ${v.b}, ${b2n(v.a)})`
: `rgb(${v.r}, ${v.g}, ${v.b})`
);
}
const to = v => v <= 0.0031308 ? v * 12.92 : Math.pow(v, 1.0 / 2.4) * 1.055 - 0.055;
const from = v => v <= 0.04045 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
function interpolate(rgb1, rgb2, t) {
const r = from(b2n(rgb1.r));
const g = from(b2n(rgb1.g));
const b = from(b2n(rgb1.b));
return {
r: n2b(to(r + t * (from(b2n(rgb2.r)) - r))),
g: n2b(to(g + t * (from(b2n(rgb2.g)) - g))),
b: n2b(to(b + t * (from(b2n(rgb2.b)) - b))),
a: rgb1.a + t * (rgb2.a - rgb1.a)
};
}
function modHSL(v, i, ratio) {
if (v) {
let tmp = rgb2hsl(v);
tmp[i] = Math.max(0, Math.min(tmp[i] + tmp[i] * ratio, i === 0 ? 360 : 1));
tmp = hsl2rgb(tmp);
v.r = tmp[0];
v.g = tmp[1];
v.b = tmp[2];
}
}
function clone(v, proto) {
return v ? Object.assign(proto || {}, v) : v;
}
function fromObject(input) {
var v = {r: 0, g: 0, b: 0, a: 255};
if (Array.isArray(input)) {
if (input.length >= 3) {
v = {r: input[0], g: input[1], b: input[2], a: 255};
if (input.length > 3) {
v.a = n2b(input[3]);
}
}
} else {
v = clone(input, {r: 0, g: 0, b: 0, a: 1});
v.a = n2b(v.a);
}
return v;
}
function functionParse(str) {
if (str.charAt(0) === 'r') {
return rgbParse(str);
}
return hueParse(str);
}
class Color {
constructor(input) {
if (input instanceof Color) {
return input;
}
const type = typeof input;
let v;
if (type === 'object') {
v = fromObject(input);
} else if (type === 'string') {
v = hexParse(input) || nameParse(input) || functionParse(input);
}
this._rgb = v;
this._valid = !!v;
}
get valid() {
return this._valid;
}
get rgb() {
var v = clone(this._rgb);
if (v) {
v.a = b2n(v.a);
}
return v;
}
set rgb(obj) {
this._rgb = fromObject(obj);
}
rgbString() {
return this._valid ? rgbString(this._rgb) : undefined;
}
hexString() {
return this._valid ? hexString(this._rgb) : undefined;
}
hslString() {
return this._valid ? hslString(this._rgb) : undefined;
}
mix(color, weight) {
if (color) {
const c1 = this.rgb;
const c2 = color.rgb;
let w2;
const p = weight === w2 ? 0.5 : weight;
const w = 2 * p - 1;
const a = c1.a - c2.a;
const w1 = ((w * a === -1 ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
w2 = 1 - w1;
c1.r = 0xFF & w1 * c1.r + w2 * c2.r + 0.5;
c1.g = 0xFF & w1 * c1.g + w2 * c2.g + 0.5;
c1.b = 0xFF & w1 * c1.b + w2 * c2.b + 0.5;
c1.a = p * c1.a + (1 - p) * c2.a;
this.rgb = c1;
}
return this;
}
interpolate(color, t) {
if (color) {
this._rgb = interpolate(this._rgb, color._rgb, t);
}
return this;
}
clone() {
return new Color(this.rgb);
}
alpha(a) {
this._rgb.a = n2b(a);
return this;
}
clearer(ratio) {
const rgb = this._rgb;
rgb.a *= 1 - ratio;
return this;
}
greyscale() {
const rgb = this._rgb;
const val = round(rgb.r * 0.3 + rgb.g * 0.59 + rgb.b * 0.11);
rgb.r = rgb.g = rgb.b = val;
return this;
}
opaquer(ratio) {
const rgb = this._rgb;
rgb.a *= 1 + ratio;
return this;
}
negate() {
const v = this._rgb;
v.r = 255 - v.r;
v.g = 255 - v.g;
v.b = 255 - v.b;
return this;
}
lighten(ratio) {
modHSL(this._rgb, 2, ratio);
return this;
}
darken(ratio) {
modHSL(this._rgb, 2, -ratio);
return this;
}
saturate(ratio) {
modHSL(this._rgb, 1, ratio);
return this;
}
desaturate(ratio) {
modHSL(this._rgb, 1, -ratio);
return this;
}
rotate(deg) {
rotate(this._rgb, deg);
return this;
}
}
function index_esm(input) {
return new Color(input);
}
var color = /*#__PURE__*/Object.freeze({
__proto__: null,
Color: Color,
b2n: b2n,
b2p: b2p,
default: index_esm,
hexParse: hexParse,
hexString: hexString,
hsl2rgb: hsl2rgb,
hslString: hslString,
hsv2rgb: hsv2rgb,
hueParse: hueParse,
hwb2rgb: hwb2rgb,
lim: lim,
n2b: n2b,
n2p: n2p,
nameParse: nameParse,
p2b: p2b,
rgb2hsl: rgb2hsl,
rgbParse: rgbParse,
rgbString: rgbString,
rotate: rotate,
round: round
});
var index = Object.assign(index_esm, color);
return index;
}));
+235
View File
@@ -0,0 +1,235 @@
/**
* @packageDocumentation
* @module @kurkle/color
*/
export type RGBA = {
/**
* - red [0..255]
*/
r: number;
/**
* - green [0..255]
*/
g: number;
/**
* - blue [0..255]
*/
b: number;
/**
* - alpha [0..1]
*/
a: number;
};
/**
* Parse HEX to color
* @param {string} str - the string
*/
export function hexParse(str: string): {
r: number;
g: number;
b: number;
a: number;
};
/**
* Return HEX string from color
* @param {RGBA} v - the color
*/
export function hexString(v: RGBA): string | RGBA;
/**
* Rounds decimal to nearest integer
* @param {number} v - the number to round
*/
export function round(v: number): number;
/**
* convert percent to byte 0..255
* @param {number} v - 0..100
*/
export function p2b(v: number): number;
/**
* convert byte to percet 0..100
* @param {number} v - 0..255
*/
export function b2p(v: number): number;
/**
* convert normalized to byte 0..255
* @param {number} v - 0..1
*/
export function n2b(v: number): number;
/**
* convert byte to normalized 0..1
* @param {number} v - 0..255
*/
export function b2n(v: number): number;
/**
* convert normalized to percent 0..100
* @param {number} v - 0..1
*/
export function n2p(v: number): number;
/**
* Convert rgb to hsl
* @param {RGBA} v - the color
* @returns {number[]} - [h, s, l]
*/
export function rgb2hsl(v: RGBA): number[];
/**
* Convert hsl to rgb
* @param {number|number[]} h - hue | [h, s, l]
* @param {number} [s] - saturation
* @param {number} [l] - lightness
* @returns {number[]}
*/
export function hsl2rgb(h: number | number[], s?: number, l?: number): number[];
/**
* Convert hwb to rgb
* @param {number|number[]} h - hue | [h, s, l]
* @param {number} [w] - whiteness
* @param {number} [b] - blackness
* @returns {number[]}
*/
export function hwb2rgb(h: number | number[], w?: number, b?: number): number[];
/**
* Convert hsv to rgb
* @param {number|number[]} h - hue | [h, s, l]
* @param {number} [s] - saturation
* @param {number} [v] - value
* @returns {number[]}
*/
export function hsv2rgb(h: number | number[], s?: number, v?: number): number[];
/**
* Parse hsl/hsv/hwb color string
* @param {string} str - hsl/hsv/hwb color string
* @returns {RGBA} - the parsed color components
*/
export function hueParse(str: string): RGBA;
/**
* Rotate the `v` color by `deg` degrees
* @param {RGBA} v - the color
* @param {number} deg - degrees to rotate
*/
export function rotate(v: RGBA, deg: number): void;
/**
* Return hsl(a) string from color components
* @param {RGBA} v - the color
* @return {string|undefined}
*/
export function hslString(v: RGBA): string;
/**
* Parse color name
* @param {string} str - the color name
* @return {RGBA} - the color
*/
export function nameParse(str: string): RGBA;
/**
* Parse rgb(a) string to RGBA
* @param {string} str - the rgb string
* @returns {RGBA} - the parsed color
*/
export function rgbParse(str: string): RGBA;
/**
* Return rgb(a) string from color
* @param {RGBA} v - the color
*/
export function rgbString(v: RGBA): string;
export class Color {
/**
* constructor
* @param {Color|RGBA|string|number[]} input
*/
constructor(input: string | number[] | Color | RGBA);
/**
* @type {RGBA}
* @hidden
**/
_rgb: RGBA;
/**
* @type {boolean}
* @hidden
**/
_valid: boolean;
/**
* `true` if this is a valid color
* @returns {boolean}
*/
get valid(): boolean;
/**
* @param {RGBA} obj - the color
*/
set rgb(arg: RGBA);
/**
* @returns {RGBA} - the color
*/
get rgb(): RGBA;
/**
* rgb(a) string
*/
rgbString(): string;
/**
* hex string
*/
hexString(): string;
/**
* hsl(a) string
*/
hslString(): string;
/**
* Mix another color to this color.
* @param {Color} color - Color to mix in
* @param {number} weight - 0..1
*/
mix(color: Color, weight: number): Color;
/**
* Clone
*/
clone(): Color;
/**
* Set aplha
* @param {number} a - the alpha [0..1]
*/
alpha(a: number): Color;
/**
* Make clearer
* @param {number} ratio - ratio [0..1]
*/
clearer(ratio: number): Color;
/**
* Convert to grayscale
*/
greyscale(): Color;
/**
* Opaquer
* @param {number} ratio - ratio [0..1]
*/
opaquer(ratio: number): Color;
negate(): Color;
/**
* Lighten
* @param {number} ratio - ratio [0..1]
*/
lighten(ratio: number): Color;
/**
* Darken
* @param {number} ratio - ratio [0..1]
*/
darken(ratio: number): Color;
/**
* Saturate
* @param {number} ratio - ratio [0..1]
*/
saturate(ratio: number): Color;
/**
* Desaturate
* @param {number} ratio - ratio [0..1]
*/
desaturate(ratio: number): Color;
/**
* Rotate
* @param {number} deg - degrees to rotate
*/
rotate(deg: number): Color;
}
/**
* Construct new Color instance
* @param {Color|RGBA|string|number[]} input
*/
export default function _default(input: string | number[] | Color | RGBA): Color;
+589
View File
@@ -0,0 +1,589 @@
/*!
* @kurkle/color v0.3.4
* https://github.com/kurkle/color#readme
* (c) 2024 Jukka Kurkela
* Released under the MIT License
*/
function round(v) {
return v + 0.5 | 0;
}
const lim = (v, l, h) => Math.max(Math.min(v, h), l);
function p2b(v) {
return lim(round(v * 2.55), 0, 255);
}
function b2p(v) {
return lim(round(v / 2.55), 0, 100);
}
function n2b(v) {
return lim(round(v * 255), 0, 255);
}
function b2n(v) {
return lim(round(v / 2.55) / 100, 0, 1);
}
function n2p(v) {
return lim(round(v * 100), 0, 100);
}
const map$1 = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, A: 10, B: 11, C: 12, D: 13, E: 14, F: 15, a: 10, b: 11, c: 12, d: 13, e: 14, f: 15};
const hex = [...'0123456789ABCDEF'];
const h1 = b => hex[b & 0xF];
const h2 = b => hex[(b & 0xF0) >> 4] + hex[b & 0xF];
const eq = b => ((b & 0xF0) >> 4) === (b & 0xF);
const isShort = v => eq(v.r) && eq(v.g) && eq(v.b) && eq(v.a);
function hexParse(str) {
var len = str.length;
var ret;
if (str[0] === '#') {
if (len === 4 || len === 5) {
ret = {
r: 255 & map$1[str[1]] * 17,
g: 255 & map$1[str[2]] * 17,
b: 255 & map$1[str[3]] * 17,
a: len === 5 ? map$1[str[4]] * 17 : 255
};
} else if (len === 7 || len === 9) {
ret = {
r: map$1[str[1]] << 4 | map$1[str[2]],
g: map$1[str[3]] << 4 | map$1[str[4]],
b: map$1[str[5]] << 4 | map$1[str[6]],
a: len === 9 ? (map$1[str[7]] << 4 | map$1[str[8]]) : 255
};
}
}
return ret;
}
const alpha = (a, f) => a < 255 ? f(a) : '';
function hexString(v) {
var f = isShort(v) ? h1 : h2;
return v
? '#' + f(v.r) + f(v.g) + f(v.b) + alpha(v.a, f)
: undefined;
}
const HUE_RE = /^(hsla?|hwb|hsv)\(\s*([-+.e\d]+)(?:deg)?[\s,]+([-+.e\d]+)%[\s,]+([-+.e\d]+)%(?:[\s,]+([-+.e\d]+)(%)?)?\s*\)$/;
function hsl2rgbn(h, s, l) {
const a = s * Math.min(l, 1 - l);
const f = (n, k = (n + h / 30) % 12) => l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
return [f(0), f(8), f(4)];
}
function hsv2rgbn(h, s, v) {
const f = (n, k = (n + h / 60) % 6) => v - v * s * Math.max(Math.min(k, 4 - k, 1), 0);
return [f(5), f(3), f(1)];
}
function hwb2rgbn(h, w, b) {
const rgb = hsl2rgbn(h, 1, 0.5);
let i;
if (w + b > 1) {
i = 1 / (w + b);
w *= i;
b *= i;
}
for (i = 0; i < 3; i++) {
rgb[i] *= 1 - w - b;
rgb[i] += w;
}
return rgb;
}
function hueValue(r, g, b, d, max) {
if (r === max) {
return ((g - b) / d) + (g < b ? 6 : 0);
}
if (g === max) {
return (b - r) / d + 2;
}
return (r - g) / d + 4;
}
function rgb2hsl(v) {
const range = 255;
const r = v.r / range;
const g = v.g / range;
const b = v.b / range;
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
const l = (max + min) / 2;
let h, s, d;
if (max !== min) {
d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
h = hueValue(r, g, b, d, max);
h = h * 60 + 0.5;
}
return [h | 0, s || 0, l];
}
function calln(f, a, b, c) {
return (
Array.isArray(a)
? f(a[0], a[1], a[2])
: f(a, b, c)
).map(n2b);
}
function hsl2rgb(h, s, l) {
return calln(hsl2rgbn, h, s, l);
}
function hwb2rgb(h, w, b) {
return calln(hwb2rgbn, h, w, b);
}
function hsv2rgb(h, s, v) {
return calln(hsv2rgbn, h, s, v);
}
function hue(h) {
return (h % 360 + 360) % 360;
}
function hueParse(str) {
const m = HUE_RE.exec(str);
let a = 255;
let v;
if (!m) {
return;
}
if (m[5] !== v) {
a = m[6] ? p2b(+m[5]) : n2b(+m[5]);
}
const h = hue(+m[2]);
const p1 = +m[3] / 100;
const p2 = +m[4] / 100;
if (m[1] === 'hwb') {
v = hwb2rgb(h, p1, p2);
} else if (m[1] === 'hsv') {
v = hsv2rgb(h, p1, p2);
} else {
v = hsl2rgb(h, p1, p2);
}
return {
r: v[0],
g: v[1],
b: v[2],
a: a
};
}
function rotate(v, deg) {
var h = rgb2hsl(v);
h[0] = hue(h[0] + deg);
h = hsl2rgb(h);
v.r = h[0];
v.g = h[1];
v.b = h[2];
}
function hslString(v) {
if (!v) {
return;
}
const a = rgb2hsl(v);
const h = a[0];
const s = n2p(a[1]);
const l = n2p(a[2]);
return v.a < 255
? `hsla(${h}, ${s}%, ${l}%, ${b2n(v.a)})`
: `hsl(${h}, ${s}%, ${l}%)`;
}
const map = {
x: 'dark',
Z: 'light',
Y: 're',
X: 'blu',
W: 'gr',
V: 'medium',
U: 'slate',
A: 'ee',
T: 'ol',
S: 'or',
B: 'ra',
C: 'lateg',
D: 'ights',
R: 'in',
Q: 'turquois',
E: 'hi',
P: 'ro',
O: 'al',
N: 'le',
M: 'de',
L: 'yello',
F: 'en',
K: 'ch',
G: 'arks',
H: 'ea',
I: 'ightg',
J: 'wh'
};
const names$1 = {
OiceXe: 'f0f8ff',
antiquewEte: 'faebd7',
aqua: 'ffff',
aquamarRe: '7fffd4',
azuY: 'f0ffff',
beige: 'f5f5dc',
bisque: 'ffe4c4',
black: '0',
blanKedOmond: 'ffebcd',
Xe: 'ff',
XeviTet: '8a2be2',
bPwn: 'a52a2a',
burlywood: 'deb887',
caMtXe: '5f9ea0',
KartYuse: '7fff00',
KocTate: 'd2691e',
cSO: 'ff7f50',
cSnflowerXe: '6495ed',
cSnsilk: 'fff8dc',
crimson: 'dc143c',
cyan: 'ffff',
xXe: '8b',
xcyan: '8b8b',
xgTMnPd: 'b8860b',
xWay: 'a9a9a9',
xgYF: '6400',
xgYy: 'a9a9a9',
xkhaki: 'bdb76b',
xmagFta: '8b008b',
xTivegYF: '556b2f',
xSange: 'ff8c00',
xScEd: '9932cc',
xYd: '8b0000',
xsOmon: 'e9967a',
xsHgYF: '8fbc8f',
xUXe: '483d8b',
xUWay: '2f4f4f',
xUgYy: '2f4f4f',
xQe: 'ced1',
xviTet: '9400d3',
dAppRk: 'ff1493',
dApskyXe: 'bfff',
dimWay: '696969',
dimgYy: '696969',
dodgerXe: '1e90ff',
fiYbrick: 'b22222',
flSOwEte: 'fffaf0',
foYstWAn: '228b22',
fuKsia: 'ff00ff',
gaRsbSo: 'dcdcdc',
ghostwEte: 'f8f8ff',
gTd: 'ffd700',
gTMnPd: 'daa520',
Way: '808080',
gYF: '8000',
gYFLw: 'adff2f',
gYy: '808080',
honeyMw: 'f0fff0',
hotpRk: 'ff69b4',
RdianYd: 'cd5c5c',
Rdigo: '4b0082',
ivSy: 'fffff0',
khaki: 'f0e68c',
lavFMr: 'e6e6fa',
lavFMrXsh: 'fff0f5',
lawngYF: '7cfc00',
NmoncEffon: 'fffacd',
ZXe: 'add8e6',
ZcSO: 'f08080',
Zcyan: 'e0ffff',
ZgTMnPdLw: 'fafad2',
ZWay: 'd3d3d3',
ZgYF: '90ee90',
ZgYy: 'd3d3d3',
ZpRk: 'ffb6c1',
ZsOmon: 'ffa07a',
ZsHgYF: '20b2aa',
ZskyXe: '87cefa',
ZUWay: '778899',
ZUgYy: '778899',
ZstAlXe: 'b0c4de',
ZLw: 'ffffe0',
lime: 'ff00',
limegYF: '32cd32',
lRF: 'faf0e6',
magFta: 'ff00ff',
maPon: '800000',
VaquamarRe: '66cdaa',
VXe: 'cd',
VScEd: 'ba55d3',
VpurpN: '9370db',
VsHgYF: '3cb371',
VUXe: '7b68ee',
VsprRggYF: 'fa9a',
VQe: '48d1cc',
VviTetYd: 'c71585',
midnightXe: '191970',
mRtcYam: 'f5fffa',
mistyPse: 'ffe4e1',
moccasR: 'ffe4b5',
navajowEte: 'ffdead',
navy: '80',
Tdlace: 'fdf5e6',
Tive: '808000',
TivedBb: '6b8e23',
Sange: 'ffa500',
SangeYd: 'ff4500',
ScEd: 'da70d6',
pOegTMnPd: 'eee8aa',
pOegYF: '98fb98',
pOeQe: 'afeeee',
pOeviTetYd: 'db7093',
papayawEp: 'ffefd5',
pHKpuff: 'ffdab9',
peru: 'cd853f',
pRk: 'ffc0cb',
plum: 'dda0dd',
powMrXe: 'b0e0e6',
purpN: '800080',
YbeccapurpN: '663399',
Yd: 'ff0000',
Psybrown: 'bc8f8f',
PyOXe: '4169e1',
saddNbPwn: '8b4513',
sOmon: 'fa8072',
sandybPwn: 'f4a460',
sHgYF: '2e8b57',
sHshell: 'fff5ee',
siFna: 'a0522d',
silver: 'c0c0c0',
skyXe: '87ceeb',
UXe: '6a5acd',
UWay: '708090',
UgYy: '708090',
snow: 'fffafa',
sprRggYF: 'ff7f',
stAlXe: '4682b4',
tan: 'd2b48c',
teO: '8080',
tEstN: 'd8bfd8',
tomato: 'ff6347',
Qe: '40e0d0',
viTet: 'ee82ee',
JHt: 'f5deb3',
wEte: 'ffffff',
wEtesmoke: 'f5f5f5',
Lw: 'ffff00',
LwgYF: '9acd32'
};
function unpack() {
const unpacked = {};
const keys = Object.keys(names$1);
const tkeys = Object.keys(map);
let i, j, k, ok, nk;
for (i = 0; i < keys.length; i++) {
ok = nk = keys[i];
for (j = 0; j < tkeys.length; j++) {
k = tkeys[j];
nk = nk.replace(k, map[k]);
}
k = parseInt(names$1[ok], 16);
unpacked[nk] = [k >> 16 & 0xFF, k >> 8 & 0xFF, k & 0xFF];
}
return unpacked;
}
let names;
function nameParse(str) {
if (!names) {
names = unpack();
names.transparent = [0, 0, 0, 0];
}
const a = names[str.toLowerCase()];
return a && {
r: a[0],
g: a[1],
b: a[2],
a: a.length === 4 ? a[3] : 255
};
}
const RGB_RE = /^rgba?\(\s*([-+.\d]+)(%)?[\s,]+([-+.e\d]+)(%)?[\s,]+([-+.e\d]+)(%)?(?:[\s,/]+([-+.e\d]+)(%)?)?\s*\)$/;
function rgbParse(str) {
const m = RGB_RE.exec(str);
let a = 255;
let r, g, b;
if (!m) {
return;
}
if (m[7] !== r) {
const v = +m[7];
a = m[8] ? p2b(v) : lim(v * 255, 0, 255);
}
r = +m[1];
g = +m[3];
b = +m[5];
r = 255 & (m[2] ? p2b(r) : lim(r, 0, 255));
g = 255 & (m[4] ? p2b(g) : lim(g, 0, 255));
b = 255 & (m[6] ? p2b(b) : lim(b, 0, 255));
return {
r: r,
g: g,
b: b,
a: a
};
}
function rgbString(v) {
return v && (
v.a < 255
? `rgba(${v.r}, ${v.g}, ${v.b}, ${b2n(v.a)})`
: `rgb(${v.r}, ${v.g}, ${v.b})`
);
}
const to = v => v <= 0.0031308 ? v * 12.92 : Math.pow(v, 1.0 / 2.4) * 1.055 - 0.055;
const from = v => v <= 0.04045 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
function interpolate(rgb1, rgb2, t) {
const r = from(b2n(rgb1.r));
const g = from(b2n(rgb1.g));
const b = from(b2n(rgb1.b));
return {
r: n2b(to(r + t * (from(b2n(rgb2.r)) - r))),
g: n2b(to(g + t * (from(b2n(rgb2.g)) - g))),
b: n2b(to(b + t * (from(b2n(rgb2.b)) - b))),
a: rgb1.a + t * (rgb2.a - rgb1.a)
};
}
function modHSL(v, i, ratio) {
if (v) {
let tmp = rgb2hsl(v);
tmp[i] = Math.max(0, Math.min(tmp[i] + tmp[i] * ratio, i === 0 ? 360 : 1));
tmp = hsl2rgb(tmp);
v.r = tmp[0];
v.g = tmp[1];
v.b = tmp[2];
}
}
function clone(v, proto) {
return v ? Object.assign(proto || {}, v) : v;
}
function fromObject(input) {
var v = {r: 0, g: 0, b: 0, a: 255};
if (Array.isArray(input)) {
if (input.length >= 3) {
v = {r: input[0], g: input[1], b: input[2], a: 255};
if (input.length > 3) {
v.a = n2b(input[3]);
}
}
} else {
v = clone(input, {r: 0, g: 0, b: 0, a: 1});
v.a = n2b(v.a);
}
return v;
}
function functionParse(str) {
if (str.charAt(0) === 'r') {
return rgbParse(str);
}
return hueParse(str);
}
class Color {
constructor(input) {
if (input instanceof Color) {
return input;
}
const type = typeof input;
let v;
if (type === 'object') {
v = fromObject(input);
} else if (type === 'string') {
v = hexParse(input) || nameParse(input) || functionParse(input);
}
this._rgb = v;
this._valid = !!v;
}
get valid() {
return this._valid;
}
get rgb() {
var v = clone(this._rgb);
if (v) {
v.a = b2n(v.a);
}
return v;
}
set rgb(obj) {
this._rgb = fromObject(obj);
}
rgbString() {
return this._valid ? rgbString(this._rgb) : undefined;
}
hexString() {
return this._valid ? hexString(this._rgb) : undefined;
}
hslString() {
return this._valid ? hslString(this._rgb) : undefined;
}
mix(color, weight) {
if (color) {
const c1 = this.rgb;
const c2 = color.rgb;
let w2;
const p = weight === w2 ? 0.5 : weight;
const w = 2 * p - 1;
const a = c1.a - c2.a;
const w1 = ((w * a === -1 ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
w2 = 1 - w1;
c1.r = 0xFF & w1 * c1.r + w2 * c2.r + 0.5;
c1.g = 0xFF & w1 * c1.g + w2 * c2.g + 0.5;
c1.b = 0xFF & w1 * c1.b + w2 * c2.b + 0.5;
c1.a = p * c1.a + (1 - p) * c2.a;
this.rgb = c1;
}
return this;
}
interpolate(color, t) {
if (color) {
this._rgb = interpolate(this._rgb, color._rgb, t);
}
return this;
}
clone() {
return new Color(this.rgb);
}
alpha(a) {
this._rgb.a = n2b(a);
return this;
}
clearer(ratio) {
const rgb = this._rgb;
rgb.a *= 1 - ratio;
return this;
}
greyscale() {
const rgb = this._rgb;
const val = round(rgb.r * 0.3 + rgb.g * 0.59 + rgb.b * 0.11);
rgb.r = rgb.g = rgb.b = val;
return this;
}
opaquer(ratio) {
const rgb = this._rgb;
rgb.a *= 1 + ratio;
return this;
}
negate() {
const v = this._rgb;
v.r = 255 - v.r;
v.g = 255 - v.g;
v.b = 255 - v.b;
return this;
}
lighten(ratio) {
modHSL(this._rgb, 2, ratio);
return this;
}
darken(ratio) {
modHSL(this._rgb, 2, -ratio);
return this;
}
saturate(ratio) {
modHSL(this._rgb, 1, ratio);
return this;
}
desaturate(ratio) {
modHSL(this._rgb, 1, -ratio);
return this;
}
rotate(deg) {
rotate(this._rgb, deg);
return this;
}
}
function index_esm(input) {
return new Color(input);
}
export { Color, b2n, b2p, index_esm as default, hexParse, hexString, hsl2rgb, hslString, hsv2rgb, hueParse, hwb2rgb, lim, n2b, n2p, nameParse, p2b, rgb2hsl, rgbParse, rgbString, rotate, round };
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+77
View File
@@ -0,0 +1,77 @@
{
"name": "@kurkle/color",
"type": "module",
"version": "0.3.4",
"description": "css color parsing, manupulation and conversion",
"sideEffects": false,
"main": "dist/color.cjs",
"module": "dist/color.esm.js",
"types": "dist/color.d.ts",
"exports": {
"types": "./dist/color.d.ts",
"import": "./dist/color.esm.js",
"require": "./dist/color.cjs"
},
"scripts": {
"build": "node util/copy_dist.js && rollup -c",
"lint": "eslint src/*.js test/*.js util/*.js",
"test": "node test/index.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/kurkle/color.git"
},
"files": [
"dist/*",
"dist/color.d.ts"
],
"keywords": [
"color",
"colour",
"css",
"hsl",
"hex",
"rgb",
"rgba",
"hwb",
"hsv",
"cmyk"
],
"author": "Jukka Kurkela",
"license": "MIT",
"bugs": {
"url": "https://github.com/kurkle/color/issues"
},
"homepage": "https://github.com/kurkle/color#readme",
"devDependencies": {
"@rollup/plugin-terser": "^0.4.0",
"assert": "^2.0.0",
"benchmark": "^2.1.4",
"chartjs-color": "^2.4.1",
"chartjs-color-string": "^0.6.0",
"child_process": "^1.0.2",
"chroma-js": "^3.1.1",
"color-name": "^2.0.0",
"color-names": "^2.0.0",
"color-parse": "^2.0.2",
"color-parser": "^0.1.0",
"color-string": "^1.5.5",
"csscolorparser": "^1.0.3",
"eslint": "^9.15.0",
"eslint-config-chartjs": "^0.3.0",
"eslint-config-defaults": "^9.0.0",
"eslint-plugin-import": "^2.22.1",
"eslint-plugin-react": "^7.22.0",
"fs": "0.0.1-security",
"perf_hooks": "0.0.1",
"rollup": "^4.25.0",
"rollup-plugin-analyzer": "^4.0.0",
"rollup-plugin-cleanup": "^3.2.1",
"rollup-plugin-istanbul": "^5.0.0",
"rollup-plugin-visualizer": "^5.8.3",
"tinycolor2": "^1.4.2",
"typedoc": "^0.26.7",
"typescript": "^5.6.2",
"util": "^0.12.3"
}
}
+22
View 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.
+543
View File
@@ -0,0 +1,543 @@
# 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 wrapper around webcrypto
- 🪶 29KB (11KB gzipped) for everything, 7KB (3KB gzipped) for ChaCha build
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),
4kb [secp256k1](https://github.com/paulmillr/noble-secp256k1) /
[ed25519](https://github.com/paulmillr/noble-ed25519)
- [Check out homepage](https://paulmillr.com/noble/)
for reading resources, documentation and apps built with noble
## Usage
> `npm install @noble/ciphers`
> `deno add jsr:@noble/ciphers`
> `deno doc jsr:@noble/ciphers` # command-line documentation
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, siv } from '@noble/ciphers/aes';
import { chacha20poly1305, xchacha20poly1305 } from '@noble/ciphers/chacha';
import { xsalsa20poly1305, secretbox } from '@noble/ciphers/salsa';
// Unauthenticated encryption: make sure to use HMAC or similar
import { ctr, cfb, cbc, ecb } from '@noble/ciphers/aes';
import { salsa20, xsalsa20 } from '@noble/ciphers/salsa';
import { chacha20, xchacha20, chacha8, chacha12 } from '@noble/ciphers/chacha';
import { aeskw, aeskwp } from '@noble/ciphers/aes'; // KW
import { bytesToHex, hexToBytes, bytesToUtf8, utf8ToBytes } from '@noble/ciphers/utils';
import { managedNonce, randomBytes } from '@noble/ciphers/webcrypto';
```
- [Examples](#examples)
- [XChaCha20-Poly1305 encryption](#xchacha20-poly1305-encryption)
- [AES-256-GCM encryption](#aes-256-gcm-encryption)
- [AES: gcm, siv, ctr, cfb, cbc, ecb](#aes-gcm-siv-ctr-cfb-cbc-ecb)
- [Friendly WebCrypto AES](#friendly-webcrypto-aes)
- [AESKW and AESKWP](#aeskw-and-aeskwp)
- [Auto-handle nonces](#auto-handle-nonces)
- [Reuse array for input and output](#reuse-array-for-input-and-output)
- [Internals](#internals)
- [Implemented primitives](#implemented-primitives)
- [Which cipher should I pick?](#which-cipher-should-i-pick)
- [How to encrypt properly](#how-to-encrypt-properly)
- [Nonces](#nonces)
- [Encryption limits](#encryption-limits)
- [AES internals and block modes](#aes-internals-and-block-modes)
- [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';
import { utf8ToBytes } from '@noble/ciphers/utils';
import { randomBytes } from '@noble/ciphers/webcrypto';
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'; // hex key
// const key = hexToBytes('4b7f89bac90a1086fef73f5da2cbe93b2fae9dfbf7678ae1f3e75fd118ddf999');
const nonce = randomBytes(24);
const chacha = xchacha20poly1305(key, nonce);
const data = utf8ToBytes('hello, noble');
const ciphertext = chacha.encrypt(data);
const data_ = chacha.decrypt(ciphertext); // utils.bytesToUtf8(data_) === data
```
#### AES-256-GCM encryption
```js
import { gcm } from '@noble/ciphers/aes';
import { utf8ToBytes } from '@noble/ciphers/utils';
import { randomBytes } from '@noble/ciphers/webcrypto';
const key = randomBytes(32);
const nonce = randomBytes(24);
const data = utf8ToBytes('hello, noble');
const aes = gcm(key, nonce);
const ciphertext = aes.encrypt(data);
const data_ = aes.decrypt(ciphertext); // utils.bytesToUtf8(data_) === data
```
#### AES: gcm, siv, ctr, cfb, cbc, ecb
```js
import { gcm, siv, ctr, cfb, cbc, ecb } from '@noble/ciphers/aes';
import { randomBytes } from '@noble/ciphers/webcrypto';
const plaintext = new Uint8Array(32).fill(16);
for (let cipher of [gcm, siv]) {
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_);
}
```
#### Friendly WebCrypto AES
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, randomBytes } from '@noble/ciphers/webcrypto';
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_);
}
```
#### AESKW and AESKWP
```ts
import { aeskw, aeskwp } from '@noble/ciphers/aes';
import { hexToBytes } from '@noble/ciphers/utils';
const kek = hexToBytes('000102030405060708090A0B0C0D0E0F');
const keyData = hexToBytes('00112233445566778899AABBCCDDEEFF');
const ciphertext = aeskw(kek).encrypt(keyData);
```
#### Auto-handle nonces
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.
```js
import { xchacha20poly1305 } from '@noble/ciphers/chacha';
import { managedNonce } from '@noble/ciphers/webcrypto';
import { hexToBytes, utf8ToBytes } from '@noble/ciphers/utils';
const key = hexToBytes('fa686bfdffd3758f6377abbc23bf3d9bdc1a0dda4a6e7f8dbdd579fa1ff6d7e1');
const chacha = managedNonce(xchacha20poly1305)(key); // manages nonces for you
const data = utf8ToBytes('hello, noble');
const ciphertext = chacha.encrypt(data);
const data_ = chacha.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';
import { utf8ToBytes } from '@noble/ciphers/utils';
import { randomBytes } from '@noble/ciphers/webcrypto';
const key = randomBytes(32);
const nonce = randomBytes(12);
const chacha = chacha20poly1305(key, nonce);
const input = utf8ToBytes('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.
## Internals
### Implemented primitives
- [Salsa20](https://cr.yp.to/snuffle.html) 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", a simple black-box
authenticated encryption. Secretbox is just xsalsa20-poly1305. We provide the
alias and corresponding seal / open methods. We don't provide "box" or "sealedbox".
- Check out [PDF](https://cr.yp.to/snuffle/salsafamily-20071225.pdf) and
[wiki](https://en.wikipedia.org/wiki/Salsa20).
- [ChaCha20](https://cr.yp.to/chacha.html) stream cipher, released
in 2008. Developed after Salsa20, ChaCha aims to increase diffusion per round.
It was standardized in [RFC 8439](https://datatracker.ietf.org/doc/html/rfc8439)
and is now used in TLS 1.3.
- [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 [PDF](http://cr.yp.to/chacha/chacha-20080128.pdf) and [wiki](https://en.wikipedia.org/wiki/Salsa20).
- [AES](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard)
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](https://en.wikipedia.org/wiki/AES-GCM-SIV)
nonce-misuse-resistant mode is also provided. It's recommended to use it,
to prevent catastrophic consequences of nonce reuse. Our implementation of SIV
has the same speed as GCM: there is no performance hit.
- We also have AESKW and AESKWP from
[RFC 3394](https://datatracker.ietf.org/doc/html/rfc3394) / [RFC 5649](https://datatracker.ietf.org/doc/html/rfc5649)
- Check out [AES internals and block modes](#aes-internals-and-block-modes).
- We expose polynomial-evaluation MACs: [Poly1305](https://cr.yp.to/mac.html), AES-GCM's [GHash](https://en.wikipedia.org/wiki/Galois/Counter_Mode) and
AES-SIV's [Polyval](https://en.wikipedia.org/wiki/AES-GCM-SIV).
- Poly1305 ([PDF](https://cr.yp.to/mac/poly1305-20050329.pdf),
[wiki](https://en.wikipedia.org/wiki/Poly1305))
is a fast and parallel secret-key message-authentication code suitable for
a wide variety of applications. It was standardized in
[RFC 8439](https://datatracker.ietf.org/doc/html/rfc8439) 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
[invisible salamanders attack](https://keymaterial.net/2020/09/07/invisible-salamanders-in-aes-gcm-siv/).
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.
- Format-preserving encryption algorithm (FPE-FF1) specified in NIST Special Publication 800-38G.
[See more info](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf).
### Which cipher should I pick?
We suggest to use XChaCha20-Poly1305.
If you can't use it, prefer AES-GCM-SIV, or AES-GCM.
### 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 should use random nonces instead
- AES-GCM should use 12-byte nonces: smaller nonces are security risk
- Prefer authenticated encryption (AEAD)
- chacha20poly1305 / aes-gcm / ChaCha + HMAC / AES + HMAC is good
- chacha20 / aes-ctr / aes-cbc without poly1305 or hmac is bad
- Flipping bits or ciphertext substitution won't be detected in unauthenticated ciphers
- Don't re-use keys between different protocols
- For example, using secp256k1 key in AES can be bad
- Use hkdf or, at least, a hash function to create sub-key instead
- If you need AES, only use AES-256 for new protocols
- For post-quantum security
### Nonces
Most ciphers need a key and a nonce (aka initialization vector / IV) to encrypt a data:
ciphertext = encrypt(plaintext, key, nonce)
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
So, you can't repeat nonces. One way of doing so 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. See [draft-irtf-cfrg-aead-limits](https://datatracker.ietf.org/doc/draft-irtf-cfrg-aead-limits/) for details.
- 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 is affected, not confidentiality
- 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`
##### AES internals and block modes
`cipher = encrypt(block, key)`. Data is split into 128-bit blocks. Encrypted in 10/12/14 rounds (128/192/256bit). Every round does:
1. **S-box**, table substitution
2. **Shift rows**, cyclic shift left of all rows of data array
3. **Mix columns**, multiplying every column by fixed polynomial
4. **Add round key**, round_key xor i-th column of array
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. Insecure 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 ciphertext block before encryption.
Hard to use: requires proper padding and an IV. Needs a separate 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. Better, but still needs a separate MAC.
- GCM (Galois/Counter Mode): Combines CTR mode with polynomial MAC. Efficient and widely used.
- SIV (Synthetic IV): Nonce-misuse-resistant mode; repeating nonces reveal only if plaintexts are identical.
Maintains security even if nonces are reused.
- 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.
GCM / SIV are not ideal:
- Conservative key wear-out is `2**32` (4B) msgs
- MAC can be forged: see Poly1305 section above. Same for SIV
## Security
The library has been independently audited:
- at version 1.0.0, in Sep 2024, 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. Make sure to verify commit signatures
- **Releases** are transparent and built on GitHub CI. Make sure to verify [provenance](https://docs.npmjs.com/generating-provenance-statements) logs
- Use GitHub CLI to verify single-file builds:
`gh attestation verify --owner paulmillr noble-ciphers.js`
- **Rare releasing** is followed to ensure less re-audit need for end-users
- **Dependencies** are minimized and locked-down: any dependency could get hacked and users will be downloading malware with every install.
- We make sure to use as few dependencies as possible
- Automatic dep updates are prevented by locking-down version ranges; diffs are checked with `npm-diff`
- **Dev Dependencies** are disabled for end-users; they are only used to develop / build the source code
For this package, there are 0 dependencies; and a few dev dependencies:
- micro-bmark, micro-should and jsbt are 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. It's hard to audit their source code thoroughly and fully because of their size
### Randomness
We're deferring to built-in
[crypto.getRandomValues](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues)
which is considered cryptographically secure (CSPRNG).
In the past, browsers had bugs that made it weak: it may happen again.
Implementing a userspace CSPRNG to get resilient to the weakness
is even worse: there is no reliable userspace source of quality entropy.
## Speed
To summarize, noble is the fastest JS implementation of Salsa, ChaCha and AES.
You can gain additional speed-up and
avoid memory allocations by passing `output`
uint8array into encrypt / decrypt methods.
Benchmark results on Apple M4:
```
64B
xsalsa20poly1305 x 675,675 ops/sec @ 1μs/op
chacha20poly1305 x 568,181 ops/sec @ 1μs/op
xchacha20poly1305 x 460,617 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 322 ops/sec @ 3ms/op
chacha20poly1305 x 327 ops/sec @ 3ms/op
xchacha20poly1305 x 331 ops/sec @ 3ms/op
aes-256-gcm x 94 ops/sec @ 10ms/op
aes-256-gcm-siv x 90 ops/sec @ 11ms/op
# Unauthenticated encryption
salsa20 x 791 ops/sec @ 1ms/op
xsalsa20 x 801 ops/sec @ 1ms/op
chacha20 x 787 ops/sec @ 1ms/op
xchacha20 x 781 ops/sec @ 1ms/op
chacha8 x 1,457 ops/sec @ 686μs/op
chacha12 x 1,130 ops/sec @ 884μ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 ops/sec
└─noble x 305 ops/sec
chacha20poly1305 (encrypt, 1MB)
├─node x 1,668 ops/sec
├─stablelib x 202 ops/sec
└─noble x 319 ops/sec
aes-ctr-256 (encrypt, 1MB)
├─stablelib x 123 ops/sec
├─aesjs x 42 ops/sec
├─noble-webcrypto x 5,965 ops/sec
└─noble x 124 ops/sec
```
## 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, which may need their deps first (`npm run bench:install`)
- `npm run build:release` will build single file
Check out [github.com/paulmillr/guidelines](https://github.com/paulmillr/guidelines)
for general coding practices and rules.
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.
+59
View File
@@ -0,0 +1,59 @@
/**
* 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) | ctr(2) | s[2] | k(4) | s[3]
chacha: s(4) | k(8) | ctr(1) | nonce(3)
chacha20orig: s(4) | k(8) | ctr(2) | nonce(2)
- Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)`
- Caveat: we can't re-use counter array
xchacha [^2] uses the subkey and remaining 8 byte nonce with ChaCha20 as normal
(prefixed by 4 NUL bytes, since [RFC8439] specifies a 12-byte nonce).
[^1]: https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/
[^2]: https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2
* @module
*/
import { type XorStream } from './utils.ts';
export declare function rotl(a: number, b: number): number;
/** Ciphers must use u32 for efficiency. */
export type CipherCoreFn = (sigma: Uint32Array, key: Uint32Array, nonce: Uint32Array, output: Uint32Array, counter: number, rounds?: number) => void;
/** Method which extends key + short nonce into larger nonce / diff key. */
export type ExtendNonceFn = (sigma: Uint32Array, key: Uint32Array, input: Uint32Array, output: Uint32Array) => void;
/** ARX cipher options.
* * `allowShortKeys` for 16-byte keys
* * `counterLength` in bytes
* * `counterRight`: right: `nonce|counter`; left: `counter|nonce`
* */
export type CipherOpts = {
allowShortKeys?: boolean;
extendNonceFn?: ExtendNonceFn;
counterLength?: number;
counterRight?: boolean;
rounds?: number;
};
/** Creates ARX-like (ChaCha, Salsa) cipher stream from core function. */
export declare function createCipher(core: CipherCoreFn, opts: CipherOpts): XorStream;
//# sourceMappingURL=_arx.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"_arx.d.ts","sourceRoot":"","sources":["src/_arx.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AAEH,OAAO,EACL,KAAK,SAAS,EACf,MAAM,YAAY,CAAC;AAUpB,wBAAgB,IAAI,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CAEjD;AAED,2CAA2C;AAC3C,MAAM,MAAM,YAAY,GAAG,CACzB,KAAK,EAAE,WAAW,EAClB,GAAG,EAAE,WAAW,EAChB,KAAK,EAAE,WAAW,EAClB,MAAM,EAAE,WAAW,EACnB,OAAO,EAAE,MAAM,EACf,MAAM,CAAC,EAAE,MAAM,KACZ,IAAI,CAAC;AAEV,2EAA2E;AAC3E,MAAM,MAAM,aAAa,GAAG,CAC1B,KAAK,EAAE,WAAW,EAClB,GAAG,EAAE,WAAW,EAChB,KAAK,EAAE,WAAW,EAClB,MAAM,EAAE,WAAW,KAChB,IAAI,CAAC;AAEV;;;;KAIK;AACL,MAAM,MAAM,UAAU,GAAG;IACvB,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,aAAa,CAAC,EAAE,aAAa,CAAC;IAC9B,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,CAAC;AAwDF,yEAAyE;AACzE,wBAAgB,YAAY,CAAC,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,UAAU,GAAG,SAAS,CAkF5E"}
+175
View File
@@ -0,0 +1,175 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.rotl = rotl;
exports.createCipher = createCipher;
/**
* 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) | ctr(2) | s[2] | k(4) | s[3]
chacha: s(4) | k(8) | ctr(1) | nonce(3)
chacha20orig: s(4) | k(8) | ctr(2) | nonce(2)
- Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)`
- Caveat: we can't re-use counter array
xchacha [^2] uses the subkey and remaining 8 byte nonce with ChaCha20 as normal
(prefixed by 4 NUL bytes, since [RFC8439] specifies a 12-byte nonce).
[^1]: https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/
[^2]: https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2
* @module
*/
// prettier-ignore
const utils_ts_1 = require("./utils.js");
// We can't make top-level var depend on utils.utf8ToBytes
// because it's not present in all envs. Creating a similar fn here
const _utf8ToBytes = (str) => Uint8Array.from(str.split('').map((c) => c.charCodeAt(0)));
const sigma16 = _utf8ToBytes('expand 16-byte k');
const sigma32 = _utf8ToBytes('expand 32-byte k');
const sigma16_32 = (0, utils_ts_1.u32)(sigma16);
const sigma32_32 = (0, utils_ts_1.u32)(sigma32);
function rotl(a, b) {
return (a << b) | (a >>> (32 - b));
}
// Is byte array aligned to 4 byte offset (u32)?
function isAligned32(b) {
return b.byteOffset % 4 === 0;
}
// Salsa and Chacha block length is always 512-bit
const BLOCK_LEN = 64;
const BLOCK_LEN32 = 16;
// new Uint32Array([2**32]) // => Uint32Array(1) [ 0 ]
// new Uint32Array([2**32-1]) // => Uint32Array(1) [ 4294967295 ]
const MAX_COUNTER = 2 ** 32 - 1;
const U32_EMPTY = new Uint32Array();
function runCipher(core, sigma, key, nonce, data, output, counter, rounds) {
const len = data.length;
const block = new Uint8Array(BLOCK_LEN);
const b32 = (0, utils_ts_1.u32)(block);
// Make sure that buffers aligned to 4 bytes
const isAligned = isAligned32(data) && isAligned32(output);
const d32 = isAligned ? (0, utils_ts_1.u32)(data) : U32_EMPTY;
const o32 = isAligned ? (0, utils_ts_1.u32)(output) : U32_EMPTY;
for (let pos = 0; pos < len; counter++) {
core(sigma, key, nonce, b32, counter, rounds);
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 ARX-like (ChaCha, Salsa) cipher stream from core function. */
function createCipher(core, opts) {
const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = (0, utils_ts_1.checkOpts)({ allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 }, opts);
if (typeof core !== 'function')
throw new Error('core must be a function');
(0, utils_ts_1.anumber)(counterLength);
(0, utils_ts_1.anumber)(rounds);
(0, utils_ts_1.abool)(counterRight);
(0, utils_ts_1.abool)(allowShortKeys);
return (key, nonce, data, output, counter = 0) => {
(0, utils_ts_1.abytes)(key);
(0, utils_ts_1.abytes)(nonce);
(0, utils_ts_1.abytes)(data);
const len = data.length;
if (output === undefined)
output = new Uint8Array(len);
(0, utils_ts_1.abytes)(output);
(0, utils_ts_1.anumber)(counter);
if (counter < 0 || counter >= MAX_COUNTER)
throw new Error('arx: counter overflow');
if (output.length < len)
throw new Error(`arx: output (${output.length}) is shorter than data (${len})`);
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) {
toClean.push((k = (0, utils_ts_1.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 {
throw new Error(`arx: invalid 32-byte key, 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)
// Align nonce to 4 bytes
if (!isAligned32(nonce))
toClean.push((nonce = (0, utils_ts_1.copyBytes)(nonce)));
const k32 = (0, utils_ts_1.u32)(k);
// hsalsa & hchacha: handle extended nonce
if (extendNonceFn) {
if (nonce.length !== 24)
throw new Error(`arx: extended nonce must be 24 bytes`);
extendNonceFn(sigma, k32, (0, utils_ts_1.u32)(nonce.subarray(0, 16)), k32);
nonce = nonce.subarray(16);
}
// Handle nonce counter
const nonceNcLen = 16 - counterLength;
if (nonceNcLen !== nonce.length)
throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);
// Pad counter when nonce is 64 bit
if (nonceNcLen !== 12) {
const nc = new Uint8Array(12);
nc.set(nonce, counterRight ? 0 : 12 - nonce.length);
nonce = nc;
toClean.push(nonce);
}
const n32 = (0, utils_ts_1.u32)(nonce);
runCipher(core, sigma, k32, n32, data, output, counter, rounds);
(0, utils_ts_1.clean)(...toClean);
return output;
};
}
//# sourceMappingURL=_arx.js.map
File diff suppressed because one or more lines are too long
+19
View File
@@ -0,0 +1,19 @@
/**
* Internal assertion helpers.
* @module
* @deprecated
*/
import { abytes as ab, abool as abool_, aexists as ae, anumber as an, aoutput as ao, type IHash as H } from './utils.ts';
/** @deprecated Use import from `noble/hashes/utils` module */
export declare const abool: typeof abool_;
/** @deprecated Use import from `noble/hashes/utils` module */
export declare const abytes: typeof ab;
/** @deprecated Use import from `noble/hashes/utils` module */
export declare const aexists: typeof ae;
/** @deprecated Use import from `noble/hashes/utils` module */
export declare const anumber: typeof an;
/** @deprecated Use import from `noble/hashes/utils` module */
export declare const aoutput: typeof ao;
/** @deprecated Use import from `noble/hashes/utils` module */
export type Hash = H;
//# sourceMappingURL=_assert.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"_assert.d.ts","sourceRoot":"","sources":["src/_assert.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EACL,MAAM,IAAI,EAAE,EACZ,KAAK,IAAI,MAAM,EACf,OAAO,IAAI,EAAE,EACb,OAAO,IAAI,EAAE,EACb,OAAO,IAAI,EAAE,EACb,KAAK,KAAK,IAAI,CAAC,EAChB,MAAM,YAAY,CAAC;AACpB,8DAA8D;AAC9D,eAAO,MAAM,KAAK,EAAE,OAAO,MAAe,CAAC;AAC3C,8DAA8D;AAC9D,eAAO,MAAM,MAAM,EAAE,OAAO,EAAO,CAAC;AACpC,8DAA8D;AAC9D,eAAO,MAAM,OAAO,EAAE,OAAO,EAAO,CAAC;AACrC,8DAA8D;AAC9D,eAAO,MAAM,OAAO,EAAE,OAAO,EAAO,CAAC;AACrC,8DAA8D;AAC9D,eAAO,MAAM,OAAO,EAAE,OAAO,EAAO,CAAC;AACrC,8DAA8D;AAC9D,MAAM,MAAM,IAAI,GAAG,CAAC,CAAC"}
+20
View File
@@ -0,0 +1,20 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.aoutput = exports.anumber = exports.aexists = exports.abytes = exports.abool = void 0;
/**
* Internal assertion helpers.
* @module
* @deprecated
*/
const utils_ts_1 = require("./utils.js");
/** @deprecated Use import from `noble/hashes/utils` module */
exports.abool = utils_ts_1.abool;
/** @deprecated Use import from `noble/hashes/utils` module */
exports.abytes = utils_ts_1.abytes;
/** @deprecated Use import from `noble/hashes/utils` module */
exports.aexists = utils_ts_1.aexists;
/** @deprecated Use import from `noble/hashes/utils` module */
exports.anumber = utils_ts_1.anumber;
/** @deprecated Use import from `noble/hashes/utils` module */
exports.aoutput = utils_ts_1.aoutput;
//# sourceMappingURL=_assert.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"_assert.js","sourceRoot":"","sources":["src/_assert.ts"],"names":[],"mappings":";;;AAAA;;;;GAIG;AACH,yCAOoB;AACpB,8DAA8D;AACjD,QAAA,KAAK,GAAkB,gBAAM,CAAC;AAC3C,8DAA8D;AACjD,QAAA,MAAM,GAAc,iBAAE,CAAC;AACpC,8DAA8D;AACjD,QAAA,OAAO,GAAc,kBAAE,CAAC;AACrC,8DAA8D;AACjD,QAAA,OAAO,GAAc,kBAAE,CAAC;AACrC,8DAA8D;AACjD,QAAA,OAAO,GAAc,kBAAE,CAAC"}
+41
View File
@@ -0,0 +1,41 @@
import { type Cipher, type XorStream } from './utils.ts';
export type ARXCipherN = ((key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array) => Cipher) & {
blockSize: number;
nonceLength: number;
tagLength: number;
};
/** hsalsa hashes key and nonce into key' and nonce'. */
export declare function hsalsa(s: Uint32Array, k: Uint32Array, i: Uint32Array, o32: Uint32Array): void;
/** hchacha hashes key and nonce into key' and nonce'. */
export declare function hchacha(s: Uint32Array, k: Uint32Array, i: Uint32Array, o32: Uint32Array): void;
/** salsa20, 12-byte nonce. */
export declare const salsa20: XorStream;
/** xsalsa20, 24-byte nonce. */
export declare const xsalsa20: XorStream;
/** chacha20 non-RFC, original version by djb. 8-byte nonce, 8-byte counter. */
export declare const chacha20orig: XorStream;
/** chacha20 RFC 8439 (IETF / TLS). 12-byte nonce, 4-byte counter. */
export declare const chacha20: XorStream;
/** xchacha20 eXtended-nonce. https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha */
export declare const xchacha20: XorStream;
/** 8-round chacha from the original paper. */
export declare const chacha8: XorStream;
/** 12-round chacha from the original paper. */
export declare const chacha12: XorStream;
/** Poly1305 polynomial MAC. Can be speed-up using BigUint64Array, at the cost of complexity. */
export declare function poly1305(msg: Uint8Array, key: Uint8Array): Uint8Array;
/** xsalsa20-poly1305 eXtended-nonce (24 bytes) salsa. */
export declare const xsalsa20poly1305: ARXCipherN;
/** Alias to `xsalsa20poly1305`. */
export declare function secretbox(key: Uint8Array, nonce: Uint8Array): {
seal: (plaintext: Uint8Array) => Uint8Array;
open: (ciphertext: Uint8Array) => Uint8Array;
};
export declare const _poly1305_aead: (fn: XorStream) => (key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array) => Cipher;
/** chacha20-poly1305 12-byte-nonce chacha. */
export declare const chacha20poly1305: ARXCipherN;
/**
* XChaCha20-Poly1305 extended-nonce chacha. Can be safely used with random nonces (CSPRNG).
*/
export declare const xchacha20poly1305: ARXCipherN;
//# sourceMappingURL=_micro.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"_micro.d.ts","sourceRoot":"","sources":["src/_micro.ts"],"names":[],"mappings":"AASA,OAAO,EACL,KAAK,MAAM,EACX,KAAK,SAAS,EASf,MAAM,YAAY,CAAC;AAEpB,MAAM,MAAM,UAAU,GAAG,CAAC,CAAC,GAAG,EAAE,UAAU,EAAE,KAAK,EAAE,UAAU,EAAE,GAAG,CAAC,EAAE,UAAU,KAAK,MAAM,CAAC,GAAG;IAC5F,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,MAAM,CAAC;CACnB,CAAC;AAuEF,wDAAwD;AAExD,wBAAgB,MAAM,CAAC,CAAC,EAAE,WAAW,EAAE,CAAC,EAAE,WAAW,EAAE,CAAC,EAAE,WAAW,EAAE,GAAG,EAAE,WAAW,GAAG,IAAI,CAa7F;AAsBD,yDAAyD;AAEzD,wBAAgB,OAAO,CAAC,CAAC,EAAE,WAAW,EAAE,CAAC,EAAE,WAAW,EAAE,CAAC,EAAE,WAAW,EAAE,GAAG,EAAE,WAAW,GAAG,IAAI,CAa9F;AAED,8BAA8B;AAC9B,eAAO,MAAM,OAAO,EAAE,SAGpB,CAAC;AAEH,+BAA+B;AAC/B,eAAO,MAAM,QAAQ,EAAE,SAGrB,CAAC;AAEH,+EAA+E;AAC/E,eAAO,MAAM,YAAY,EAAE,SAIzB,CAAC;AAEH,qEAAqE;AACrE,eAAO,MAAM,QAAQ,EAAE,SAGrB,CAAC;AAEH,8FAA8F;AAC9F,eAAO,MAAM,SAAS,EAAE,SAItB,CAAC;AAEH,8CAA8C;AAC9C,eAAO,MAAM,OAAO,EAAE,SAIpB,CAAC;AAEH,+CAA+C;AAC/C,eAAO,MAAM,QAAQ,EAAE,SAIrB,CAAC;AAQH,gGAAgG;AAChG,wBAAgB,QAAQ,CAAC,GAAG,EAAE,UAAU,EAAE,GAAG,EAAE,UAAU,GAAG,UAAU,CAcrE;AAuBD,yDAAyD;AACzD,eAAO,MAAM,gBAAgB,EAAE,UAsB9B,CAAC;AAEF,mCAAmC;AACnC,wBAAgB,SAAS,CACvB,GAAG,EAAE,UAAU,EACf,KAAK,EAAE,UAAU,GAChB;IACD,IAAI,EAAE,CAAC,SAAS,EAAE,UAAU,KAAK,UAAU,CAAC;IAC5C,IAAI,EAAE,CAAC,UAAU,EAAE,UAAU,KAAK,UAAU,CAAC;CAC9C,CAGA;AAED,eAAO,MAAM,cAAc,GACxB,IAAI,SAAS,MACb,KAAK,UAAU,EAAE,OAAO,UAAU,EAAE,MAAM,UAAU,KAAG,MAgBvD,CAAC;AAEJ,8CAA8C;AAC9C,eAAO,MAAM,gBAAgB,EAAE,UAG9B,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,iBAAiB,EAAE,UAG/B,CAAC"}
+260
View File
@@ -0,0 +1,260 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.xchacha20poly1305 = exports.chacha20poly1305 = exports._poly1305_aead = exports.xsalsa20poly1305 = exports.chacha12 = exports.chacha8 = exports.xchacha20 = exports.chacha20 = exports.chacha20orig = exports.xsalsa20 = exports.salsa20 = void 0;
exports.hsalsa = hsalsa;
exports.hchacha = hchacha;
exports.poly1305 = poly1305;
exports.secretbox = secretbox;
/**
* noble-ciphers-micro: more auditable, but 4x slower version of salsa20, chacha & poly1305.
* Implements the same algorithms that are present in other files, but without
* unrolled loops (https://en.wikipedia.org/wiki/Loop_unrolling).
* @module
*/
/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
// prettier-ignore
const _arx_ts_1 = require("./_arx.js");
const utils_ts_1 = require("./utils.js");
function bytesToNumberLE(bytes) {
(0, utils_ts_1.abytes)(bytes);
return (0, utils_ts_1.hexToNumber)((0, utils_ts_1.bytesToHex)(Uint8Array.from(bytes).reverse()));
}
function numberToBytesLE(n, len) {
return (0, utils_ts_1.numberToBytesBE)(n, len).reverse();
}
function salsaQR(x, a, b, c, d) {
x[b] ^= (0, _arx_ts_1.rotl)((x[a] + x[d]) | 0, 7);
x[c] ^= (0, _arx_ts_1.rotl)((x[b] + x[a]) | 0, 9);
x[d] ^= (0, _arx_ts_1.rotl)((x[c] + x[b]) | 0, 13);
x[a] ^= (0, _arx_ts_1.rotl)((x[d] + x[c]) | 0, 18);
}
// prettier-ignore
function chachaQR(x, a, b, c, d) {
x[a] = (x[a] + x[b]) | 0;
x[d] = (0, _arx_ts_1.rotl)(x[d] ^ x[a], 16);
x[c] = (x[c] + x[d]) | 0;
x[b] = (0, _arx_ts_1.rotl)(x[b] ^ x[c], 12);
x[a] = (x[a] + x[b]) | 0;
x[d] = (0, _arx_ts_1.rotl)(x[d] ^ x[a], 8);
x[c] = (x[c] + x[d]) | 0;
x[b] = (0, _arx_ts_1.rotl)(x[b] ^ x[c], 7);
}
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);
}
}
function chachaRound(x, rounds = 20) {
for (let r = 0; r < rounds; r += 2) {
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);
}
}
function salsaCore(s, k, n, out, cnt, rounds = 20) {
// prettier-ignore
const y = new Uint32Array([
s[0], k[0], k[1], k[2], // "expa" Key Key Key
k[3], s[1], n[0], n[1], // Key "nd 3" Nonce Nonce
cnt, 0, s[2], k[4], // Pos. Pos. "2-by" Key
k[5], k[6], k[7], s[3], // Key Key Key "te k"
]);
const x = y.slice();
salsaRound(x, rounds);
for (let i = 0; i < 16; i++)
out[i] = (y[i] + x[i]) | 0;
}
/** hsalsa hashes key and nonce into key' and nonce'. */
// prettier-ignore
function hsalsa(s, k, i, o32) {
const x = new Uint32Array([
s[0], k[0], k[1], k[2],
k[3], s[1], i[0], i[1],
i[2], i[3], s[2], k[4],
k[5], k[6], k[7], s[3]
]);
salsaRound(x, 20);
let oi = 0;
o32[oi++] = x[0];
o32[oi++] = x[5];
o32[oi++] = x[10];
o32[oi++] = x[15];
o32[oi++] = x[6];
o32[oi++] = x[7];
o32[oi++] = x[8];
o32[oi++] = x[9];
}
function chachaCore(s, k, n, out, cnt, rounds = 20) {
// prettier-ignore
const y = new Uint32Array([
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
cnt, n[0], n[1], n[2], // Counter Counter Nonce Nonce
]);
const x = y.slice();
chachaRound(x, rounds);
for (let i = 0; i < 16; i++)
out[i] = (y[i] + x[i]) | 0;
}
/** hchacha hashes key and nonce into key' and nonce'. */
// prettier-ignore
function hchacha(s, k, i, o32) {
const x = new Uint32Array([
s[0], s[1], s[2], s[3],
k[0], k[1], k[2], k[3],
k[4], k[5], k[6], k[7],
i[0], i[1], i[2], i[3],
]);
chachaRound(x, 20);
let oi = 0;
o32[oi++] = x[0];
o32[oi++] = x[1];
o32[oi++] = x[2];
o32[oi++] = x[3];
o32[oi++] = x[12];
o32[oi++] = x[13];
o32[oi++] = x[14];
o32[oi++] = x[15];
}
/** salsa20, 12-byte nonce. */
exports.salsa20 = (0, _arx_ts_1.createCipher)(salsaCore, {
allowShortKeys: true,
counterRight: true,
});
/** xsalsa20, 24-byte nonce. */
exports.xsalsa20 = (0, _arx_ts_1.createCipher)(salsaCore, {
counterRight: true,
extendNonceFn: hsalsa,
});
/** chacha20 non-RFC, original version by djb. 8-byte nonce, 8-byte counter. */
exports.chacha20orig = (0, _arx_ts_1.createCipher)(chachaCore, {
allowShortKeys: true,
counterRight: false,
counterLength: 8,
});
/** chacha20 RFC 8439 (IETF / TLS). 12-byte nonce, 4-byte counter. */
exports.chacha20 = (0, _arx_ts_1.createCipher)(chachaCore, {
counterRight: false,
counterLength: 4,
});
/** xchacha20 eXtended-nonce. https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha */
exports.xchacha20 = (0, _arx_ts_1.createCipher)(chachaCore, {
counterRight: false,
counterLength: 8,
extendNonceFn: hchacha,
});
/** 8-round chacha from the original paper. */
exports.chacha8 = (0, _arx_ts_1.createCipher)(chachaCore, {
counterRight: false,
counterLength: 4,
rounds: 8,
});
/** 12-round chacha from the original paper. */
exports.chacha12 = (0, _arx_ts_1.createCipher)(chachaCore, {
counterRight: false,
counterLength: 4,
rounds: 12,
});
const POW_2_130_5 = BigInt(2) ** BigInt(130) - BigInt(5);
const POW_2_128_1 = BigInt(2) ** BigInt(16 * 8) - BigInt(1);
const CLAMP_R = BigInt('0x0ffffffc0ffffffc0ffffffc0fffffff');
const _0 = BigInt(0);
const _1 = BigInt(1);
/** Poly1305 polynomial MAC. Can be speed-up using BigUint64Array, at the cost of complexity. */
function poly1305(msg, key) {
(0, utils_ts_1.abytes)(msg);
(0, utils_ts_1.abytes)(key, 32);
let acc = _0;
const r = bytesToNumberLE(key.subarray(0, 16)) & CLAMP_R;
const s = bytesToNumberLE(key.subarray(16));
// Process by 16 byte chunks
for (let i = 0; i < msg.length; i += 16) {
const m = msg.subarray(i, i + 16);
const n = bytesToNumberLE(m) | (_1 << BigInt(8 * m.length));
acc = ((acc + n) * r) % POW_2_130_5;
}
const res = (acc + s) & POW_2_128_1;
return numberToBytesLE(res, 16);
}
function computeTag(fn, key, nonce, ciphertext, AAD) {
const res = [];
if (AAD) {
res.push(AAD);
const leftover = AAD.length % 16;
if (leftover > 0)
res.push(new Uint8Array(16 - leftover));
}
res.push(ciphertext);
const leftover = ciphertext.length % 16;
if (leftover > 0)
res.push(new Uint8Array(16 - leftover));
res.push((0, utils_ts_1.u64Lengths)(ciphertext.length, AAD ? AAD.length : 0, true));
const authKey = fn(key, nonce, new Uint8Array(32));
return poly1305((0, utils_ts_1.concatBytes)(...res), authKey);
}
/** xsalsa20-poly1305 eXtended-nonce (24 bytes) salsa. */
exports.xsalsa20poly1305 = (0, utils_ts_1.wrapCipher)({ blockSize: 64, nonceLength: 24, tagLength: 16 }, function xsalsapoly(key, nonce) {
return {
encrypt(plaintext) {
const m = (0, utils_ts_1.concatBytes)(new Uint8Array(32), plaintext);
const c = (0, exports.xsalsa20)(key, nonce, m);
const authKey = c.subarray(0, 32);
const data = c.subarray(32);
const tag = poly1305(data, authKey);
return (0, utils_ts_1.concatBytes)(tag, data);
},
decrypt(ciphertext) {
const c = (0, utils_ts_1.concatBytes)(new Uint8Array(16), ciphertext);
const passedTag = c.subarray(16, 32);
const authKey = (0, exports.xsalsa20)(key, nonce, new Uint8Array(32));
const tag = poly1305(c.subarray(32), authKey);
if (!(0, utils_ts_1.equalBytes)(tag, passedTag))
throw new Error('invalid poly1305 tag');
return (0, exports.xsalsa20)(key, nonce, c).subarray(32);
},
};
});
/** Alias to `xsalsa20poly1305`. */
function secretbox(key, nonce) {
const xs = (0, exports.xsalsa20poly1305)(key, nonce);
return { seal: xs.encrypt, open: xs.decrypt };
}
const _poly1305_aead = (fn) => (key, nonce, AAD) => {
const tagLength = 16;
return {
encrypt(plaintext) {
const data = fn(key, nonce, plaintext, undefined, 1); // stream from i=1
const tag = computeTag(fn, key, nonce, data, AAD);
return (0, utils_ts_1.concatBytes)(data, tag);
},
decrypt(ciphertext) {
const passedTag = ciphertext.subarray(-tagLength);
const data = ciphertext.subarray(0, -tagLength);
const tag = computeTag(fn, key, nonce, data, AAD);
if (!(0, utils_ts_1.equalBytes)(tag, passedTag))
throw new Error('invalid poly1305 tag');
return fn(key, nonce, data, undefined, 1); // stream from i=1
},
};
};
exports._poly1305_aead = _poly1305_aead;
/** chacha20-poly1305 12-byte-nonce chacha. */
exports.chacha20poly1305 = (0, utils_ts_1.wrapCipher)({ blockSize: 64, nonceLength: 12, tagLength: 16 }, (0, exports._poly1305_aead)(exports.chacha20));
/**
* XChaCha20-Poly1305 extended-nonce chacha. Can be safely used with random nonces (CSPRNG).
*/
exports.xchacha20poly1305 = (0, utils_ts_1.wrapCipher)({ blockSize: 64, nonceLength: 24, tagLength: 16 }, (0, exports._poly1305_aead)(exports.xchacha20));
//# sourceMappingURL=_micro.js.map
File diff suppressed because one or more lines are too long
+29
View File
@@ -0,0 +1,29 @@
/**
* Poly1305 ([PDF](https://cr.yp.to/mac/poly1305-20050329.pdf),
* [wiki](https://en.wikipedia.org/wiki/Poly1305))
* is a fast and parallel secret-key message-authentication code suitable for
* a wide variety of applications. It was standardized in
* [RFC 8439](https://datatracker.ietf.org/doc/html/rfc8439) 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 [invisible salamanders attack](https://keymaterial.net/2020/09/07/invisible-salamanders-in-aes-gcm-siv/).
* 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 [original website](https://cr.yp.to/mac.html).
* @module
*/
import { Hash, type Input } from './utils.ts';
export type CHash = ReturnType<typeof wrapConstructorWithKey>;
export declare function wrapConstructorWithKey<H extends Hash<H>>(hashCons: (key: Input) => Hash<H>): {
(msg: Input, key: Input): Uint8Array;
outputLen: number;
blockLen: number;
create(key: Input): Hash<H>;
};
/** Poly1305 MAC from RFC 8439. */
export declare const poly1305: CHash;
//# sourceMappingURL=_poly1305.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"_poly1305.d.ts","sourceRoot":"","sources":["src/_poly1305.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AACH,OAAO,EAAE,IAAI,EAAE,KAAK,KAAK,EAA4C,MAAM,YAAY,CAAC;AA4QxF,MAAM,MAAM,KAAK,GAAG,UAAU,CAAC,OAAO,sBAAsB,CAAC,CAAC;AAC9D,wBAAgB,sBAAsB,CAAC,CAAC,SAAS,IAAI,CAAC,CAAC,CAAC,EACtD,QAAQ,EAAE,CAAC,GAAG,EAAE,KAAK,KAAK,IAAI,CAAC,CAAC,CAAC,GAChC;IACD,CAAC,GAAG,EAAE,KAAK,EAAE,GAAG,EAAE,KAAK,GAAG,UAAU,CAAC;IACrC,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,GAAG,EAAE,KAAK,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;CAC7B,CAOA;AAED,kCAAkC;AAClC,eAAO,MAAM,QAAQ,EAAE,KAA0D,CAAC"}
+281
View File
@@ -0,0 +1,281 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.poly1305 = void 0;
exports.wrapConstructorWithKey = wrapConstructorWithKey;
/**
* Poly1305 ([PDF](https://cr.yp.to/mac/poly1305-20050329.pdf),
* [wiki](https://en.wikipedia.org/wiki/Poly1305))
* is a fast and parallel secret-key message-authentication code suitable for
* a wide variety of applications. It was standardized in
* [RFC 8439](https://datatracker.ietf.org/doc/html/rfc8439) 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 [invisible salamanders attack](https://keymaterial.net/2020/09/07/invisible-salamanders-in-aes-gcm-siv/).
* 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 [original website](https://cr.yp.to/mac.html).
* @module
*/
const utils_ts_1 = require("./utils.js");
// Based on Public Domain poly1305-donna https://github.com/floodyberry/poly1305-donna
const u8to16 = (a, i) => (a[i++] & 0xff) | ((a[i++] & 0xff) << 8);
class Poly1305 {
constructor(key) {
this.blockLen = 16;
this.outputLen = 16;
this.buffer = new Uint8Array(16);
this.r = new Uint16Array(10);
this.h = new Uint16Array(10);
this.pad = new Uint16Array(8);
this.pos = 0;
this.finished = false;
key = (0, utils_ts_1.toBytes)(key);
(0, utils_ts_1.abytes)(key, 32);
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);
// https://github.com/floodyberry/poly1305-donna/blob/e6ad6e091d30d7f4ec2d4f978be1fcfcbce72781/poly1305-donna-16.h#L47
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) {
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;
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;
}
(0, utils_ts_1.clean)(g);
}
update(data) {
(0, utils_ts_1.aexists)(this);
data = (0, utils_ts_1.toBytes)(data);
(0, utils_ts_1.abytes)(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() {
(0, utils_ts_1.clean)(this.h, this.r, this.buffer, this.pad);
}
digestInto(out) {
(0, utils_ts_1.aexists)(this);
(0, utils_ts_1.aoutput)(out, this);
this.finished = true;
const { buffer, h } = this;
let { pos } = this;
if (pos) {
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;
}
return out;
}
digest() {
const { buffer, outputLen } = this;
this.digestInto(buffer);
const res = buffer.slice(0, outputLen);
this.destroy();
return res;
}
}
function wrapConstructorWithKey(hashCons) {
const hashC = (msg, key) => hashCons(key).update((0, utils_ts_1.toBytes)(msg)).digest();
const tmp = hashCons(new Uint8Array(32));
hashC.outputLen = tmp.outputLen;
hashC.blockLen = tmp.blockLen;
hashC.create = (key) => hashCons(key);
return hashC;
}
/** Poly1305 MAC from RFC 8439. */
exports.poly1305 = wrapConstructorWithKey((key) => new Poly1305(key));
//# sourceMappingURL=_poly1305.js.map
File diff suppressed because one or more lines are too long
+33
View File
@@ -0,0 +1,33 @@
/**
* 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
* [NIST SP800-38d](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf),
* SIV from
* [RFC 8452](https://datatracker.ietf.org/doc/html/rfc8452).
*
* GHASH modulo: x^128 + x^7 + x^2 + x + 1
* POLYVAL modulo: x^128 + x^127 + x^126 + x^121 + 1
*
* @module
*/
import { Hash, type Input } from './utils.ts';
/**
* `mulX_POLYVAL(ByteReverse(H))` from spec
* @param k mutated in place
*/
export declare function _toGHASHKey(k: Uint8Array): Uint8Array;
export type CHashPV = ReturnType<typeof wrapConstructorWithKey>;
declare function wrapConstructorWithKey<H extends Hash<H>>(hashCons: (key: Input, expectedLength?: number) => Hash<H>): {
(msg: Input, key: Input): Uint8Array;
outputLen: number;
blockLen: number;
create(key: Input, expectedLength?: number): Hash<H>;
};
/** GHash MAC for AES-GCM. */
export declare const ghash: CHashPV;
/** Polyval MAC for AES-SIV. */
export declare const polyval: CHashPV;
export {};
//# sourceMappingURL=_polyval.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"_polyval.d.ts","sourceRoot":"","sources":["src/_polyval.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAEyB,IAAI,EAAE,KAAK,KAAK,EAC/C,MAAM,YAAY,CAAC;AA6BpB;;;GAGG;AACH,wBAAgB,WAAW,CAAC,CAAC,EAAE,UAAU,GAAG,UAAU,CAYrD;AAiLD,MAAM,MAAM,OAAO,GAAG,UAAU,CAAC,OAAO,sBAAsB,CAAC,CAAC;AAChE,iBAAS,sBAAsB,CAAC,CAAC,SAAS,IAAI,CAAC,CAAC,CAAC,EAC/C,QAAQ,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,cAAc,CAAC,EAAE,MAAM,KAAK,IAAI,CAAC,CAAC,CAAC,GACzD;IACD,CAAC,GAAG,EAAE,KAAK,EAAE,GAAG,EAAE,KAAK,GAAG,UAAU,CAAC;IACrC,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,GAAG,EAAE,KAAK,EAAE,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;CACtD,CAQA;AAED,6BAA6B;AAC7B,eAAO,MAAM,KAAK,EAAE,OAEnB,CAAC;AAEF,+BAA+B;AAC/B,eAAO,MAAM,OAAO,EAAE,OAErB,CAAC"}
+233
View File
@@ -0,0 +1,233 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.polyval = exports.ghash = void 0;
exports._toGHASHKey = _toGHASHKey;
/**
* 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
* [NIST SP800-38d](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf),
* SIV from
* [RFC 8452](https://datatracker.ietf.org/doc/html/rfc8452).
*
* GHASH modulo: x^128 + x^7 + x^2 + x + 1
* POLYVAL modulo: x^128 + x^127 + x^126 + x^121 + 1
*
* @module
*/
// prettier-ignore
const utils_ts_1 = require("./utils.js");
const BLOCK_SIZE = 16;
// TODO: rewrite
// temporary padding buffer
const ZEROS16 = /* @__PURE__ */ new Uint8Array(16);
const ZEROS32 = (0, utils_ts_1.u32)(ZEROS16);
const POLY = 0xe1; // v = 2*v % POLY
// v = 2*v % POLY
// NOTE: because x + x = 0 (add/sub is same), mul2(x) != x+x
// We can multiply any number using montgomery ladder and this function (works as double, add is 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),
s0: (s0 >>> 1) ^ ((POLY << 24) & -(hiBit & 1)), // reduce % poly
};
};
const swapLE = (n) => (((n >>> 0) & 0xff) << 24) |
(((n >>> 8) & 0xff) << 16) |
(((n >>> 16) & 0xff) << 8) |
((n >>> 24) & 0xff) |
0;
/**
* `mulX_POLYVAL(ByteReverse(H))` from spec
* @param k mutated in place
*/
function _toGHASHKey(k) {
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;
}
const estimateWindow = (bytes) => {
if (bytes > 64 * 1024)
return 8;
if (bytes > 1024)
return 4;
return 2;
};
class GHASH {
// We select bits per window adaptively based on expectedLength
constructor(key, expectedLength) {
this.blockLen = BLOCK_SIZE;
this.outputLen = BLOCK_SIZE;
this.s0 = 0;
this.s1 = 0;
this.s2 = 0;
this.s3 = 0;
this.finished = false;
key = (0, utils_ts_1.toBytes)(key);
(0, utils_ts_1.abytes)(key, 16);
const kView = (0, utils_ts_1.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;
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) {
(0, utils_ts_1.aexists)(this);
data = (0, utils_ts_1.toBytes)(data);
(0, utils_ts_1.abytes)(data);
const b32 = (0, utils_ts_1.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(b32[i * 4 + 0], b32[i * 4 + 1], b32[i * 4 + 2], b32[i * 4 + 3]);
}
if (left) {
ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));
this._updateBlock(ZEROS32[0], ZEROS32[1], ZEROS32[2], ZEROS32[3]);
(0, utils_ts_1.clean)(ZEROS32); // clean tmp buffer
}
return this;
}
destroy() {
const { t } = this;
// clean precompute table
for (const elm of t) {
(elm.s0 = 0), (elm.s1 = 0), (elm.s2 = 0), (elm.s3 = 0);
}
}
digestInto(out) {
(0, utils_ts_1.aexists)(this);
(0, utils_ts_1.aoutput)(out, this);
this.finished = true;
const { s0, s1, s2, s3 } = this;
const o32 = (0, utils_ts_1.u32)(out);
o32[0] = s0;
o32[1] = s1;
o32[2] = s2;
o32[3] = s3;
return out;
}
digest() {
const res = new Uint8Array(BLOCK_SIZE);
this.digestInto(res);
this.destroy();
return res;
}
}
class Polyval extends GHASH {
constructor(key, expectedLength) {
key = (0, utils_ts_1.toBytes)(key);
(0, utils_ts_1.abytes)(key);
const ghKey = _toGHASHKey((0, utils_ts_1.copyBytes)(key));
super(ghKey, expectedLength);
(0, utils_ts_1.clean)(ghKey);
}
update(data) {
data = (0, utils_ts_1.toBytes)(data);
(0, utils_ts_1.aexists)(this);
const b32 = (0, utils_ts_1.u32)(data);
const left = data.length % BLOCK_SIZE;
const blocks = Math.floor(data.length / BLOCK_SIZE);
for (let i = 0; i < blocks; i++) {
this._updateBlock(swapLE(b32[i * 4 + 3]), swapLE(b32[i * 4 + 2]), swapLE(b32[i * 4 + 1]), swapLE(b32[i * 4 + 0]));
}
if (left) {
ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));
this._updateBlock(swapLE(ZEROS32[3]), swapLE(ZEROS32[2]), swapLE(ZEROS32[1]), swapLE(ZEROS32[0]));
(0, utils_ts_1.clean)(ZEROS32);
}
return this;
}
digestInto(out) {
(0, utils_ts_1.aexists)(this);
(0, utils_ts_1.aoutput)(out, this);
this.finished = true;
// tmp ugly hack
const { s0, s1, s2, s3 } = this;
const o32 = (0, utils_ts_1.u32)(out);
o32[0] = s0;
o32[1] = s1;
o32[2] = s2;
o32[3] = s3;
return out.reverse();
}
}
function wrapConstructorWithKey(hashCons) {
const hashC = (msg, key) => hashCons(key, msg.length).update((0, utils_ts_1.toBytes)(msg)).digest();
const tmp = hashCons(new Uint8Array(16), 0);
hashC.outputLen = tmp.outputLen;
hashC.blockLen = tmp.blockLen;
hashC.create = (key, expectedLength) => hashCons(key, expectedLength);
return hashC;
}
/** GHash MAC for AES-GCM. */
exports.ghash = wrapConstructorWithKey((key, expectedLength) => new GHASH(key, expectedLength));
/** Polyval MAC for AES-SIV. */
exports.polyval = wrapConstructorWithKey((key, expectedLength) => new Polyval(key, expectedLength));
//# sourceMappingURL=_polyval.js.map
File diff suppressed because one or more lines are too long
+117
View File
@@ -0,0 +1,117 @@
import { type Cipher, type CipherWithOutput } from './utils.ts';
/** Key expansion used in CTR. */
declare function expandKeyLE(key: Uint8Array): Uint32Array;
declare function expandKeyDecLE(key: Uint8Array): Uint32Array;
declare function encrypt(xk: Uint32Array, s0: number, s1: number, s2: number, s3: number): {
s0: number;
s1: number;
s2: number;
s3: number;
};
declare function decrypt(xk: Uint32Array, s0: number, s1: number, s2: number, s3: number): {
s0: number;
s1: number;
s2: number;
s3: number;
};
declare function ctrCounter(xk: Uint32Array, nonce: Uint8Array, src: Uint8Array, dst?: Uint8Array): Uint8Array;
declare function ctr32(xk: Uint32Array, isLE: boolean, nonce: Uint8Array, src: Uint8Array, dst?: Uint8Array): Uint8Array;
/**
* CTR: counter mode. Creates stream cipher.
* Requires good IV. Parallelizable. OK, but no MAC.
*/
export declare const ctr: ((key: Uint8Array, nonce: Uint8Array) => CipherWithOutput) & {
blockSize: number;
nonceLength: number;
};
/** Options for ECB and CBC. */
export type BlockOpts = {
disablePadding?: boolean;
};
/**
* ECB: Electronic CodeBook. Simple deterministic replacement.
* Dangerous: always map x to y. See [AES Penguin](https://words.filippo.io/the-ecb-penguin/).
*/
export declare const ecb: ((key: Uint8Array, opts?: BlockOpts) => CipherWithOutput) & {
blockSize: number;
};
/**
* CBC: Cipher-Block-Chaining. Key is previous rounds block.
* Fragile: needs proper padding. Unauthenticated: needs MAC.
*/
export declare const cbc: ((key: Uint8Array, iv: Uint8Array, opts?: BlockOpts) => CipherWithOutput) & {
blockSize: number;
nonceLength: number;
};
/**
* CFB: Cipher Feedback Mode. The input for the block cipher is the previous cipher output.
* Unauthenticated: needs MAC.
*/
export declare const cfb: ((key: Uint8Array, iv: Uint8Array) => CipherWithOutput) & {
blockSize: number;
nonceLength: number;
};
/**
* GCM: Galois/Counter Mode.
* Modern, parallel version of CTR, with MAC.
* Be careful: MACs can be forged.
* Unsafe to use random nonces under the same key, due to collision chance.
* As for nonce size, prefer 12-byte, instead of 8-byte.
*/
export declare const gcm: ((key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array) => Cipher) & {
blockSize: number;
nonceLength: number;
tagLength: number;
varSizeNonce: true;
};
/**
* AES-GCM-SIV: classic AES-GCM with nonce-misuse resistance.
* Guarantees that, when a nonce is repeated, the only security loss is that identical
* plaintexts will produce identical ciphertexts.
* RFC 8452, https://datatracker.ietf.org/doc/html/rfc8452
*/
export declare const gcmsiv: ((key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array) => Cipher) & {
blockSize: number;
nonceLength: number;
tagLength: number;
varSizeNonce: true;
};
/**
* AES-GCM-SIV, not AES-SIV.
* This is legace name, use `gcmsiv` export instead.
* @deprecated
*/
export declare const siv: typeof gcmsiv;
declare function encryptBlock(xk: Uint32Array, block: Uint8Array): Uint8Array;
declare function decryptBlock(xk: Uint32Array, block: Uint8Array): Uint8Array;
/**
* AES-KW (key-wrap). Injects static IV into plaintext, adds counter, encrypts 6 times.
* Reduces block size from 16 to 8 bytes.
* For padded version, use aeskwp.
* [RFC 3394](https://datatracker.ietf.org/doc/rfc3394/),
* [NIST.SP.800-38F](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf).
*/
export declare const aeskw: ((kek: Uint8Array) => Cipher) & {
blockSize: number;
};
/**
* AES-KW, but with padding and allows random keys.
* Second u32 of IV is used as counter for length.
* [RFC 5649](https://www.rfc-editor.org/rfc/rfc5649)
*/
export declare const aeskwp: ((kek: Uint8Array) => Cipher) & {
blockSize: number;
};
/** Unsafe low-level internal methods. May change at any time. */
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;
};
export {};
//# sourceMappingURL=aes.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"aes.d.ts","sourceRoot":"","sources":["src/aes.ts"],"names":[],"mappings":"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"}
+906
View File
@@ -0,0 +1,906 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.unsafe = exports.aeskwp = exports.aeskw = exports.siv = exports.gcmsiv = exports.gcm = exports.cfb = exports.cbc = exports.ecb = exports.ctr = void 0;
/**
* [AES](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard)
* a.k.a. Advanced Encryption Standard
* is a variant of Rijndael block cipher, standardized by NIST in 2001.
* We provide the fastest available pure JS implementation.
*
* Data is split into 128-bit blocks. Encrypted in 10/12/14 rounds (128/192/256 bits). In every round:
* 1. **S-box**, table substitution
* 2. **Shift rows**, cyclic shift left of all rows of data array
* 3. **Mix columns**, multiplying every column by fixed polynomial
* 4. **Add round key**, round_key xor i-th column of array
*
* Check out [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)
* @module
*/
const _polyval_ts_1 = require("./_polyval.js");
// prettier-ignore
const utils_ts_1 = require("./utils.js");
const BLOCK_SIZE = 16;
const BLOCK_SIZE32 = 4;
const EMPTY_BLOCK = /* @__PURE__ */ new Uint8Array(BLOCK_SIZE);
const POLY = 0x11b; // 1 + x + x**3 + x**4 + x**8
// TODO: remove multiplication, binary ops only
function mul2(n) {
return (n << 1) ^ (POLY & -(n >> 7));
}
function mul(a, b) {
let res = 0;
for (; b > 0; b >>= 1) {
// Montgomery ladder
res ^= a & -(b & 1); // if (b&1) res ^=a (but const-time).
a = mul2(a); // a = 2*a
}
return res;
}
// AES S-box is generated using finite field inversion,
// an affine transform, and xor of a constant 0x63.
const sbox = /* @__PURE__ */ (() => {
const t = new Uint8Array(256);
for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x))
t[i] = x;
const box = new Uint8Array(256);
box[0] = 0x63; // first elm
for (let i = 0; i < 255; i++) {
let x = t[255 - i];
x |= x << 8;
box[t[i]] = (x ^ (x >> 4) ^ (x >> 5) ^ (x >> 6) ^ (x >> 7) ^ 0x63) & 0xff;
}
(0, utils_ts_1.clean)(t);
return box;
})();
// Inverted S-box
const invSbox = /* @__PURE__ */ sbox.map((_, j) => sbox.indexOf(j));
// Rotate u32 by 8
const rotr32_8 = (n) => (n << 24) | (n >>> 8);
const rotl32_8 = (n) => (n << 8) | (n >>> 24);
// The byte swap operation for uint32 (LE<->BE)
const byteSwap = (word) => ((word << 24) & 0xff000000) |
((word << 8) & 0xff0000) |
((word >>> 8) & 0xff00) |
((word >>> 24) & 0xff);
// T-table is optimization suggested in 5.2 of original proposal (missed from FIPS-197). Changes:
// - LE instead of BE
// - bigger tables: T0 and T1 are merged into T01 table and T2 & T3 into T23;
// so index is u16, instead of u8. This speeds up things, unexpectedly
function genTtable(sbox, fn) {
if (sbox.length !== 256)
throw new Error('Wrong sbox length');
const T0 = new Uint32Array(256).map((_, j) => fn(sbox[j]));
const T1 = T0.map(rotl32_8);
const T2 = T1.map(rotl32_8);
const T3 = T2.map(rotl32_8);
const T01 = new Uint32Array(256 * 256);
const T23 = new Uint32Array(256 * 256);
const sbox2 = new Uint16Array(256 * 256);
for (let i = 0; i < 256; i++) {
for (let j = 0; j < 256; j++) {
const idx = i * 256 + j;
T01[idx] = T0[i] ^ T1[j];
T23[idx] = T2[i] ^ T3[j];
sbox2[idx] = (sbox[i] << 8) | sbox[j];
}
}
return { sbox, sbox2, T0, T1, T2, T3, T01, T23 };
}
const tableEncoding = /* @__PURE__ */ genTtable(sbox, (s) => (mul(s, 3) << 24) | (s << 16) | (s << 8) | mul(s, 2));
const tableDecoding = /* @__PURE__ */ genTtable(invSbox, (s) => (mul(s, 11) << 24) | (mul(s, 13) << 16) | (mul(s, 9) << 8) | mul(s, 14));
const xPowers = /* @__PURE__ */ (() => {
const p = new Uint8Array(16);
for (let i = 0, x = 1; i < 16; i++, x = mul2(x))
p[i] = x;
return p;
})();
/** Key expansion used in CTR. */
function expandKeyLE(key) {
(0, utils_ts_1.abytes)(key);
const len = key.length;
if (![16, 24, 32].includes(len))
throw new Error('aes: invalid key size, should be 16, 24 or 32, got ' + len);
const { sbox2 } = tableEncoding;
const toClean = [];
if (!(0, utils_ts_1.isAligned32)(key))
toClean.push((key = (0, utils_ts_1.copyBytes)(key)));
const k32 = (0, utils_ts_1.u32)(key);
const Nk = k32.length;
const subByte = (n) => applySbox(sbox2, n, n, n, n);
const xk = new Uint32Array(len + 28); // expanded key
xk.set(k32);
// 4.3.1 Key expansion
for (let i = Nk; i < xk.length; i++) {
let t = xk[i - 1];
if (i % Nk === 0)
t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1];
else if (Nk > 6 && i % Nk === 4)
t = subByte(t);
xk[i] = xk[i - Nk] ^ t;
}
(0, utils_ts_1.clean)(...toClean);
return xk;
}
function expandKeyDecLE(key) {
const encKey = expandKeyLE(key);
const xk = encKey.slice();
const Nk = encKey.length;
const { sbox2 } = tableEncoding;
const { T0, T1, T2, T3 } = tableDecoding;
// Inverse key by chunks of 4 (rounds)
for (let i = 0; i < Nk; i += 4) {
for (let j = 0; j < 4; j++)
xk[i + j] = encKey[Nk - i - 4 + j];
}
(0, utils_ts_1.clean)(encKey);
// apply InvMixColumn except first & last round
for (let i = 4; i < Nk - 4; i++) {
const x = xk[i];
const w = applySbox(sbox2, x, x, x, x);
xk[i] = T0[w & 0xff] ^ T1[(w >>> 8) & 0xff] ^ T2[(w >>> 16) & 0xff] ^ T3[w >>> 24];
}
return xk;
}
// Apply tables
function apply0123(T01, T23, s0, s1, s2, s3) {
return (T01[((s0 << 8) & 0xff00) | ((s1 >>> 8) & 0xff)] ^
T23[((s2 >>> 8) & 0xff00) | ((s3 >>> 24) & 0xff)]);
}
function applySbox(sbox2, s0, s1, s2, s3) {
return (sbox2[(s0 & 0xff) | (s1 & 0xff00)] |
(sbox2[((s2 >>> 16) & 0xff) | ((s3 >>> 16) & 0xff00)] << 16));
}
function encrypt(xk, s0, s1, s2, s3) {
const { sbox2, T01, T23 } = tableEncoding;
let k = 0;
(s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]);
const rounds = xk.length / 4 - 2;
for (let i = 0; i < rounds; i++) {
const t0 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3);
const t1 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0);
const t2 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1);
const t3 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2);
(s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3);
}
// last round (without mixcolumns, so using SBOX2 table)
const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3);
const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0);
const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1);
const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2);
return { s0: t0, s1: t1, s2: t2, s3: t3 };
}
// Can't be merged with encrypt: arg positions for apply0123 / applySbox are different
function decrypt(xk, s0, s1, s2, s3) {
const { sbox2, T01, T23 } = tableDecoding;
let k = 0;
(s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]);
const rounds = xk.length / 4 - 2;
for (let i = 0; i < rounds; i++) {
const t0 = xk[k++] ^ apply0123(T01, T23, s0, s3, s2, s1);
const t1 = xk[k++] ^ apply0123(T01, T23, s1, s0, s3, s2);
const t2 = xk[k++] ^ apply0123(T01, T23, s2, s1, s0, s3);
const t3 = xk[k++] ^ apply0123(T01, T23, s3, s2, s1, s0);
(s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3);
}
// Last round
const t0 = xk[k++] ^ applySbox(sbox2, s0, s3, s2, s1);
const t1 = xk[k++] ^ applySbox(sbox2, s1, s0, s3, s2);
const t2 = xk[k++] ^ applySbox(sbox2, s2, s1, s0, s3);
const t3 = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0);
return { s0: t0, s1: t1, s2: t2, s3: t3 };
}
// TODO: investigate merging with ctr32
function ctrCounter(xk, nonce, src, dst) {
(0, utils_ts_1.abytes)(nonce, BLOCK_SIZE);
(0, utils_ts_1.abytes)(src);
const srcLen = src.length;
dst = (0, utils_ts_1.getOutput)(srcLen, dst);
(0, utils_ts_1.complexOverlapBytes)(src, dst);
const ctr = nonce;
const c32 = (0, utils_ts_1.u32)(ctr);
// Fill block (empty, ctr=0)
let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]);
const src32 = (0, utils_ts_1.u32)(src);
const dst32 = (0, utils_ts_1.u32)(dst);
// process blocks
for (let i = 0; i + 4 <= src32.length; i += 4) {
dst32[i + 0] = src32[i + 0] ^ s0;
dst32[i + 1] = src32[i + 1] ^ s1;
dst32[i + 2] = src32[i + 2] ^ s2;
dst32[i + 3] = src32[i + 3] ^ s3;
// Full 128 bit counter with wrap around
let carry = 1;
for (let i = ctr.length - 1; i >= 0; i--) {
carry = (carry + (ctr[i] & 0xff)) | 0;
ctr[i] = carry & 0xff;
carry >>>= 8;
}
({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]));
}
// leftovers (less than block)
// It's possible to handle > u32 fast, but is it worth it?
const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);
if (start < srcLen) {
const b32 = new Uint32Array([s0, s1, s2, s3]);
const buf = (0, utils_ts_1.u8)(b32);
for (let i = start, pos = 0; i < srcLen; i++, pos++)
dst[i] = src[i] ^ buf[pos];
(0, utils_ts_1.clean)(b32);
}
return dst;
}
// AES CTR with overflowing 32 bit counter
// It's possible to do 32le significantly simpler (and probably faster) by using u32.
// But, we need both, and perf bottleneck is in ghash anyway.
function ctr32(xk, isLE, nonce, src, dst) {
(0, utils_ts_1.abytes)(nonce, BLOCK_SIZE);
(0, utils_ts_1.abytes)(src);
dst = (0, utils_ts_1.getOutput)(src.length, dst);
const ctr = nonce; // write new value to nonce, so it can be re-used
const c32 = (0, utils_ts_1.u32)(ctr);
const view = (0, utils_ts_1.createView)(ctr);
const src32 = (0, utils_ts_1.u32)(src);
const dst32 = (0, utils_ts_1.u32)(dst);
const ctrPos = isLE ? 0 : 12;
const srcLen = src.length;
// Fill block (empty, ctr=0)
let ctrNum = view.getUint32(ctrPos, isLE); // read current counter value
let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]);
// process blocks
for (let i = 0; i + 4 <= src32.length; i += 4) {
dst32[i + 0] = src32[i + 0] ^ s0;
dst32[i + 1] = src32[i + 1] ^ s1;
dst32[i + 2] = src32[i + 2] ^ s2;
dst32[i + 3] = src32[i + 3] ^ s3;
ctrNum = (ctrNum + 1) >>> 0; // u32 wrap
view.setUint32(ctrPos, ctrNum, isLE);
({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]));
}
// leftovers (less than a block)
const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);
if (start < srcLen) {
const b32 = new Uint32Array([s0, s1, s2, s3]);
const buf = (0, utils_ts_1.u8)(b32);
for (let i = start, pos = 0; i < srcLen; i++, pos++)
dst[i] = src[i] ^ buf[pos];
(0, utils_ts_1.clean)(b32);
}
return dst;
}
/**
* CTR: counter mode. Creates stream cipher.
* Requires good IV. Parallelizable. OK, but no MAC.
*/
exports.ctr = (0, utils_ts_1.wrapCipher)({ blockSize: 16, nonceLength: 16 }, function aesctr(key, nonce) {
function processCtr(buf, dst) {
(0, utils_ts_1.abytes)(buf);
if (dst !== undefined) {
(0, utils_ts_1.abytes)(dst);
if (!(0, utils_ts_1.isAligned32)(dst))
throw new Error('unaligned destination');
}
const xk = expandKeyLE(key);
const n = (0, utils_ts_1.copyBytes)(nonce); // align + avoid changing
const toClean = [xk, n];
if (!(0, utils_ts_1.isAligned32)(buf))
toClean.push((buf = (0, utils_ts_1.copyBytes)(buf)));
const out = ctrCounter(xk, n, buf, dst);
(0, utils_ts_1.clean)(...toClean);
return out;
}
return {
encrypt: (plaintext, dst) => processCtr(plaintext, dst),
decrypt: (ciphertext, dst) => processCtr(ciphertext, dst),
};
});
function validateBlockDecrypt(data) {
(0, utils_ts_1.abytes)(data);
if (data.length % BLOCK_SIZE !== 0) {
throw new Error('aes-(cbc/ecb).decrypt ciphertext should consist of blocks with size ' + BLOCK_SIZE);
}
}
function validateBlockEncrypt(plaintext, pcks5, dst) {
(0, utils_ts_1.abytes)(plaintext);
let outLen = plaintext.length;
const remaining = outLen % BLOCK_SIZE;
if (!pcks5 && remaining !== 0)
throw new Error('aec/(cbc-ecb): unpadded plaintext with disabled padding');
if (!(0, utils_ts_1.isAligned32)(plaintext))
plaintext = (0, utils_ts_1.copyBytes)(plaintext);
const b = (0, utils_ts_1.u32)(plaintext);
if (pcks5) {
let left = BLOCK_SIZE - remaining;
if (!left)
left = BLOCK_SIZE; // if no bytes left, create empty padding block
outLen = outLen + left;
}
dst = (0, utils_ts_1.getOutput)(outLen, dst);
(0, utils_ts_1.complexOverlapBytes)(plaintext, dst);
const o = (0, utils_ts_1.u32)(dst);
return { b, o, out: dst };
}
function validatePCKS(data, pcks5) {
if (!pcks5)
return data;
const len = data.length;
if (!len)
throw new Error('aes/pcks5: empty ciphertext not allowed');
const lastByte = data[len - 1];
if (lastByte <= 0 || lastByte > 16)
throw new Error('aes/pcks5: wrong padding');
const out = data.subarray(0, -lastByte);
for (let i = 0; i < lastByte; i++)
if (data[len - i - 1] !== lastByte)
throw new Error('aes/pcks5: wrong padding');
return out;
}
function padPCKS(left) {
const tmp = new Uint8Array(16);
const tmp32 = (0, utils_ts_1.u32)(tmp);
tmp.set(left);
const paddingByte = BLOCK_SIZE - left.length;
for (let i = BLOCK_SIZE - paddingByte; i < BLOCK_SIZE; i++)
tmp[i] = paddingByte;
return tmp32;
}
/**
* ECB: Electronic CodeBook. Simple deterministic replacement.
* Dangerous: always map x to y. See [AES Penguin](https://words.filippo.io/the-ecb-penguin/).
*/
exports.ecb = (0, utils_ts_1.wrapCipher)({ blockSize: 16 }, function aesecb(key, opts = {}) {
const pcks5 = !opts.disablePadding;
return {
encrypt(plaintext, dst) {
const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst);
const xk = expandKeyLE(key);
let i = 0;
for (; i + 4 <= b.length;) {
const { s0, s1, s2, s3 } = encrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);
(o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);
}
if (pcks5) {
const tmp32 = padPCKS(plaintext.subarray(i * 4));
const { s0, s1, s2, s3 } = encrypt(xk, tmp32[0], tmp32[1], tmp32[2], tmp32[3]);
(o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);
}
(0, utils_ts_1.clean)(xk);
return _out;
},
decrypt(ciphertext, dst) {
validateBlockDecrypt(ciphertext);
const xk = expandKeyDecLE(key);
dst = (0, utils_ts_1.getOutput)(ciphertext.length, dst);
const toClean = [xk];
if (!(0, utils_ts_1.isAligned32)(ciphertext))
toClean.push((ciphertext = (0, utils_ts_1.copyBytes)(ciphertext)));
(0, utils_ts_1.complexOverlapBytes)(ciphertext, dst);
const b = (0, utils_ts_1.u32)(ciphertext);
const o = (0, utils_ts_1.u32)(dst);
for (let i = 0; i + 4 <= b.length;) {
const { s0, s1, s2, s3 } = decrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);
(o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);
}
(0, utils_ts_1.clean)(...toClean);
return validatePCKS(dst, pcks5);
},
};
});
/**
* CBC: Cipher-Block-Chaining. Key is previous rounds block.
* Fragile: needs proper padding. Unauthenticated: needs MAC.
*/
exports.cbc = (0, utils_ts_1.wrapCipher)({ blockSize: 16, nonceLength: 16 }, function aescbc(key, iv, opts = {}) {
const pcks5 = !opts.disablePadding;
return {
encrypt(plaintext, dst) {
const xk = expandKeyLE(key);
const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst);
let _iv = iv;
const toClean = [xk];
if (!(0, utils_ts_1.isAligned32)(_iv))
toClean.push((_iv = (0, utils_ts_1.copyBytes)(_iv)));
const n32 = (0, utils_ts_1.u32)(_iv);
// prettier-ignore
let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];
let i = 0;
for (; i + 4 <= b.length;) {
(s0 ^= b[i + 0]), (s1 ^= b[i + 1]), (s2 ^= b[i + 2]), (s3 ^= b[i + 3]);
({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));
(o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);
}
if (pcks5) {
const tmp32 = padPCKS(plaintext.subarray(i * 4));
(s0 ^= tmp32[0]), (s1 ^= tmp32[1]), (s2 ^= tmp32[2]), (s3 ^= tmp32[3]);
({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));
(o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);
}
(0, utils_ts_1.clean)(...toClean);
return _out;
},
decrypt(ciphertext, dst) {
validateBlockDecrypt(ciphertext);
const xk = expandKeyDecLE(key);
let _iv = iv;
const toClean = [xk];
if (!(0, utils_ts_1.isAligned32)(_iv))
toClean.push((_iv = (0, utils_ts_1.copyBytes)(_iv)));
const n32 = (0, utils_ts_1.u32)(_iv);
dst = (0, utils_ts_1.getOutput)(ciphertext.length, dst);
if (!(0, utils_ts_1.isAligned32)(ciphertext))
toClean.push((ciphertext = (0, utils_ts_1.copyBytes)(ciphertext)));
(0, utils_ts_1.complexOverlapBytes)(ciphertext, dst);
const b = (0, utils_ts_1.u32)(ciphertext);
const o = (0, utils_ts_1.u32)(dst);
// prettier-ignore
let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];
for (let i = 0; i + 4 <= b.length;) {
// prettier-ignore
const ps0 = s0, ps1 = s1, ps2 = s2, ps3 = s3;
(s0 = b[i + 0]), (s1 = b[i + 1]), (s2 = b[i + 2]), (s3 = b[i + 3]);
const { s0: o0, s1: o1, s2: o2, s3: o3 } = decrypt(xk, s0, s1, s2, s3);
(o[i++] = o0 ^ ps0), (o[i++] = o1 ^ ps1), (o[i++] = o2 ^ ps2), (o[i++] = o3 ^ ps3);
}
(0, utils_ts_1.clean)(...toClean);
return validatePCKS(dst, pcks5);
},
};
});
/**
* CFB: Cipher Feedback Mode. The input for the block cipher is the previous cipher output.
* Unauthenticated: needs MAC.
*/
exports.cfb = (0, utils_ts_1.wrapCipher)({ blockSize: 16, nonceLength: 16 }, function aescfb(key, iv) {
function processCfb(src, isEncrypt, dst) {
(0, utils_ts_1.abytes)(src);
const srcLen = src.length;
dst = (0, utils_ts_1.getOutput)(srcLen, dst);
if ((0, utils_ts_1.overlapBytes)(src, dst))
throw new Error('overlapping src and dst not supported.');
const xk = expandKeyLE(key);
let _iv = iv;
const toClean = [xk];
if (!(0, utils_ts_1.isAligned32)(_iv))
toClean.push((_iv = (0, utils_ts_1.copyBytes)(_iv)));
if (!(0, utils_ts_1.isAligned32)(src))
toClean.push((src = (0, utils_ts_1.copyBytes)(src)));
const src32 = (0, utils_ts_1.u32)(src);
const dst32 = (0, utils_ts_1.u32)(dst);
const next32 = isEncrypt ? dst32 : src32;
const n32 = (0, utils_ts_1.u32)(_iv);
// prettier-ignore
let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];
for (let i = 0; i + 4 <= src32.length;) {
const { s0: e0, s1: e1, s2: e2, s3: e3 } = encrypt(xk, s0, s1, s2, s3);
dst32[i + 0] = src32[i + 0] ^ e0;
dst32[i + 1] = src32[i + 1] ^ e1;
dst32[i + 2] = src32[i + 2] ^ e2;
dst32[i + 3] = src32[i + 3] ^ e3;
(s0 = next32[i++]), (s1 = next32[i++]), (s2 = next32[i++]), (s3 = next32[i++]);
}
// leftovers (less than block)
const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);
if (start < srcLen) {
({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));
const buf = (0, utils_ts_1.u8)(new Uint32Array([s0, s1, s2, s3]));
for (let i = start, pos = 0; i < srcLen; i++, pos++)
dst[i] = src[i] ^ buf[pos];
(0, utils_ts_1.clean)(buf);
}
(0, utils_ts_1.clean)(...toClean);
return dst;
}
return {
encrypt: (plaintext, dst) => processCfb(plaintext, true, dst),
decrypt: (ciphertext, dst) => processCfb(ciphertext, false, dst),
};
});
// TODO: merge with chacha, however gcm has bitLen while chacha has byteLen
function computeTag(fn, isLE, key, data, AAD) {
const aadLength = AAD ? AAD.length : 0;
const h = fn.create(key, data.length + aadLength);
if (AAD)
h.update(AAD);
const num = (0, utils_ts_1.u64Lengths)(8 * data.length, 8 * aadLength, isLE);
h.update(data);
h.update(num);
const res = h.digest();
(0, utils_ts_1.clean)(num);
return res;
}
/**
* GCM: Galois/Counter Mode.
* Modern, parallel version of CTR, with MAC.
* Be careful: MACs can be forged.
* Unsafe to use random nonces under the same key, due to collision chance.
* As for nonce size, prefer 12-byte, instead of 8-byte.
*/
exports.gcm = (0, utils_ts_1.wrapCipher)({ blockSize: 16, nonceLength: 12, tagLength: 16, varSizeNonce: true }, function aesgcm(key, nonce, AAD) {
// NIST 800-38d doesn't enforce minimum nonce length.
// We enforce 8 bytes for compat with openssl.
// 12 bytes are recommended. More than 12 bytes would be converted into 12.
if (nonce.length < 8)
throw new Error('aes/gcm: invalid nonce length');
const tagLength = 16;
function _computeTag(authKey, tagMask, data) {
const tag = computeTag(_polyval_ts_1.ghash, false, authKey, data, AAD);
for (let i = 0; i < tagMask.length; i++)
tag[i] ^= tagMask[i];
return tag;
}
function deriveKeys() {
const xk = expandKeyLE(key);
const authKey = EMPTY_BLOCK.slice();
const counter = EMPTY_BLOCK.slice();
ctr32(xk, false, counter, counter, authKey);
// NIST 800-38d, page 15: different behavior for 96-bit and non-96-bit nonces
if (nonce.length === 12) {
counter.set(nonce);
}
else {
const nonceLen = EMPTY_BLOCK.slice();
const view = (0, utils_ts_1.createView)(nonceLen);
(0, utils_ts_1.setBigUint64)(view, 8, BigInt(nonce.length * 8), false);
// ghash(nonce || u64be(0) || u64be(nonceLen*8))
const g = _polyval_ts_1.ghash.create(authKey).update(nonce).update(nonceLen);
g.digestInto(counter); // digestInto doesn't trigger '.destroy'
g.destroy();
}
const tagMask = ctr32(xk, false, counter, EMPTY_BLOCK);
return { xk, authKey, counter, tagMask };
}
return {
encrypt(plaintext) {
const { xk, authKey, counter, tagMask } = deriveKeys();
const out = new Uint8Array(plaintext.length + tagLength);
const toClean = [xk, authKey, counter, tagMask];
if (!(0, utils_ts_1.isAligned32)(plaintext))
toClean.push((plaintext = (0, utils_ts_1.copyBytes)(plaintext)));
ctr32(xk, false, counter, plaintext, out.subarray(0, plaintext.length));
const tag = _computeTag(authKey, tagMask, out.subarray(0, out.length - tagLength));
toClean.push(tag);
out.set(tag, plaintext.length);
(0, utils_ts_1.clean)(...toClean);
return out;
},
decrypt(ciphertext) {
const { xk, authKey, counter, tagMask } = deriveKeys();
const toClean = [xk, authKey, tagMask, counter];
if (!(0, utils_ts_1.isAligned32)(ciphertext))
toClean.push((ciphertext = (0, utils_ts_1.copyBytes)(ciphertext)));
const data = ciphertext.subarray(0, -tagLength);
const passedTag = ciphertext.subarray(-tagLength);
const tag = _computeTag(authKey, tagMask, data);
toClean.push(tag);
if (!(0, utils_ts_1.equalBytes)(tag, passedTag))
throw new Error('aes/gcm: invalid ghash tag');
const out = ctr32(xk, false, counter, data);
(0, utils_ts_1.clean)(...toClean);
return out;
},
};
});
const limit = (name, min, max) => (value) => {
if (!Number.isSafeInteger(value) || min > value || value > max) {
const minmax = '[' + min + '..' + max + ']';
throw new Error('' + name + ': expected value in range ' + minmax + ', got ' + value);
}
};
/**
* AES-GCM-SIV: classic AES-GCM with nonce-misuse resistance.
* Guarantees that, when a nonce is repeated, the only security loss is that identical
* plaintexts will produce identical ciphertexts.
* RFC 8452, https://datatracker.ietf.org/doc/html/rfc8452
*/
exports.gcmsiv = (0, utils_ts_1.wrapCipher)({ blockSize: 16, nonceLength: 12, tagLength: 16, varSizeNonce: true }, function aessiv(key, nonce, AAD) {
const tagLength = 16;
// From RFC 8452: Section 6
const AAD_LIMIT = limit('AAD', 0, 2 ** 36);
const PLAIN_LIMIT = limit('plaintext', 0, 2 ** 36);
const NONCE_LIMIT = limit('nonce', 12, 12);
const CIPHER_LIMIT = limit('ciphertext', 16, 2 ** 36 + 16);
(0, utils_ts_1.abytes)(key, 16, 24, 32);
NONCE_LIMIT(nonce.length);
if (AAD !== undefined)
AAD_LIMIT(AAD.length);
function deriveKeys() {
const xk = expandKeyLE(key);
const encKey = new Uint8Array(key.length);
const authKey = new Uint8Array(16);
const toClean = [xk, encKey];
let _nonce = nonce;
if (!(0, utils_ts_1.isAligned32)(_nonce))
toClean.push((_nonce = (0, utils_ts_1.copyBytes)(_nonce)));
const n32 = (0, utils_ts_1.u32)(_nonce);
// prettier-ignore
let s0 = 0, s1 = n32[0], s2 = n32[1], s3 = n32[2];
let counter = 0;
for (const derivedKey of [authKey, encKey].map(utils_ts_1.u32)) {
const d32 = (0, utils_ts_1.u32)(derivedKey);
for (let i = 0; i < d32.length; i += 2) {
// aes(u32le(0) || nonce)[:8] || aes(u32le(1) || nonce)[:8] ...
const { s0: o0, s1: o1 } = encrypt(xk, s0, s1, s2, s3);
d32[i + 0] = o0;
d32[i + 1] = o1;
s0 = ++counter; // increment counter inside state
}
}
const res = { authKey, encKey: expandKeyLE(encKey) };
// Cleanup
(0, utils_ts_1.clean)(...toClean);
return res;
}
function _computeTag(encKey, authKey, data) {
const tag = computeTag(_polyval_ts_1.polyval, true, authKey, data, AAD);
// Compute the expected tag by XORing S_s and the nonce, clearing the
// most significant bit of the last byte and encrypting with the
// message-encryption key.
for (let i = 0; i < 12; i++)
tag[i] ^= nonce[i];
tag[15] &= 0x7f; // Clear the highest bit
// encrypt tag as block
const t32 = (0, utils_ts_1.u32)(tag);
// prettier-ignore
let s0 = t32[0], s1 = t32[1], s2 = t32[2], s3 = t32[3];
({ s0, s1, s2, s3 } = encrypt(encKey, s0, s1, s2, s3));
(t32[0] = s0), (t32[1] = s1), (t32[2] = s2), (t32[3] = s3);
return tag;
}
// actual decrypt/encrypt of message.
function processSiv(encKey, tag, input) {
let block = (0, utils_ts_1.copyBytes)(tag);
block[15] |= 0x80; // Force highest bit
const res = ctr32(encKey, true, block, input);
// Cleanup
(0, utils_ts_1.clean)(block);
return res;
}
return {
encrypt(plaintext) {
PLAIN_LIMIT(plaintext.length);
const { encKey, authKey } = deriveKeys();
const tag = _computeTag(encKey, authKey, plaintext);
const toClean = [encKey, authKey, tag];
if (!(0, utils_ts_1.isAligned32)(plaintext))
toClean.push((plaintext = (0, utils_ts_1.copyBytes)(plaintext)));
const out = new Uint8Array(plaintext.length + tagLength);
out.set(tag, plaintext.length);
out.set(processSiv(encKey, tag, plaintext));
// Cleanup
(0, utils_ts_1.clean)(...toClean);
return out;
},
decrypt(ciphertext) {
CIPHER_LIMIT(ciphertext.length);
const tag = ciphertext.subarray(-tagLength);
const { encKey, authKey } = deriveKeys();
const toClean = [encKey, authKey];
if (!(0, utils_ts_1.isAligned32)(ciphertext))
toClean.push((ciphertext = (0, utils_ts_1.copyBytes)(ciphertext)));
const plaintext = processSiv(encKey, tag, ciphertext.subarray(0, -tagLength));
const expectedTag = _computeTag(encKey, authKey, plaintext);
toClean.push(expectedTag);
if (!(0, utils_ts_1.equalBytes)(tag, expectedTag)) {
(0, utils_ts_1.clean)(...toClean);
throw new Error('invalid polyval tag');
}
// Cleanup
(0, utils_ts_1.clean)(...toClean);
return plaintext;
},
};
});
/**
* AES-GCM-SIV, not AES-SIV.
* This is legace name, use `gcmsiv` export instead.
* @deprecated
*/
exports.siv = exports.gcmsiv;
function isBytes32(a) {
return (a instanceof Uint32Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint32Array'));
}
function encryptBlock(xk, block) {
(0, utils_ts_1.abytes)(block, 16);
if (!isBytes32(xk))
throw new Error('_encryptBlock accepts result of expandKeyLE');
const b32 = (0, utils_ts_1.u32)(block);
let { s0, s1, s2, s3 } = encrypt(xk, b32[0], b32[1], b32[2], b32[3]);
(b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3);
return block;
}
function decryptBlock(xk, block) {
(0, utils_ts_1.abytes)(block, 16);
if (!isBytes32(xk))
throw new Error('_decryptBlock accepts result of expandKeyLE');
const b32 = (0, utils_ts_1.u32)(block);
let { s0, s1, s2, s3 } = decrypt(xk, b32[0], b32[1], b32[2], b32[3]);
(b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3);
return block;
}
/**
* AES-W (base for AESKW/AESKWP).
* Specs: [SP800-38F](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf),
* [RFC 3394](https://datatracker.ietf.org/doc/rfc3394/),
* [RFC 5649](https://datatracker.ietf.org/doc/rfc5649/).
*/
const AESW = {
/*
High-level pseudocode:
```
A: u64 = IV
out = []
for (let i=0, ctr = 0; i<6; i++) {
for (const chunk of chunks(plaintext, 8)) {
A ^= swapEndianess(ctr++)
[A, res] = chunks(encrypt(A || chunk), 8);
out ||= res
}
}
out = A || out
```
Decrypt is the same, but reversed.
*/
encrypt(kek, out) {
// Size is limited to 4GB, otherwise ctr will overflow and we'll need to switch to bigints.
// If you need it larger, open an issue.
if (out.length >= 2 ** 32)
throw new Error('plaintext should be less than 4gb');
const xk = expandKeyLE(kek);
if (out.length === 16)
encryptBlock(xk, out);
else {
const o32 = (0, utils_ts_1.u32)(out);
// prettier-ignore
let a0 = o32[0], a1 = o32[1]; // A
for (let j = 0, ctr = 1; j < 6; j++) {
for (let pos = 2; pos < o32.length; pos += 2, ctr++) {
const { s0, s1, s2, s3 } = encrypt(xk, a0, a1, o32[pos], o32[pos + 1]);
// A = MSB(64, B) ^ t where t = (n*j)+i
(a0 = s0), (a1 = s1 ^ byteSwap(ctr)), (o32[pos] = s2), (o32[pos + 1] = s3);
}
}
(o32[0] = a0), (o32[1] = a1); // out = A || out
}
xk.fill(0);
},
decrypt(kek, out) {
if (out.length - 8 >= 2 ** 32)
throw new Error('ciphertext should be less than 4gb');
const xk = expandKeyDecLE(kek);
const chunks = out.length / 8 - 1; // first chunk is IV
if (chunks === 1)
decryptBlock(xk, out);
else {
const o32 = (0, utils_ts_1.u32)(out);
// prettier-ignore
let a0 = o32[0], a1 = o32[1]; // A
for (let j = 0, ctr = chunks * 6; j < 6; j++) {
for (let pos = chunks * 2; pos >= 1; pos -= 2, ctr--) {
a1 ^= byteSwap(ctr);
const { s0, s1, s2, s3 } = decrypt(xk, a0, a1, o32[pos], o32[pos + 1]);
(a0 = s0), (a1 = s1), (o32[pos] = s2), (o32[pos + 1] = s3);
}
}
(o32[0] = a0), (o32[1] = a1);
}
xk.fill(0);
},
};
const AESKW_IV = /* @__PURE__ */ new Uint8Array(8).fill(0xa6); // A6A6A6A6A6A6A6A6
/**
* AES-KW (key-wrap). Injects static IV into plaintext, adds counter, encrypts 6 times.
* Reduces block size from 16 to 8 bytes.
* For padded version, use aeskwp.
* [RFC 3394](https://datatracker.ietf.org/doc/rfc3394/),
* [NIST.SP.800-38F](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf).
*/
exports.aeskw = (0, utils_ts_1.wrapCipher)({ blockSize: 8 }, (kek) => ({
encrypt(plaintext) {
if (!plaintext.length || plaintext.length % 8 !== 0)
throw new Error('invalid plaintext length');
if (plaintext.length === 8)
throw new Error('8-byte keys not allowed in AESKW, use AESKWP instead');
const out = (0, utils_ts_1.concatBytes)(AESKW_IV, plaintext);
AESW.encrypt(kek, out);
return out;
},
decrypt(ciphertext) {
// ciphertext must be at least 24 bytes and a multiple of 8 bytes
// 24 because should have at least two block (1 iv + 2).
// Replace with 16 to enable '8-byte keys'
if (ciphertext.length % 8 !== 0 || ciphertext.length < 3 * 8)
throw new Error('invalid ciphertext length');
const out = (0, utils_ts_1.copyBytes)(ciphertext);
AESW.decrypt(kek, out);
if (!(0, utils_ts_1.equalBytes)(out.subarray(0, 8), AESKW_IV))
throw new Error('integrity check failed');
out.subarray(0, 8).fill(0); // ciphertext.subarray(0, 8) === IV, but we clean it anyway
return out.subarray(8);
},
}));
/*
We don't support 8-byte keys. The rabbit hole:
- Wycheproof says: "NIST SP 800-38F does not define the wrapping of 8 byte keys.
RFC 3394 Section 2 on the other hand specifies that 8 byte keys are wrapped
by directly encrypting one block with AES."
- https://github.com/C2SP/wycheproof/blob/master/doc/key_wrap.md
- "RFC 3394 specifies in Section 2, that the input for the key wrap
algorithm must be at least two blocks and otherwise the constant
field and key are simply encrypted with ECB as a single block"
- What RFC 3394 actually says (in Section 2):
- "Before being wrapped, the key data is parsed into n blocks of 64 bits.
The only restriction the key wrap algorithm places on n is that n be
at least two"
- "For key data with length less than or equal to 64 bits, the constant
field used in this specification and the key data form a single
128-bit codebook input making this key wrap unnecessary."
- Which means "assert(n >= 2)" and "use something else for 8 byte keys"
- NIST SP800-38F actually prohibits 8-byte in "5.3.1 Mandatory Limits".
It states that plaintext for KW should be "2 to 2^54 -1 semiblocks".
- So, where does "directly encrypt single block with AES" come from?
- Not RFC 3394. Pseudocode of key wrap in 2.2 explicitly uses
loop of 6 for any code path
- There is a weird W3C spec:
https://www.w3.org/TR/2002/REC-xmlenc-core-20021210/Overview.html#kw-aes128
- This spec is outdated, as admitted by Wycheproof authors
- There is RFC 5649 for padded key wrap, which is padding construction on
top of AESKW. In '4.1.2' it says: "If the padded plaintext contains exactly
eight octets, then prepend the AIV as defined in Section 3 above to P[1] and
encrypt the resulting 128-bit block using AES in ECB mode [Modes] with key
K (the KEK). In this case, the output is two 64-bit blocks C[0] and C[1]:"
- Browser subtle crypto is actually crashes on wrapping keys less than 16 bytes:
`Error: error:1C8000E6:Provider routines::invalid input length] { opensslErrorStack: [ 'error:030000BD:digital envelope routines::update error' ]`
In the end, seems like a bug in Wycheproof.
The 8-byte check can be easily disabled inside of AES_W.
*/
const AESKWP_IV = 0xa65959a6; // single u32le value
/**
* AES-KW, but with padding and allows random keys.
* Second u32 of IV is used as counter for length.
* [RFC 5649](https://www.rfc-editor.org/rfc/rfc5649)
*/
exports.aeskwp = (0, utils_ts_1.wrapCipher)({ blockSize: 8 }, (kek) => ({
encrypt(plaintext) {
if (!plaintext.length)
throw new Error('invalid plaintext length');
const padded = Math.ceil(plaintext.length / 8) * 8;
const out = new Uint8Array(8 + padded);
out.set(plaintext, 8);
const out32 = (0, utils_ts_1.u32)(out);
out32[0] = AESKWP_IV;
out32[1] = byteSwap(plaintext.length);
AESW.encrypt(kek, out);
return out;
},
decrypt(ciphertext) {
// 16 because should have at least one block
if (ciphertext.length < 16)
throw new Error('invalid ciphertext length');
const out = (0, utils_ts_1.copyBytes)(ciphertext);
const o32 = (0, utils_ts_1.u32)(out);
AESW.decrypt(kek, out);
const len = byteSwap(o32[1]) >>> 0;
const padded = Math.ceil(len / 8) * 8;
if (o32[0] !== AESKWP_IV || out.length - 8 !== padded)
throw new Error('integrity check failed');
for (let i = len; i < padded; i++)
if (out[8 + i] !== 0)
throw new Error('integrity check failed');
out.subarray(0, 8).fill(0); // ciphertext.subarray(0, 8) === IV, but we clean it anyway
return out.subarray(8, 8 + len);
},
}));
/** Unsafe low-level internal methods. May change at any time. */
exports.unsafe = {
expandKeyLE,
expandKeyDecLE,
encrypt,
decrypt,
encryptBlock,
decryptBlock,
ctrCounter,
ctr32,
};
//# sourceMappingURL=aes.js.map
File diff suppressed because one or more lines are too long
+56
View File
@@ -0,0 +1,56 @@
import { type ARXCipher, type CipherWithOutput, type XorStream } from './utils.ts';
/**
* hchacha helper method, used primarily in xchacha, to hash
* key and nonce into key' and nonce'.
* Same as chachaCore, but there doesn't seem to be a way to move the block
* out without 25% performance hit.
*/
export declare function hchacha(s: Uint32Array, k: Uint32Array, i: Uint32Array, o32: Uint32Array): void;
/**
* Original, non-RFC chacha20 from DJB. 8-byte nonce, 8-byte counter.
*/
export declare const chacha20orig: XorStream;
/**
* ChaCha stream cipher. Conforms to RFC 8439 (IETF, TLS). 12-byte nonce, 4-byte counter.
* With 12-byte nonce, it's not safe to use fill it with random (CSPRNG), due to collision chance.
*/
export declare const chacha20: XorStream;
/**
* XChaCha eXtended-nonce ChaCha. 24-byte nonce.
* With 24-byte nonce, it's safe to use fill it with random (CSPRNG).
* https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha
*/
export declare const xchacha20: XorStream;
/**
* Reduced 8-round chacha, described in original paper.
*/
export declare const chacha8: XorStream;
/**
* Reduced 12-round chacha, described in original paper.
*/
export declare const chacha12: XorStream;
/**
* AEAD algorithm from RFC 8439.
* Salsa20 and chacha (RFC 8439) use poly1305 differently.
* We could have composed them similar to:
* https://github.com/paulmillr/scure-base/blob/b266c73dde977b1dd7ef40ef7a23cc15aab526b3/index.ts#L250
* 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: XorStream) => (key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array) => CipherWithOutput;
/**
* ChaCha20-Poly1305 from RFC 8439.
*
* Unsafe to use random nonces under the same key, due to collision chance.
* Prefer XChaCha instead.
*/
export declare const chacha20poly1305: ARXCipher;
/**
* XChaCha20-Poly1305 extended-nonce chacha.
*
* Can be safely used with random nonces (CSPRNG).
* See [IRTF draft](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha).
*/
export declare const xchacha20poly1305: ARXCipher;
//# sourceMappingURL=chacha.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"chacha.d.ts","sourceRoot":"","sources":["src/chacha.ts"],"names":[],"mappings":"AAgBA,OAAO,EACL,KAAK,SAAS,EACd,KAAK,gBAAgB,EACrB,KAAK,SAAS,EAMf,MAAM,YAAY,CAAC;AAsEpB;;;;;GAKG;AAEH,wBAAgB,OAAO,CACrB,CAAC,EAAE,WAAW,EAAE,CAAC,EAAE,WAAW,EAAE,CAAC,EAAE,WAAW,EAAE,GAAG,EAAE,WAAW,GAC/D,IAAI,CAmDN;AACD;;GAEG;AACH,eAAO,MAAM,YAAY,EAAE,SAIzB,CAAC;AACH;;;GAGG;AACH,eAAO,MAAM,QAAQ,EAAE,SAIrB,CAAC;AAEH;;;;GAIG;AACH,eAAO,MAAM,SAAS,EAAE,SAKtB,CAAC;AAEH;;GAEG;AACH,eAAO,MAAM,OAAO,EAAE,SAIpB,CAAC;AAEH;;GAEG;AACH,eAAO,MAAM,QAAQ,EAAE,SAIrB,CAAC;AA6BH;;;;;;;;GAQG;AACH,eAAO,MAAM,cAAc,GACxB,WAAW,SAAS,MACpB,KAAK,UAAU,EAAE,OAAO,UAAU,EAAE,MAAM,UAAU,KAAG,gBA0BvD,CAAC;AAEJ;;;;;GAKG;AACH,eAAO,MAAM,gBAAgB,EAAE,SAG9B,CAAC;AACF;;;;;GAKG;AACH,eAAO,MAAM,iBAAiB,EAAE,SAG/B,CAAC"}
+320
View File
@@ -0,0 +1,320 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.xchacha20poly1305 = exports.chacha20poly1305 = exports._poly1305_aead = exports.chacha12 = exports.chacha8 = exports.xchacha20 = exports.chacha20 = exports.chacha20orig = void 0;
exports.hchacha = hchacha;
/**
* [ChaCha20](https://cr.yp.to/chacha.html) stream cipher, released
* in 2008. Developed after Salsa20, ChaCha aims to increase diffusion per round.
* It was standardized in [RFC 8439](https://datatracker.ietf.org/doc/html/rfc8439) and
* is now used in TLS 1.3.
*
* [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 [PDF](http://cr.yp.to/chacha/chacha-20080128.pdf) and
* [wiki](https://en.wikipedia.org/wiki/Salsa20).
* @module
*/
const _arx_ts_1 = require("./_arx.js");
const _poly1305_ts_1 = require("./_poly1305.js");
const utils_ts_1 = require("./utils.js");
/**
* ChaCha core function.
*/
// 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 Counter 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 = (0, _arx_ts_1.rotl)(x12 ^ x00, 16);
x08 = (x08 + x12) | 0;
x04 = (0, _arx_ts_1.rotl)(x04 ^ x08, 12);
x00 = (x00 + x04) | 0;
x12 = (0, _arx_ts_1.rotl)(x12 ^ x00, 8);
x08 = (x08 + x12) | 0;
x04 = (0, _arx_ts_1.rotl)(x04 ^ x08, 7);
x01 = (x01 + x05) | 0;
x13 = (0, _arx_ts_1.rotl)(x13 ^ x01, 16);
x09 = (x09 + x13) | 0;
x05 = (0, _arx_ts_1.rotl)(x05 ^ x09, 12);
x01 = (x01 + x05) | 0;
x13 = (0, _arx_ts_1.rotl)(x13 ^ x01, 8);
x09 = (x09 + x13) | 0;
x05 = (0, _arx_ts_1.rotl)(x05 ^ x09, 7);
x02 = (x02 + x06) | 0;
x14 = (0, _arx_ts_1.rotl)(x14 ^ x02, 16);
x10 = (x10 + x14) | 0;
x06 = (0, _arx_ts_1.rotl)(x06 ^ x10, 12);
x02 = (x02 + x06) | 0;
x14 = (0, _arx_ts_1.rotl)(x14 ^ x02, 8);
x10 = (x10 + x14) | 0;
x06 = (0, _arx_ts_1.rotl)(x06 ^ x10, 7);
x03 = (x03 + x07) | 0;
x15 = (0, _arx_ts_1.rotl)(x15 ^ x03, 16);
x11 = (x11 + x15) | 0;
x07 = (0, _arx_ts_1.rotl)(x07 ^ x11, 12);
x03 = (x03 + x07) | 0;
x15 = (0, _arx_ts_1.rotl)(x15 ^ x03, 8);
x11 = (x11 + x15) | 0;
x07 = (0, _arx_ts_1.rotl)(x07 ^ x11, 7);
x00 = (x00 + x05) | 0;
x15 = (0, _arx_ts_1.rotl)(x15 ^ x00, 16);
x10 = (x10 + x15) | 0;
x05 = (0, _arx_ts_1.rotl)(x05 ^ x10, 12);
x00 = (x00 + x05) | 0;
x15 = (0, _arx_ts_1.rotl)(x15 ^ x00, 8);
x10 = (x10 + x15) | 0;
x05 = (0, _arx_ts_1.rotl)(x05 ^ x10, 7);
x01 = (x01 + x06) | 0;
x12 = (0, _arx_ts_1.rotl)(x12 ^ x01, 16);
x11 = (x11 + x12) | 0;
x06 = (0, _arx_ts_1.rotl)(x06 ^ x11, 12);
x01 = (x01 + x06) | 0;
x12 = (0, _arx_ts_1.rotl)(x12 ^ x01, 8);
x11 = (x11 + x12) | 0;
x06 = (0, _arx_ts_1.rotl)(x06 ^ x11, 7);
x02 = (x02 + x07) | 0;
x13 = (0, _arx_ts_1.rotl)(x13 ^ x02, 16);
x08 = (x08 + x13) | 0;
x07 = (0, _arx_ts_1.rotl)(x07 ^ x08, 12);
x02 = (x02 + x07) | 0;
x13 = (0, _arx_ts_1.rotl)(x13 ^ x02, 8);
x08 = (x08 + x13) | 0;
x07 = (0, _arx_ts_1.rotl)(x07 ^ x08, 7);
x03 = (x03 + x04) | 0;
x14 = (0, _arx_ts_1.rotl)(x14 ^ x03, 16);
x09 = (x09 + x14) | 0;
x04 = (0, _arx_ts_1.rotl)(x04 ^ x09, 12);
x03 = (x03 + x04) | 0;
x14 = (0, _arx_ts_1.rotl)(x14 ^ x03, 8);
x09 = (x09 + x14) | 0;
x04 = (0, _arx_ts_1.rotl)(x04 ^ x09, 7);
}
// 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;
}
/**
* hchacha helper method, used primarily in xchacha, to hash
* key and nonce into key' and nonce'.
* Same as chachaCore, but there doesn't seem to be a way to move the block
* out without 25% performance hit.
*/
// prettier-ignore
function hchacha(s, k, i, o32) {
let x00 = s[0], x01 = s[1], x02 = s[2], x03 = s[3], x04 = k[0], x05 = k[1], x06 = k[2], x07 = k[3], x08 = k[4], x09 = k[5], x10 = k[6], x11 = k[7], x12 = i[0], x13 = i[1], x14 = i[2], x15 = i[3];
for (let r = 0; r < 20; r += 2) {
x00 = (x00 + x04) | 0;
x12 = (0, _arx_ts_1.rotl)(x12 ^ x00, 16);
x08 = (x08 + x12) | 0;
x04 = (0, _arx_ts_1.rotl)(x04 ^ x08, 12);
x00 = (x00 + x04) | 0;
x12 = (0, _arx_ts_1.rotl)(x12 ^ x00, 8);
x08 = (x08 + x12) | 0;
x04 = (0, _arx_ts_1.rotl)(x04 ^ x08, 7);
x01 = (x01 + x05) | 0;
x13 = (0, _arx_ts_1.rotl)(x13 ^ x01, 16);
x09 = (x09 + x13) | 0;
x05 = (0, _arx_ts_1.rotl)(x05 ^ x09, 12);
x01 = (x01 + x05) | 0;
x13 = (0, _arx_ts_1.rotl)(x13 ^ x01, 8);
x09 = (x09 + x13) | 0;
x05 = (0, _arx_ts_1.rotl)(x05 ^ x09, 7);
x02 = (x02 + x06) | 0;
x14 = (0, _arx_ts_1.rotl)(x14 ^ x02, 16);
x10 = (x10 + x14) | 0;
x06 = (0, _arx_ts_1.rotl)(x06 ^ x10, 12);
x02 = (x02 + x06) | 0;
x14 = (0, _arx_ts_1.rotl)(x14 ^ x02, 8);
x10 = (x10 + x14) | 0;
x06 = (0, _arx_ts_1.rotl)(x06 ^ x10, 7);
x03 = (x03 + x07) | 0;
x15 = (0, _arx_ts_1.rotl)(x15 ^ x03, 16);
x11 = (x11 + x15) | 0;
x07 = (0, _arx_ts_1.rotl)(x07 ^ x11, 12);
x03 = (x03 + x07) | 0;
x15 = (0, _arx_ts_1.rotl)(x15 ^ x03, 8);
x11 = (x11 + x15) | 0;
x07 = (0, _arx_ts_1.rotl)(x07 ^ x11, 7);
x00 = (x00 + x05) | 0;
x15 = (0, _arx_ts_1.rotl)(x15 ^ x00, 16);
x10 = (x10 + x15) | 0;
x05 = (0, _arx_ts_1.rotl)(x05 ^ x10, 12);
x00 = (x00 + x05) | 0;
x15 = (0, _arx_ts_1.rotl)(x15 ^ x00, 8);
x10 = (x10 + x15) | 0;
x05 = (0, _arx_ts_1.rotl)(x05 ^ x10, 7);
x01 = (x01 + x06) | 0;
x12 = (0, _arx_ts_1.rotl)(x12 ^ x01, 16);
x11 = (x11 + x12) | 0;
x06 = (0, _arx_ts_1.rotl)(x06 ^ x11, 12);
x01 = (x01 + x06) | 0;
x12 = (0, _arx_ts_1.rotl)(x12 ^ x01, 8);
x11 = (x11 + x12) | 0;
x06 = (0, _arx_ts_1.rotl)(x06 ^ x11, 7);
x02 = (x02 + x07) | 0;
x13 = (0, _arx_ts_1.rotl)(x13 ^ x02, 16);
x08 = (x08 + x13) | 0;
x07 = (0, _arx_ts_1.rotl)(x07 ^ x08, 12);
x02 = (x02 + x07) | 0;
x13 = (0, _arx_ts_1.rotl)(x13 ^ x02, 8);
x08 = (x08 + x13) | 0;
x07 = (0, _arx_ts_1.rotl)(x07 ^ x08, 7);
x03 = (x03 + x04) | 0;
x14 = (0, _arx_ts_1.rotl)(x14 ^ x03, 16);
x09 = (x09 + x14) | 0;
x04 = (0, _arx_ts_1.rotl)(x04 ^ x09, 12);
x03 = (x03 + x04) | 0;
x14 = (0, _arx_ts_1.rotl)(x14 ^ x03, 8);
x09 = (x09 + x14) | 0;
x04 = (0, _arx_ts_1.rotl)(x04 ^ x09, 7);
}
let oi = 0;
o32[oi++] = x00;
o32[oi++] = x01;
o32[oi++] = x02;
o32[oi++] = x03;
o32[oi++] = x12;
o32[oi++] = x13;
o32[oi++] = x14;
o32[oi++] = x15;
}
/**
* Original, non-RFC chacha20 from DJB. 8-byte nonce, 8-byte counter.
*/
exports.chacha20orig = (0, _arx_ts_1.createCipher)(chachaCore, {
counterRight: false,
counterLength: 8,
allowShortKeys: true,
});
/**
* ChaCha stream cipher. Conforms to RFC 8439 (IETF, TLS). 12-byte nonce, 4-byte counter.
* With 12-byte nonce, it's not safe to use fill it with random (CSPRNG), due to collision chance.
*/
exports.chacha20 = (0, _arx_ts_1.createCipher)(chachaCore, {
counterRight: false,
counterLength: 4,
allowShortKeys: false,
});
/**
* XChaCha eXtended-nonce ChaCha. 24-byte nonce.
* With 24-byte nonce, it's safe to use fill it with random (CSPRNG).
* https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha
*/
exports.xchacha20 = (0, _arx_ts_1.createCipher)(chachaCore, {
counterRight: false,
counterLength: 8,
extendNonceFn: hchacha,
allowShortKeys: false,
});
/**
* Reduced 8-round chacha, described in original paper.
*/
exports.chacha8 = (0, _arx_ts_1.createCipher)(chachaCore, {
counterRight: false,
counterLength: 4,
rounds: 8,
});
/**
* Reduced 12-round chacha, described in original paper.
*/
exports.chacha12 = (0, _arx_ts_1.createCipher)(chachaCore, {
counterRight: false,
counterLength: 4,
rounds: 12,
});
const ZEROS16 = /* @__PURE__ */ new Uint8Array(16);
// Pad to digest size with zeros
const updatePadded = (h, msg) => {
h.update(msg);
const left = msg.length % 16;
if (left)
h.update(ZEROS16.subarray(left));
};
const ZEROS32 = /* @__PURE__ */ new Uint8Array(32);
function computeTag(fn, key, nonce, data, AAD) {
const authKey = fn(key, nonce, ZEROS32);
const h = _poly1305_ts_1.poly1305.create(authKey);
if (AAD)
updatePadded(h, AAD);
updatePadded(h, data);
const num = (0, utils_ts_1.u64Lengths)(data.length, AAD ? AAD.length : 0, true);
h.update(num);
const res = h.digest();
(0, utils_ts_1.clean)(authKey, num);
return res;
}
/**
* AEAD algorithm from RFC 8439.
* Salsa20 and chacha (RFC 8439) use poly1305 differently.
* We could have composed them similar to:
* https://github.com/paulmillr/scure-base/blob/b266c73dde977b1dd7ef40ef7a23cc15aab526b3/index.ts#L250
* 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.
*/
const _poly1305_aead = (xorStream) => (key, nonce, AAD) => {
const tagLength = 16;
return {
encrypt(plaintext, output) {
const plength = plaintext.length;
output = (0, utils_ts_1.getOutput)(plength + tagLength, output, false);
output.set(plaintext);
const oPlain = output.subarray(0, -tagLength);
xorStream(key, nonce, oPlain, oPlain, 1);
const tag = computeTag(xorStream, key, nonce, oPlain, AAD);
output.set(tag, plength); // append tag
(0, utils_ts_1.clean)(tag);
return output;
},
decrypt(ciphertext, output) {
output = (0, utils_ts_1.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);
if (!(0, utils_ts_1.equalBytes)(passedTag, tag))
throw new Error('invalid tag');
output.set(ciphertext.subarray(0, -tagLength));
xorStream(key, nonce, output, output, 1); // start stream with i=1
(0, utils_ts_1.clean)(tag);
return output;
},
};
};
exports._poly1305_aead = _poly1305_aead;
/**
* ChaCha20-Poly1305 from RFC 8439.
*
* Unsafe to use random nonces under the same key, due to collision chance.
* Prefer XChaCha instead.
*/
exports.chacha20poly1305 = (0, utils_ts_1.wrapCipher)({ blockSize: 64, nonceLength: 12, tagLength: 16 }, (0, exports._poly1305_aead)(exports.chacha20));
/**
* XChaCha20-Poly1305 extended-nonce chacha.
*
* Can be safely used with random nonces (CSPRNG).
* See [IRTF draft](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha).
*/
exports.xchacha20poly1305 = (0, utils_ts_1.wrapCipher)({ blockSize: 64, nonceLength: 24, tagLength: 16 }, (0, exports._poly1305_aead)(exports.xchacha20));
//# sourceMappingURL=chacha.js.map
File diff suppressed because one or more lines are too long
+2
View File
@@ -0,0 +1,2 @@
export declare const crypto: any;
//# sourceMappingURL=crypto.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"crypto.d.ts","sourceRoot":"","sources":["src/crypto.ts"],"names":[],"mappings":"AAOA,eAAO,MAAM,MAAM,EAAE,GACqE,CAAC"}
+5
View File
@@ -0,0 +1,5 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.crypto = void 0;
exports.crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
//# sourceMappingURL=crypto.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"crypto.js","sourceRoot":"","sources":["src/crypto.ts"],"names":[],"mappings":";;;AAOa,QAAA,MAAM,GACjB,OAAO,UAAU,KAAK,QAAQ,IAAI,QAAQ,IAAI,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC"}
+2
View File
@@ -0,0 +1,2 @@
export declare const crypto: any;
//# sourceMappingURL=cryptoNode.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"cryptoNode.d.ts","sourceRoot":"","sources":["src/cryptoNode.ts"],"names":[],"mappings":"AASA,eAAO,MAAM,MAAM,EAAE,GAKJ,CAAC"}
+18
View File
@@ -0,0 +1,18 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.crypto = void 0;
/**
* Internal webcrypto alias.
* We prefer WebCrypto aka globalThis.crypto, which exists in node.js 16+.
* Falls back to Node.js built-in crypto for Node.js <=v14.
* See utils.ts for details.
* @module
*/
// @ts-ignore
const nc = require("node:crypto");
exports.crypto = nc && typeof nc === 'object' && 'webcrypto' in nc
? nc.webcrypto
: nc && typeof nc === 'object' && 'randomBytes' in nc
? nc
: undefined;
//# sourceMappingURL=cryptoNode.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"cryptoNode.js","sourceRoot":"","sources":["src/cryptoNode.ts"],"names":[],"mappings":";;;AAAA;;;;;;GAMG;AACH,aAAa;AACb,kCAAkC;AACrB,QAAA,MAAM,GACjB,EAAE,IAAI,OAAO,EAAE,KAAK,QAAQ,IAAI,WAAW,IAAI,EAAE;IAC/C,CAAC,CAAE,EAAE,CAAC,SAAiB;IACvB,CAAC,CAAC,EAAE,IAAI,OAAO,EAAE,KAAK,QAAQ,IAAI,aAAa,IAAI,EAAE;QACnD,CAAC,CAAC,EAAE;QACJ,CAAC,CAAC,SAAS,CAAC"}
+59
View File
@@ -0,0 +1,59 @@
/**
* 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) | ctr(2) | s[2] | k(4) | s[3]
chacha: s(4) | k(8) | ctr(1) | nonce(3)
chacha20orig: s(4) | k(8) | ctr(2) | nonce(2)
- Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)`
- Caveat: we can't re-use counter array
xchacha [^2] uses the subkey and remaining 8 byte nonce with ChaCha20 as normal
(prefixed by 4 NUL bytes, since [RFC8439] specifies a 12-byte nonce).
[^1]: https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/
[^2]: https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2
* @module
*/
import { type XorStream } from './utils.ts';
export declare function rotl(a: number, b: number): number;
/** Ciphers must use u32 for efficiency. */
export type CipherCoreFn = (sigma: Uint32Array, key: Uint32Array, nonce: Uint32Array, output: Uint32Array, counter: number, rounds?: number) => void;
/** Method which extends key + short nonce into larger nonce / diff key. */
export type ExtendNonceFn = (sigma: Uint32Array, key: Uint32Array, input: Uint32Array, output: Uint32Array) => void;
/** ARX cipher options.
* * `allowShortKeys` for 16-byte keys
* * `counterLength` in bytes
* * `counterRight`: right: `nonce|counter`; left: `counter|nonce`
* */
export type CipherOpts = {
allowShortKeys?: boolean;
extendNonceFn?: ExtendNonceFn;
counterLength?: number;
counterRight?: boolean;
rounds?: number;
};
/** Creates ARX-like (ChaCha, Salsa) cipher stream from core function. */
export declare function createCipher(core: CipherCoreFn, opts: CipherOpts): XorStream;
//# sourceMappingURL=_arx.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"_arx.d.ts","sourceRoot":"","sources":["../src/_arx.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AAEH,OAAO,EACL,KAAK,SAAS,EACf,MAAM,YAAY,CAAC;AAUpB,wBAAgB,IAAI,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CAEjD;AAED,2CAA2C;AAC3C,MAAM,MAAM,YAAY,GAAG,CACzB,KAAK,EAAE,WAAW,EAClB,GAAG,EAAE,WAAW,EAChB,KAAK,EAAE,WAAW,EAClB,MAAM,EAAE,WAAW,EACnB,OAAO,EAAE,MAAM,EACf,MAAM,CAAC,EAAE,MAAM,KACZ,IAAI,CAAC;AAEV,2EAA2E;AAC3E,MAAM,MAAM,aAAa,GAAG,CAC1B,KAAK,EAAE,WAAW,EAClB,GAAG,EAAE,WAAW,EAChB,KAAK,EAAE,WAAW,EAClB,MAAM,EAAE,WAAW,KAChB,IAAI,CAAC;AAEV;;;;KAIK;AACL,MAAM,MAAM,UAAU,GAAG;IACvB,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,aAAa,CAAC,EAAE,aAAa,CAAC;IAC9B,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,CAAC;AAwDF,yEAAyE;AACzE,wBAAgB,YAAY,CAAC,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,UAAU,GAAG,SAAS,CAkF5E"}
+171
View File
@@ -0,0 +1,171 @@
/**
* 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) | ctr(2) | s[2] | k(4) | s[3]
chacha: s(4) | k(8) | ctr(1) | nonce(3)
chacha20orig: s(4) | k(8) | ctr(2) | nonce(2)
- Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)`
- Caveat: we can't re-use counter array
xchacha [^2] uses the subkey and remaining 8 byte nonce with ChaCha20 as normal
(prefixed by 4 NUL bytes, since [RFC8439] specifies a 12-byte nonce).
[^1]: https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/
[^2]: https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2
* @module
*/
// prettier-ignore
import { abool, abytes, anumber, checkOpts, clean, copyBytes, u32 } from "./utils.js";
// We can't make top-level var depend on utils.utf8ToBytes
// because it's not present in all envs. Creating a similar fn here
const _utf8ToBytes = (str) => Uint8Array.from(str.split('').map((c) => c.charCodeAt(0)));
const sigma16 = _utf8ToBytes('expand 16-byte k');
const sigma32 = _utf8ToBytes('expand 32-byte k');
const sigma16_32 = u32(sigma16);
const sigma32_32 = u32(sigma32);
export function rotl(a, b) {
return (a << b) | (a >>> (32 - b));
}
// Is byte array aligned to 4 byte offset (u32)?
function isAligned32(b) {
return b.byteOffset % 4 === 0;
}
// Salsa and Chacha block length is always 512-bit
const BLOCK_LEN = 64;
const BLOCK_LEN32 = 16;
// new Uint32Array([2**32]) // => Uint32Array(1) [ 0 ]
// new Uint32Array([2**32-1]) // => Uint32Array(1) [ 4294967295 ]
const MAX_COUNTER = 2 ** 32 - 1;
const U32_EMPTY = new Uint32Array();
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 = isAligned32(data) && isAligned32(output);
const d32 = isAligned ? u32(data) : U32_EMPTY;
const o32 = isAligned ? u32(output) : U32_EMPTY;
for (let pos = 0; pos < len; counter++) {
core(sigma, key, nonce, b32, counter, rounds);
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 ARX-like (ChaCha, Salsa) cipher stream from core function. */
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);
abytes(nonce);
abytes(data);
const len = data.length;
if (output === undefined)
output = new Uint8Array(len);
abytes(output);
anumber(counter);
if (counter < 0 || counter >= MAX_COUNTER)
throw new Error('arx: counter overflow');
if (output.length < len)
throw new Error(`arx: output (${output.length}) is shorter than data (${len})`);
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) {
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 {
throw new Error(`arx: invalid 32-byte key, 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)
// Align nonce to 4 bytes
if (!isAligned32(nonce))
toClean.push((nonce = copyBytes(nonce)));
const k32 = u32(k);
// hsalsa & hchacha: handle extended nonce
if (extendNonceFn) {
if (nonce.length !== 24)
throw new Error(`arx: extended nonce must be 24 bytes`);
extendNonceFn(sigma, k32, u32(nonce.subarray(0, 16)), k32);
nonce = nonce.subarray(16);
}
// Handle nonce counter
const nonceNcLen = 16 - counterLength;
if (nonceNcLen !== nonce.length)
throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);
// Pad counter when nonce is 64 bit
if (nonceNcLen !== 12) {
const nc = new Uint8Array(12);
nc.set(nonce, counterRight ? 0 : 12 - nonce.length);
nonce = nc;
toClean.push(nonce);
}
const n32 = u32(nonce);
runCipher(core, sigma, k32, n32, data, output, counter, rounds);
clean(...toClean);
return output;
};
}
//# sourceMappingURL=_arx.js.map
File diff suppressed because one or more lines are too long
+19
View File
@@ -0,0 +1,19 @@
/**
* Internal assertion helpers.
* @module
* @deprecated
*/
import { abytes as ab, abool as abool_, aexists as ae, anumber as an, aoutput as ao, type IHash as H } from './utils.ts';
/** @deprecated Use import from `noble/hashes/utils` module */
export declare const abool: typeof abool_;
/** @deprecated Use import from `noble/hashes/utils` module */
export declare const abytes: typeof ab;
/** @deprecated Use import from `noble/hashes/utils` module */
export declare const aexists: typeof ae;
/** @deprecated Use import from `noble/hashes/utils` module */
export declare const anumber: typeof an;
/** @deprecated Use import from `noble/hashes/utils` module */
export declare const aoutput: typeof ao;
/** @deprecated Use import from `noble/hashes/utils` module */
export type Hash = H;
//# sourceMappingURL=_assert.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"_assert.d.ts","sourceRoot":"","sources":["../src/_assert.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EACL,MAAM,IAAI,EAAE,EACZ,KAAK,IAAI,MAAM,EACf,OAAO,IAAI,EAAE,EACb,OAAO,IAAI,EAAE,EACb,OAAO,IAAI,EAAE,EACb,KAAK,KAAK,IAAI,CAAC,EAChB,MAAM,YAAY,CAAC;AACpB,8DAA8D;AAC9D,eAAO,MAAM,KAAK,EAAE,OAAO,MAAe,CAAC;AAC3C,8DAA8D;AAC9D,eAAO,MAAM,MAAM,EAAE,OAAO,EAAO,CAAC;AACpC,8DAA8D;AAC9D,eAAO,MAAM,OAAO,EAAE,OAAO,EAAO,CAAC;AACrC,8DAA8D;AAC9D,eAAO,MAAM,OAAO,EAAE,OAAO,EAAO,CAAC;AACrC,8DAA8D;AAC9D,eAAO,MAAM,OAAO,EAAE,OAAO,EAAO,CAAC;AACrC,8DAA8D;AAC9D,MAAM,MAAM,IAAI,GAAG,CAAC,CAAC"}
+17
View File
@@ -0,0 +1,17 @@
/**
* Internal assertion helpers.
* @module
* @deprecated
*/
import { abytes as ab, abool as abool_, aexists as ae, anumber as an, aoutput as ao, } from "./utils.js";
/** @deprecated Use import from `noble/hashes/utils` module */
export const abool = abool_;
/** @deprecated Use import from `noble/hashes/utils` module */
export const abytes = ab;
/** @deprecated Use import from `noble/hashes/utils` module */
export const aexists = ae;
/** @deprecated Use import from `noble/hashes/utils` module */
export const anumber = an;
/** @deprecated Use import from `noble/hashes/utils` module */
export const aoutput = ao;
//# sourceMappingURL=_assert.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"_assert.js","sourceRoot":"","sources":["../src/_assert.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EACL,MAAM,IAAI,EAAE,EACZ,KAAK,IAAI,MAAM,EACf,OAAO,IAAI,EAAE,EACb,OAAO,IAAI,EAAE,EACb,OAAO,IAAI,EAAE,GAEd,MAAM,YAAY,CAAC;AACpB,8DAA8D;AAC9D,MAAM,CAAC,MAAM,KAAK,GAAkB,MAAM,CAAC;AAC3C,8DAA8D;AAC9D,MAAM,CAAC,MAAM,MAAM,GAAc,EAAE,CAAC;AACpC,8DAA8D;AAC9D,MAAM,CAAC,MAAM,OAAO,GAAc,EAAE,CAAC;AACrC,8DAA8D;AAC9D,MAAM,CAAC,MAAM,OAAO,GAAc,EAAE,CAAC;AACrC,8DAA8D;AAC9D,MAAM,CAAC,MAAM,OAAO,GAAc,EAAE,CAAC"}
+41
View File
@@ -0,0 +1,41 @@
import { type Cipher, type XorStream } from './utils.ts';
export type ARXCipherN = ((key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array) => Cipher) & {
blockSize: number;
nonceLength: number;
tagLength: number;
};
/** hsalsa hashes key and nonce into key' and nonce'. */
export declare function hsalsa(s: Uint32Array, k: Uint32Array, i: Uint32Array, o32: Uint32Array): void;
/** hchacha hashes key and nonce into key' and nonce'. */
export declare function hchacha(s: Uint32Array, k: Uint32Array, i: Uint32Array, o32: Uint32Array): void;
/** salsa20, 12-byte nonce. */
export declare const salsa20: XorStream;
/** xsalsa20, 24-byte nonce. */
export declare const xsalsa20: XorStream;
/** chacha20 non-RFC, original version by djb. 8-byte nonce, 8-byte counter. */
export declare const chacha20orig: XorStream;
/** chacha20 RFC 8439 (IETF / TLS). 12-byte nonce, 4-byte counter. */
export declare const chacha20: XorStream;
/** xchacha20 eXtended-nonce. https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha */
export declare const xchacha20: XorStream;
/** 8-round chacha from the original paper. */
export declare const chacha8: XorStream;
/** 12-round chacha from the original paper. */
export declare const chacha12: XorStream;
/** Poly1305 polynomial MAC. Can be speed-up using BigUint64Array, at the cost of complexity. */
export declare function poly1305(msg: Uint8Array, key: Uint8Array): Uint8Array;
/** xsalsa20-poly1305 eXtended-nonce (24 bytes) salsa. */
export declare const xsalsa20poly1305: ARXCipherN;
/** Alias to `xsalsa20poly1305`. */
export declare function secretbox(key: Uint8Array, nonce: Uint8Array): {
seal: (plaintext: Uint8Array) => Uint8Array;
open: (ciphertext: Uint8Array) => Uint8Array;
};
export declare const _poly1305_aead: (fn: XorStream) => (key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array) => Cipher;
/** chacha20-poly1305 12-byte-nonce chacha. */
export declare const chacha20poly1305: ARXCipherN;
/**
* XChaCha20-Poly1305 extended-nonce chacha. Can be safely used with random nonces (CSPRNG).
*/
export declare const xchacha20poly1305: ARXCipherN;
//# sourceMappingURL=_micro.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"_micro.d.ts","sourceRoot":"","sources":["../src/_micro.ts"],"names":[],"mappings":"AASA,OAAO,EACL,KAAK,MAAM,EACX,KAAK,SAAS,EASf,MAAM,YAAY,CAAC;AAEpB,MAAM,MAAM,UAAU,GAAG,CAAC,CAAC,GAAG,EAAE,UAAU,EAAE,KAAK,EAAE,UAAU,EAAE,GAAG,CAAC,EAAE,UAAU,KAAK,MAAM,CAAC,GAAG;IAC5F,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,MAAM,CAAC;CACnB,CAAC;AAuEF,wDAAwD;AAExD,wBAAgB,MAAM,CAAC,CAAC,EAAE,WAAW,EAAE,CAAC,EAAE,WAAW,EAAE,CAAC,EAAE,WAAW,EAAE,GAAG,EAAE,WAAW,GAAG,IAAI,CAa7F;AAsBD,yDAAyD;AAEzD,wBAAgB,OAAO,CAAC,CAAC,EAAE,WAAW,EAAE,CAAC,EAAE,WAAW,EAAE,CAAC,EAAE,WAAW,EAAE,GAAG,EAAE,WAAW,GAAG,IAAI,CAa9F;AAED,8BAA8B;AAC9B,eAAO,MAAM,OAAO,EAAE,SAGpB,CAAC;AAEH,+BAA+B;AAC/B,eAAO,MAAM,QAAQ,EAAE,SAGrB,CAAC;AAEH,+EAA+E;AAC/E,eAAO,MAAM,YAAY,EAAE,SAIzB,CAAC;AAEH,qEAAqE;AACrE,eAAO,MAAM,QAAQ,EAAE,SAGrB,CAAC;AAEH,8FAA8F;AAC9F,eAAO,MAAM,SAAS,EAAE,SAItB,CAAC;AAEH,8CAA8C;AAC9C,eAAO,MAAM,OAAO,EAAE,SAIpB,CAAC;AAEH,+CAA+C;AAC/C,eAAO,MAAM,QAAQ,EAAE,SAIrB,CAAC;AAQH,gGAAgG;AAChG,wBAAgB,QAAQ,CAAC,GAAG,EAAE,UAAU,EAAE,GAAG,EAAE,UAAU,GAAG,UAAU,CAcrE;AAuBD,yDAAyD;AACzD,eAAO,MAAM,gBAAgB,EAAE,UAsB9B,CAAC;AAEF,mCAAmC;AACnC,wBAAgB,SAAS,CACvB,GAAG,EAAE,UAAU,EACf,KAAK,EAAE,UAAU,GAChB;IACD,IAAI,EAAE,CAAC,SAAS,EAAE,UAAU,KAAK,UAAU,CAAC;IAC5C,IAAI,EAAE,CAAC,UAAU,EAAE,UAAU,KAAK,UAAU,CAAC;CAC9C,CAGA;AAED,eAAO,MAAM,cAAc,GACxB,IAAI,SAAS,MACb,KAAK,UAAU,EAAE,OAAO,UAAU,EAAE,MAAM,UAAU,KAAG,MAgBvD,CAAC;AAEJ,8CAA8C;AAC9C,eAAO,MAAM,gBAAgB,EAAE,UAG9B,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,iBAAiB,EAAE,UAG/B,CAAC"}
+252
View File
@@ -0,0 +1,252 @@
/**
* noble-ciphers-micro: more auditable, but 4x slower version of salsa20, chacha & poly1305.
* Implements the same algorithms that are present in other files, but without
* unrolled loops (https://en.wikipedia.org/wiki/Loop_unrolling).
* @module
*/
/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
// prettier-ignore
import { createCipher, rotl } from "./_arx.js";
import { abytes, bytesToHex, concatBytes, equalBytes, hexToNumber, numberToBytesBE, u64Lengths, wrapCipher, } from "./utils.js";
function bytesToNumberLE(bytes) {
abytes(bytes);
return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
}
function numberToBytesLE(n, len) {
return numberToBytesBE(n, len).reverse();
}
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);
}
// 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);
}
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);
}
}
function chachaRound(x, rounds = 20) {
for (let r = 0; r < rounds; r += 2) {
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);
}
}
function salsaCore(s, k, n, out, cnt, rounds = 20) {
// prettier-ignore
const y = new Uint32Array([
s[0], k[0], k[1], k[2], // "expa" Key Key Key
k[3], s[1], n[0], n[1], // Key "nd 3" Nonce Nonce
cnt, 0, s[2], k[4], // Pos. Pos. "2-by" Key
k[5], k[6], k[7], s[3], // Key Key Key "te k"
]);
const x = y.slice();
salsaRound(x, rounds);
for (let i = 0; i < 16; i++)
out[i] = (y[i] + x[i]) | 0;
}
/** hsalsa hashes key and nonce into key' and nonce'. */
// prettier-ignore
export function hsalsa(s, k, i, o32) {
const x = new Uint32Array([
s[0], k[0], k[1], k[2],
k[3], s[1], i[0], i[1],
i[2], i[3], s[2], k[4],
k[5], k[6], k[7], s[3]
]);
salsaRound(x, 20);
let oi = 0;
o32[oi++] = x[0];
o32[oi++] = x[5];
o32[oi++] = x[10];
o32[oi++] = x[15];
o32[oi++] = x[6];
o32[oi++] = x[7];
o32[oi++] = x[8];
o32[oi++] = x[9];
}
function chachaCore(s, k, n, out, cnt, rounds = 20) {
// prettier-ignore
const y = new Uint32Array([
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
cnt, n[0], n[1], n[2], // Counter Counter Nonce Nonce
]);
const x = y.slice();
chachaRound(x, rounds);
for (let i = 0; i < 16; i++)
out[i] = (y[i] + x[i]) | 0;
}
/** hchacha hashes key and nonce into key' and nonce'. */
// prettier-ignore
export function hchacha(s, k, i, o32) {
const x = new Uint32Array([
s[0], s[1], s[2], s[3],
k[0], k[1], k[2], k[3],
k[4], k[5], k[6], k[7],
i[0], i[1], i[2], i[3],
]);
chachaRound(x, 20);
let oi = 0;
o32[oi++] = x[0];
o32[oi++] = x[1];
o32[oi++] = x[2];
o32[oi++] = x[3];
o32[oi++] = x[12];
o32[oi++] = x[13];
o32[oi++] = x[14];
o32[oi++] = x[15];
}
/** salsa20, 12-byte nonce. */
export const salsa20 = /* @__PURE__ */ createCipher(salsaCore, {
allowShortKeys: true,
counterRight: true,
});
/** xsalsa20, 24-byte nonce. */
export const xsalsa20 = /* @__PURE__ */ createCipher(salsaCore, {
counterRight: true,
extendNonceFn: hsalsa,
});
/** chacha20 non-RFC, original version by djb. 8-byte nonce, 8-byte counter. */
export const chacha20orig = /* @__PURE__ */ createCipher(chachaCore, {
allowShortKeys: true,
counterRight: false,
counterLength: 8,
});
/** chacha20 RFC 8439 (IETF / TLS). 12-byte nonce, 4-byte counter. */
export const chacha20 = /* @__PURE__ */ createCipher(chachaCore, {
counterRight: false,
counterLength: 4,
});
/** xchacha20 eXtended-nonce. https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha */
export const xchacha20 = /* @__PURE__ */ createCipher(chachaCore, {
counterRight: false,
counterLength: 8,
extendNonceFn: hchacha,
});
/** 8-round chacha from the original paper. */
export const chacha8 = /* @__PURE__ */ createCipher(chachaCore, {
counterRight: false,
counterLength: 4,
rounds: 8,
});
/** 12-round chacha from the original paper. */
export const chacha12 = /* @__PURE__ */ createCipher(chachaCore, {
counterRight: false,
counterLength: 4,
rounds: 12,
});
const POW_2_130_5 = BigInt(2) ** BigInt(130) - BigInt(5);
const POW_2_128_1 = BigInt(2) ** BigInt(16 * 8) - BigInt(1);
const CLAMP_R = BigInt('0x0ffffffc0ffffffc0ffffffc0fffffff');
const _0 = BigInt(0);
const _1 = BigInt(1);
/** Poly1305 polynomial MAC. Can be speed-up using BigUint64Array, at the cost of complexity. */
export function poly1305(msg, key) {
abytes(msg);
abytes(key, 32);
let acc = _0;
const r = bytesToNumberLE(key.subarray(0, 16)) & CLAMP_R;
const s = bytesToNumberLE(key.subarray(16));
// Process by 16 byte chunks
for (let i = 0; i < msg.length; i += 16) {
const m = msg.subarray(i, i + 16);
const n = bytesToNumberLE(m) | (_1 << BigInt(8 * m.length));
acc = ((acc + n) * r) % POW_2_130_5;
}
const res = (acc + s) & POW_2_128_1;
return numberToBytesLE(res, 16);
}
function computeTag(fn, key, nonce, ciphertext, AAD) {
const res = [];
if (AAD) {
res.push(AAD);
const leftover = AAD.length % 16;
if (leftover > 0)
res.push(new Uint8Array(16 - leftover));
}
res.push(ciphertext);
const leftover = ciphertext.length % 16;
if (leftover > 0)
res.push(new Uint8Array(16 - leftover));
res.push(u64Lengths(ciphertext.length, AAD ? AAD.length : 0, true));
const authKey = fn(key, nonce, new Uint8Array(32));
return poly1305(concatBytes(...res), authKey);
}
/** xsalsa20-poly1305 eXtended-nonce (24 bytes) salsa. */
export const xsalsa20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 24, tagLength: 16 }, function xsalsapoly(key, nonce) {
return {
encrypt(plaintext) {
const m = concatBytes(new Uint8Array(32), plaintext);
const c = xsalsa20(key, nonce, m);
const authKey = c.subarray(0, 32);
const data = c.subarray(32);
const tag = poly1305(data, authKey);
return concatBytes(tag, data);
},
decrypt(ciphertext) {
const c = concatBytes(new Uint8Array(16), ciphertext);
const passedTag = c.subarray(16, 32);
const authKey = xsalsa20(key, nonce, new Uint8Array(32));
const tag = poly1305(c.subarray(32), authKey);
if (!equalBytes(tag, passedTag))
throw new Error('invalid poly1305 tag');
return xsalsa20(key, nonce, c).subarray(32);
},
};
});
/** Alias to `xsalsa20poly1305`. */
export function secretbox(key, nonce) {
const xs = xsalsa20poly1305(key, nonce);
return { seal: xs.encrypt, open: xs.decrypt };
}
export const _poly1305_aead = (fn) => (key, nonce, AAD) => {
const tagLength = 16;
return {
encrypt(plaintext) {
const data = fn(key, nonce, plaintext, undefined, 1); // stream from i=1
const tag = computeTag(fn, key, nonce, data, AAD);
return concatBytes(data, tag);
},
decrypt(ciphertext) {
const passedTag = ciphertext.subarray(-tagLength);
const data = ciphertext.subarray(0, -tagLength);
const tag = computeTag(fn, key, nonce, data, AAD);
if (!equalBytes(tag, passedTag))
throw new Error('invalid poly1305 tag');
return fn(key, nonce, data, undefined, 1); // stream from i=1
},
};
};
/** chacha20-poly1305 12-byte-nonce chacha. */
export const chacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 12, tagLength: 16 }, _poly1305_aead(chacha20));
/**
* XChaCha20-Poly1305 extended-nonce chacha. Can be safely used with random nonces (CSPRNG).
*/
export const xchacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 24, tagLength: 16 }, _poly1305_aead(xchacha20));
//# sourceMappingURL=_micro.js.map
File diff suppressed because one or more lines are too long
+29
View File
@@ -0,0 +1,29 @@
/**
* Poly1305 ([PDF](https://cr.yp.to/mac/poly1305-20050329.pdf),
* [wiki](https://en.wikipedia.org/wiki/Poly1305))
* is a fast and parallel secret-key message-authentication code suitable for
* a wide variety of applications. It was standardized in
* [RFC 8439](https://datatracker.ietf.org/doc/html/rfc8439) 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 [invisible salamanders attack](https://keymaterial.net/2020/09/07/invisible-salamanders-in-aes-gcm-siv/).
* 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 [original website](https://cr.yp.to/mac.html).
* @module
*/
import { Hash, type Input } from './utils.ts';
export type CHash = ReturnType<typeof wrapConstructorWithKey>;
export declare function wrapConstructorWithKey<H extends Hash<H>>(hashCons: (key: Input) => Hash<H>): {
(msg: Input, key: Input): Uint8Array;
outputLen: number;
blockLen: number;
create(key: Input): Hash<H>;
};
/** Poly1305 MAC from RFC 8439. */
export declare const poly1305: CHash;
//# sourceMappingURL=_poly1305.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"_poly1305.d.ts","sourceRoot":"","sources":["../src/_poly1305.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AACH,OAAO,EAAE,IAAI,EAAE,KAAK,KAAK,EAA4C,MAAM,YAAY,CAAC;AA4QxF,MAAM,MAAM,KAAK,GAAG,UAAU,CAAC,OAAO,sBAAsB,CAAC,CAAC;AAC9D,wBAAgB,sBAAsB,CAAC,CAAC,SAAS,IAAI,CAAC,CAAC,CAAC,EACtD,QAAQ,EAAE,CAAC,GAAG,EAAE,KAAK,KAAK,IAAI,CAAC,CAAC,CAAC,GAChC;IACD,CAAC,GAAG,EAAE,KAAK,EAAE,GAAG,EAAE,KAAK,GAAG,UAAU,CAAC;IACrC,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,GAAG,EAAE,KAAK,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;CAC7B,CAOA;AAED,kCAAkC;AAClC,eAAO,MAAM,QAAQ,EAAE,KAA0D,CAAC"}
+277
View File
@@ -0,0 +1,277 @@
/**
* Poly1305 ([PDF](https://cr.yp.to/mac/poly1305-20050329.pdf),
* [wiki](https://en.wikipedia.org/wiki/Poly1305))
* is a fast and parallel secret-key message-authentication code suitable for
* a wide variety of applications. It was standardized in
* [RFC 8439](https://datatracker.ietf.org/doc/html/rfc8439) 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 [invisible salamanders attack](https://keymaterial.net/2020/09/07/invisible-salamanders-in-aes-gcm-siv/).
* 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 [original website](https://cr.yp.to/mac.html).
* @module
*/
import { Hash, abytes, aexists, aoutput, clean, toBytes } from "./utils.js";
// Based on Public Domain poly1305-donna https://github.com/floodyberry/poly1305-donna
const u8to16 = (a, i) => (a[i++] & 0xff) | ((a[i++] & 0xff) << 8);
class Poly1305 {
constructor(key) {
this.blockLen = 16;
this.outputLen = 16;
this.buffer = new Uint8Array(16);
this.r = new Uint16Array(10);
this.h = new Uint16Array(10);
this.pad = new Uint16Array(8);
this.pos = 0;
this.finished = false;
key = toBytes(key);
abytes(key, 32);
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);
// https://github.com/floodyberry/poly1305-donna/blob/e6ad6e091d30d7f4ec2d4f978be1fcfcbce72781/poly1305-donna-16.h#L47
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) {
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;
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);
data = toBytes(data);
abytes(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() {
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) {
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;
}
return out;
}
digest() {
const { buffer, outputLen } = this;
this.digestInto(buffer);
const res = buffer.slice(0, outputLen);
this.destroy();
return res;
}
}
export function wrapConstructorWithKey(hashCons) {
const hashC = (msg, key) => hashCons(key).update(toBytes(msg)).digest();
const tmp = hashCons(new Uint8Array(32));
hashC.outputLen = tmp.outputLen;
hashC.blockLen = tmp.blockLen;
hashC.create = (key) => hashCons(key);
return hashC;
}
/** Poly1305 MAC from RFC 8439. */
export const poly1305 = wrapConstructorWithKey((key) => new Poly1305(key));
//# sourceMappingURL=_poly1305.js.map
File diff suppressed because one or more lines are too long
+33
View File
@@ -0,0 +1,33 @@
/**
* 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
* [NIST SP800-38d](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf),
* SIV from
* [RFC 8452](https://datatracker.ietf.org/doc/html/rfc8452).
*
* GHASH modulo: x^128 + x^7 + x^2 + x + 1
* POLYVAL modulo: x^128 + x^127 + x^126 + x^121 + 1
*
* @module
*/
import { Hash, type Input } from './utils.ts';
/**
* `mulX_POLYVAL(ByteReverse(H))` from spec
* @param k mutated in place
*/
export declare function _toGHASHKey(k: Uint8Array): Uint8Array;
export type CHashPV = ReturnType<typeof wrapConstructorWithKey>;
declare function wrapConstructorWithKey<H extends Hash<H>>(hashCons: (key: Input, expectedLength?: number) => Hash<H>): {
(msg: Input, key: Input): Uint8Array;
outputLen: number;
blockLen: number;
create(key: Input, expectedLength?: number): Hash<H>;
};
/** GHash MAC for AES-GCM. */
export declare const ghash: CHashPV;
/** Polyval MAC for AES-SIV. */
export declare const polyval: CHashPV;
export {};
//# sourceMappingURL=_polyval.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"_polyval.d.ts","sourceRoot":"","sources":["../src/_polyval.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAEyB,IAAI,EAAE,KAAK,KAAK,EAC/C,MAAM,YAAY,CAAC;AA6BpB;;;GAGG;AACH,wBAAgB,WAAW,CAAC,CAAC,EAAE,UAAU,GAAG,UAAU,CAYrD;AAiLD,MAAM,MAAM,OAAO,GAAG,UAAU,CAAC,OAAO,sBAAsB,CAAC,CAAC;AAChE,iBAAS,sBAAsB,CAAC,CAAC,SAAS,IAAI,CAAC,CAAC,CAAC,EAC/C,QAAQ,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,cAAc,CAAC,EAAE,MAAM,KAAK,IAAI,CAAC,CAAC,CAAC,GACzD;IACD,CAAC,GAAG,EAAE,KAAK,EAAE,GAAG,EAAE,KAAK,GAAG,UAAU,CAAC;IACrC,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,GAAG,EAAE,KAAK,EAAE,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;CACtD,CAQA;AAED,6BAA6B;AAC7B,eAAO,MAAM,KAAK,EAAE,OAEnB,CAAC;AAEF,+BAA+B;AAC/B,eAAO,MAAM,OAAO,EAAE,OAErB,CAAC"}
+229
View File
@@ -0,0 +1,229 @@
/**
* 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
* [NIST SP800-38d](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf),
* SIV from
* [RFC 8452](https://datatracker.ietf.org/doc/html/rfc8452).
*
* GHASH modulo: x^128 + x^7 + x^2 + x + 1
* POLYVAL modulo: x^128 + x^127 + x^126 + x^121 + 1
*
* @module
*/
// prettier-ignore
import { abytes, aexists, aoutput, clean, copyBytes, createView, Hash, toBytes, u32, } from "./utils.js";
const BLOCK_SIZE = 16;
// TODO: rewrite
// temporary padding buffer
const ZEROS16 = /* @__PURE__ */ new Uint8Array(16);
const ZEROS32 = u32(ZEROS16);
const POLY = 0xe1; // v = 2*v % POLY
// v = 2*v % POLY
// NOTE: because x + x = 0 (add/sub is same), mul2(x) != x+x
// We can multiply any number using montgomery ladder and this function (works as double, add is 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),
s0: (s0 >>> 1) ^ ((POLY << 24) & -(hiBit & 1)), // reduce % poly
};
};
const swapLE = (n) => (((n >>> 0) & 0xff) << 24) |
(((n >>> 8) & 0xff) << 16) |
(((n >>> 16) & 0xff) << 8) |
((n >>> 24) & 0xff) |
0;
/**
* `mulX_POLYVAL(ByteReverse(H))` from spec
* @param k mutated in place
*/
export function _toGHASHKey(k) {
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;
}
const estimateWindow = (bytes) => {
if (bytes > 64 * 1024)
return 8;
if (bytes > 1024)
return 4;
return 2;
};
class GHASH {
// We select bits per window adaptively based on expectedLength
constructor(key, expectedLength) {
this.blockLen = BLOCK_SIZE;
this.outputLen = BLOCK_SIZE;
this.s0 = 0;
this.s1 = 0;
this.s2 = 0;
this.s3 = 0;
this.finished = false;
key = toBytes(key);
abytes(key, 16);
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;
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);
data = toBytes(data);
abytes(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(b32[i * 4 + 0], b32[i * 4 + 1], b32[i * 4 + 2], b32[i * 4 + 3]);
}
if (left) {
ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));
this._updateBlock(ZEROS32[0], ZEROS32[1], ZEROS32[2], ZEROS32[3]);
clean(ZEROS32); // clean tmp buffer
}
return this;
}
destroy() {
const { t } = this;
// clean precompute table
for (const elm of t) {
(elm.s0 = 0), (elm.s1 = 0), (elm.s2 = 0), (elm.s3 = 0);
}
}
digestInto(out) {
aexists(this);
aoutput(out, this);
this.finished = true;
const { s0, s1, s2, s3 } = this;
const o32 = u32(out);
o32[0] = s0;
o32[1] = s1;
o32[2] = s2;
o32[3] = s3;
return out;
}
digest() {
const res = new Uint8Array(BLOCK_SIZE);
this.digestInto(res);
this.destroy();
return res;
}
}
class Polyval extends GHASH {
constructor(key, expectedLength) {
key = toBytes(key);
abytes(key);
const ghKey = _toGHASHKey(copyBytes(key));
super(ghKey, expectedLength);
clean(ghKey);
}
update(data) {
data = toBytes(data);
aexists(this);
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++) {
this._updateBlock(swapLE(b32[i * 4 + 3]), swapLE(b32[i * 4 + 2]), swapLE(b32[i * 4 + 1]), swapLE(b32[i * 4 + 0]));
}
if (left) {
ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));
this._updateBlock(swapLE(ZEROS32[3]), swapLE(ZEROS32[2]), swapLE(ZEROS32[1]), swapLE(ZEROS32[0]));
clean(ZEROS32);
}
return this;
}
digestInto(out) {
aexists(this);
aoutput(out, this);
this.finished = true;
// tmp ugly hack
const { s0, s1, s2, s3 } = this;
const o32 = u32(out);
o32[0] = s0;
o32[1] = s1;
o32[2] = s2;
o32[3] = s3;
return out.reverse();
}
}
function wrapConstructorWithKey(hashCons) {
const hashC = (msg, key) => hashCons(key, msg.length).update(toBytes(msg)).digest();
const tmp = hashCons(new Uint8Array(16), 0);
hashC.outputLen = tmp.outputLen;
hashC.blockLen = tmp.blockLen;
hashC.create = (key, expectedLength) => hashCons(key, expectedLength);
return hashC;
}
/** GHash MAC for AES-GCM. */
export const ghash = wrapConstructorWithKey((key, expectedLength) => new GHASH(key, expectedLength));
/** Polyval MAC for AES-SIV. */
export const polyval = wrapConstructorWithKey((key, expectedLength) => new Polyval(key, expectedLength));
//# sourceMappingURL=_polyval.js.map
File diff suppressed because one or more lines are too long
+117
View File
@@ -0,0 +1,117 @@
import { type Cipher, type CipherWithOutput } from './utils.ts';
/** Key expansion used in CTR. */
declare function expandKeyLE(key: Uint8Array): Uint32Array;
declare function expandKeyDecLE(key: Uint8Array): Uint32Array;
declare function encrypt(xk: Uint32Array, s0: number, s1: number, s2: number, s3: number): {
s0: number;
s1: number;
s2: number;
s3: number;
};
declare function decrypt(xk: Uint32Array, s0: number, s1: number, s2: number, s3: number): {
s0: number;
s1: number;
s2: number;
s3: number;
};
declare function ctrCounter(xk: Uint32Array, nonce: Uint8Array, src: Uint8Array, dst?: Uint8Array): Uint8Array;
declare function ctr32(xk: Uint32Array, isLE: boolean, nonce: Uint8Array, src: Uint8Array, dst?: Uint8Array): Uint8Array;
/**
* CTR: counter mode. Creates stream cipher.
* Requires good IV. Parallelizable. OK, but no MAC.
*/
export declare const ctr: ((key: Uint8Array, nonce: Uint8Array) => CipherWithOutput) & {
blockSize: number;
nonceLength: number;
};
/** Options for ECB and CBC. */
export type BlockOpts = {
disablePadding?: boolean;
};
/**
* ECB: Electronic CodeBook. Simple deterministic replacement.
* Dangerous: always map x to y. See [AES Penguin](https://words.filippo.io/the-ecb-penguin/).
*/
export declare const ecb: ((key: Uint8Array, opts?: BlockOpts) => CipherWithOutput) & {
blockSize: number;
};
/**
* CBC: Cipher-Block-Chaining. Key is previous rounds block.
* Fragile: needs proper padding. Unauthenticated: needs MAC.
*/
export declare const cbc: ((key: Uint8Array, iv: Uint8Array, opts?: BlockOpts) => CipherWithOutput) & {
blockSize: number;
nonceLength: number;
};
/**
* CFB: Cipher Feedback Mode. The input for the block cipher is the previous cipher output.
* Unauthenticated: needs MAC.
*/
export declare const cfb: ((key: Uint8Array, iv: Uint8Array) => CipherWithOutput) & {
blockSize: number;
nonceLength: number;
};
/**
* GCM: Galois/Counter Mode.
* Modern, parallel version of CTR, with MAC.
* Be careful: MACs can be forged.
* Unsafe to use random nonces under the same key, due to collision chance.
* As for nonce size, prefer 12-byte, instead of 8-byte.
*/
export declare const gcm: ((key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array) => Cipher) & {
blockSize: number;
nonceLength: number;
tagLength: number;
varSizeNonce: true;
};
/**
* AES-GCM-SIV: classic AES-GCM with nonce-misuse resistance.
* Guarantees that, when a nonce is repeated, the only security loss is that identical
* plaintexts will produce identical ciphertexts.
* RFC 8452, https://datatracker.ietf.org/doc/html/rfc8452
*/
export declare const gcmsiv: ((key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array) => Cipher) & {
blockSize: number;
nonceLength: number;
tagLength: number;
varSizeNonce: true;
};
/**
* AES-GCM-SIV, not AES-SIV.
* This is legace name, use `gcmsiv` export instead.
* @deprecated
*/
export declare const siv: typeof gcmsiv;
declare function encryptBlock(xk: Uint32Array, block: Uint8Array): Uint8Array;
declare function decryptBlock(xk: Uint32Array, block: Uint8Array): Uint8Array;
/**
* AES-KW (key-wrap). Injects static IV into plaintext, adds counter, encrypts 6 times.
* Reduces block size from 16 to 8 bytes.
* For padded version, use aeskwp.
* [RFC 3394](https://datatracker.ietf.org/doc/rfc3394/),
* [NIST.SP.800-38F](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf).
*/
export declare const aeskw: ((kek: Uint8Array) => Cipher) & {
blockSize: number;
};
/**
* AES-KW, but with padding and allows random keys.
* Second u32 of IV is used as counter for length.
* [RFC 5649](https://www.rfc-editor.org/rfc/rfc5649)
*/
export declare const aeskwp: ((kek: Uint8Array) => Cipher) & {
blockSize: number;
};
/** Unsafe low-level internal methods. May change at any time. */
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;
};
export {};
//# sourceMappingURL=aes.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"aes.d.ts","sourceRoot":"","sources":["../src/aes.ts"],"names":[],"mappings":"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"}
+903
View File
@@ -0,0 +1,903 @@
/**
* [AES](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard)
* a.k.a. Advanced Encryption Standard
* is a variant of Rijndael block cipher, standardized by NIST in 2001.
* We provide the fastest available pure JS implementation.
*
* Data is split into 128-bit blocks. Encrypted in 10/12/14 rounds (128/192/256 bits). In every round:
* 1. **S-box**, table substitution
* 2. **Shift rows**, cyclic shift left of all rows of data array
* 3. **Mix columns**, multiplying every column by fixed polynomial
* 4. **Add round key**, round_key xor i-th column of array
*
* Check out [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)
* @module
*/
import { ghash, polyval } from "./_polyval.js";
// prettier-ignore
import { abytes, clean, complexOverlapBytes, concatBytes, copyBytes, createView, equalBytes, getOutput, isAligned32, overlapBytes, setBigUint64, u32, u64Lengths, u8, wrapCipher, } from "./utils.js";
const BLOCK_SIZE = 16;
const BLOCK_SIZE32 = 4;
const EMPTY_BLOCK = /* @__PURE__ */ new Uint8Array(BLOCK_SIZE);
const POLY = 0x11b; // 1 + x + x**3 + x**4 + x**8
// TODO: remove multiplication, binary ops only
function mul2(n) {
return (n << 1) ^ (POLY & -(n >> 7));
}
function mul(a, b) {
let res = 0;
for (; b > 0; b >>= 1) {
// Montgomery ladder
res ^= a & -(b & 1); // if (b&1) res ^=a (but const-time).
a = mul2(a); // a = 2*a
}
return res;
}
// AES S-box is generated using finite field inversion,
// an affine transform, and xor of a constant 0x63.
const sbox = /* @__PURE__ */ (() => {
const t = new Uint8Array(256);
for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x))
t[i] = x;
const box = new Uint8Array(256);
box[0] = 0x63; // first elm
for (let i = 0; i < 255; i++) {
let x = t[255 - i];
x |= x << 8;
box[t[i]] = (x ^ (x >> 4) ^ (x >> 5) ^ (x >> 6) ^ (x >> 7) ^ 0x63) & 0xff;
}
clean(t);
return box;
})();
// Inverted S-box
const invSbox = /* @__PURE__ */ sbox.map((_, j) => sbox.indexOf(j));
// Rotate u32 by 8
const rotr32_8 = (n) => (n << 24) | (n >>> 8);
const rotl32_8 = (n) => (n << 8) | (n >>> 24);
// The byte swap operation for uint32 (LE<->BE)
const byteSwap = (word) => ((word << 24) & 0xff000000) |
((word << 8) & 0xff0000) |
((word >>> 8) & 0xff00) |
((word >>> 24) & 0xff);
// T-table is optimization suggested in 5.2 of original proposal (missed from FIPS-197). Changes:
// - LE instead of BE
// - bigger tables: T0 and T1 are merged into T01 table and T2 & T3 into T23;
// so index is u16, instead of u8. This speeds up things, unexpectedly
function genTtable(sbox, fn) {
if (sbox.length !== 256)
throw new Error('Wrong sbox length');
const T0 = new Uint32Array(256).map((_, j) => fn(sbox[j]));
const T1 = T0.map(rotl32_8);
const T2 = T1.map(rotl32_8);
const T3 = T2.map(rotl32_8);
const T01 = new Uint32Array(256 * 256);
const T23 = new Uint32Array(256 * 256);
const sbox2 = new Uint16Array(256 * 256);
for (let i = 0; i < 256; i++) {
for (let j = 0; j < 256; j++) {
const idx = i * 256 + j;
T01[idx] = T0[i] ^ T1[j];
T23[idx] = T2[i] ^ T3[j];
sbox2[idx] = (sbox[i] << 8) | sbox[j];
}
}
return { sbox, sbox2, T0, T1, T2, T3, T01, T23 };
}
const tableEncoding = /* @__PURE__ */ genTtable(sbox, (s) => (mul(s, 3) << 24) | (s << 16) | (s << 8) | mul(s, 2));
const tableDecoding = /* @__PURE__ */ genTtable(invSbox, (s) => (mul(s, 11) << 24) | (mul(s, 13) << 16) | (mul(s, 9) << 8) | mul(s, 14));
const xPowers = /* @__PURE__ */ (() => {
const p = new Uint8Array(16);
for (let i = 0, x = 1; i < 16; i++, x = mul2(x))
p[i] = x;
return p;
})();
/** Key expansion used in CTR. */
function expandKeyLE(key) {
abytes(key);
const len = key.length;
if (![16, 24, 32].includes(len))
throw new Error('aes: invalid key size, should be 16, 24 or 32, got ' + len);
const { sbox2 } = tableEncoding;
const toClean = [];
if (!isAligned32(key))
toClean.push((key = copyBytes(key)));
const k32 = u32(key);
const Nk = k32.length;
const subByte = (n) => applySbox(sbox2, n, n, n, n);
const xk = new Uint32Array(len + 28); // expanded key
xk.set(k32);
// 4.3.1 Key expansion
for (let i = Nk; i < xk.length; i++) {
let t = xk[i - 1];
if (i % Nk === 0)
t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1];
else if (Nk > 6 && i % Nk === 4)
t = subByte(t);
xk[i] = xk[i - Nk] ^ t;
}
clean(...toClean);
return xk;
}
function expandKeyDecLE(key) {
const encKey = expandKeyLE(key);
const xk = encKey.slice();
const Nk = encKey.length;
const { sbox2 } = tableEncoding;
const { T0, T1, T2, T3 } = tableDecoding;
// Inverse key by chunks of 4 (rounds)
for (let i = 0; i < Nk; i += 4) {
for (let j = 0; j < 4; j++)
xk[i + j] = encKey[Nk - i - 4 + j];
}
clean(encKey);
// apply InvMixColumn except first & last round
for (let i = 4; i < Nk - 4; i++) {
const x = xk[i];
const w = applySbox(sbox2, x, x, x, x);
xk[i] = T0[w & 0xff] ^ T1[(w >>> 8) & 0xff] ^ T2[(w >>> 16) & 0xff] ^ T3[w >>> 24];
}
return xk;
}
// Apply tables
function apply0123(T01, T23, s0, s1, s2, s3) {
return (T01[((s0 << 8) & 0xff00) | ((s1 >>> 8) & 0xff)] ^
T23[((s2 >>> 8) & 0xff00) | ((s3 >>> 24) & 0xff)]);
}
function applySbox(sbox2, s0, s1, s2, s3) {
return (sbox2[(s0 & 0xff) | (s1 & 0xff00)] |
(sbox2[((s2 >>> 16) & 0xff) | ((s3 >>> 16) & 0xff00)] << 16));
}
function encrypt(xk, s0, s1, s2, s3) {
const { sbox2, T01, T23 } = tableEncoding;
let k = 0;
(s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]);
const rounds = xk.length / 4 - 2;
for (let i = 0; i < rounds; i++) {
const t0 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3);
const t1 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0);
const t2 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1);
const t3 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2);
(s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3);
}
// last round (without mixcolumns, so using SBOX2 table)
const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3);
const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0);
const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1);
const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2);
return { s0: t0, s1: t1, s2: t2, s3: t3 };
}
// Can't be merged with encrypt: arg positions for apply0123 / applySbox are different
function decrypt(xk, s0, s1, s2, s3) {
const { sbox2, T01, T23 } = tableDecoding;
let k = 0;
(s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]);
const rounds = xk.length / 4 - 2;
for (let i = 0; i < rounds; i++) {
const t0 = xk[k++] ^ apply0123(T01, T23, s0, s3, s2, s1);
const t1 = xk[k++] ^ apply0123(T01, T23, s1, s0, s3, s2);
const t2 = xk[k++] ^ apply0123(T01, T23, s2, s1, s0, s3);
const t3 = xk[k++] ^ apply0123(T01, T23, s3, s2, s1, s0);
(s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3);
}
// Last round
const t0 = xk[k++] ^ applySbox(sbox2, s0, s3, s2, s1);
const t1 = xk[k++] ^ applySbox(sbox2, s1, s0, s3, s2);
const t2 = xk[k++] ^ applySbox(sbox2, s2, s1, s0, s3);
const t3 = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0);
return { s0: t0, s1: t1, s2: t2, s3: t3 };
}
// TODO: investigate merging with ctr32
function ctrCounter(xk, nonce, src, dst) {
abytes(nonce, BLOCK_SIZE);
abytes(src);
const srcLen = src.length;
dst = getOutput(srcLen, dst);
complexOverlapBytes(src, dst);
const ctr = nonce;
const c32 = u32(ctr);
// Fill block (empty, ctr=0)
let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]);
const src32 = u32(src);
const dst32 = u32(dst);
// process blocks
for (let i = 0; i + 4 <= src32.length; i += 4) {
dst32[i + 0] = src32[i + 0] ^ s0;
dst32[i + 1] = src32[i + 1] ^ s1;
dst32[i + 2] = src32[i + 2] ^ s2;
dst32[i + 3] = src32[i + 3] ^ s3;
// Full 128 bit counter with wrap around
let carry = 1;
for (let i = ctr.length - 1; i >= 0; i--) {
carry = (carry + (ctr[i] & 0xff)) | 0;
ctr[i] = carry & 0xff;
carry >>>= 8;
}
({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]));
}
// leftovers (less than block)
// It's possible to handle > u32 fast, but is it worth it?
const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);
if (start < srcLen) {
const b32 = new Uint32Array([s0, s1, s2, s3]);
const buf = u8(b32);
for (let i = start, pos = 0; i < srcLen; i++, pos++)
dst[i] = src[i] ^ buf[pos];
clean(b32);
}
return dst;
}
// AES CTR with overflowing 32 bit counter
// It's possible to do 32le significantly simpler (and probably faster) by using u32.
// But, we need both, and perf bottleneck is in ghash anyway.
function ctr32(xk, isLE, nonce, src, dst) {
abytes(nonce, BLOCK_SIZE);
abytes(src);
dst = getOutput(src.length, dst);
const ctr = nonce; // write new value to nonce, so it can be re-used
const c32 = u32(ctr);
const view = createView(ctr);
const src32 = u32(src);
const dst32 = u32(dst);
const ctrPos = isLE ? 0 : 12;
const srcLen = src.length;
// Fill block (empty, ctr=0)
let ctrNum = view.getUint32(ctrPos, isLE); // read current counter value
let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]);
// process blocks
for (let i = 0; i + 4 <= src32.length; i += 4) {
dst32[i + 0] = src32[i + 0] ^ s0;
dst32[i + 1] = src32[i + 1] ^ s1;
dst32[i + 2] = src32[i + 2] ^ s2;
dst32[i + 3] = src32[i + 3] ^ s3;
ctrNum = (ctrNum + 1) >>> 0; // u32 wrap
view.setUint32(ctrPos, ctrNum, isLE);
({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]));
}
// leftovers (less than a block)
const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);
if (start < srcLen) {
const b32 = new Uint32Array([s0, s1, s2, s3]);
const buf = u8(b32);
for (let i = start, pos = 0; i < srcLen; i++, pos++)
dst[i] = src[i] ^ buf[pos];
clean(b32);
}
return dst;
}
/**
* CTR: counter mode. Creates stream cipher.
* Requires good IV. Parallelizable. OK, but no MAC.
*/
export const ctr = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 16 }, function aesctr(key, nonce) {
function processCtr(buf, dst) {
abytes(buf);
if (dst !== undefined) {
abytes(dst);
if (!isAligned32(dst))
throw new Error('unaligned destination');
}
const xk = expandKeyLE(key);
const n = copyBytes(nonce); // align + avoid changing
const toClean = [xk, n];
if (!isAligned32(buf))
toClean.push((buf = copyBytes(buf)));
const out = ctrCounter(xk, n, buf, dst);
clean(...toClean);
return out;
}
return {
encrypt: (plaintext, dst) => processCtr(plaintext, dst),
decrypt: (ciphertext, dst) => processCtr(ciphertext, dst),
};
});
function validateBlockDecrypt(data) {
abytes(data);
if (data.length % BLOCK_SIZE !== 0) {
throw new Error('aes-(cbc/ecb).decrypt ciphertext should consist of blocks with size ' + BLOCK_SIZE);
}
}
function validateBlockEncrypt(plaintext, pcks5, dst) {
abytes(plaintext);
let outLen = plaintext.length;
const remaining = outLen % BLOCK_SIZE;
if (!pcks5 && remaining !== 0)
throw new Error('aec/(cbc-ecb): unpadded plaintext with disabled padding');
if (!isAligned32(plaintext))
plaintext = copyBytes(plaintext);
const b = u32(plaintext);
if (pcks5) {
let left = BLOCK_SIZE - remaining;
if (!left)
left = BLOCK_SIZE; // if no bytes left, create empty padding block
outLen = outLen + left;
}
dst = getOutput(outLen, dst);
complexOverlapBytes(plaintext, dst);
const o = u32(dst);
return { b, o, out: dst };
}
function validatePCKS(data, pcks5) {
if (!pcks5)
return data;
const len = data.length;
if (!len)
throw new Error('aes/pcks5: empty ciphertext not allowed');
const lastByte = data[len - 1];
if (lastByte <= 0 || lastByte > 16)
throw new Error('aes/pcks5: wrong padding');
const out = data.subarray(0, -lastByte);
for (let i = 0; i < lastByte; i++)
if (data[len - i - 1] !== lastByte)
throw new Error('aes/pcks5: wrong padding');
return out;
}
function padPCKS(left) {
const tmp = new Uint8Array(16);
const tmp32 = u32(tmp);
tmp.set(left);
const paddingByte = BLOCK_SIZE - left.length;
for (let i = BLOCK_SIZE - paddingByte; i < BLOCK_SIZE; i++)
tmp[i] = paddingByte;
return tmp32;
}
/**
* ECB: Electronic CodeBook. Simple deterministic replacement.
* Dangerous: always map x to y. See [AES Penguin](https://words.filippo.io/the-ecb-penguin/).
*/
export const ecb = /* @__PURE__ */ wrapCipher({ blockSize: 16 }, function aesecb(key, opts = {}) {
const pcks5 = !opts.disablePadding;
return {
encrypt(plaintext, dst) {
const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst);
const xk = expandKeyLE(key);
let i = 0;
for (; i + 4 <= b.length;) {
const { s0, s1, s2, s3 } = encrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);
(o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);
}
if (pcks5) {
const tmp32 = padPCKS(plaintext.subarray(i * 4));
const { s0, s1, s2, s3 } = encrypt(xk, tmp32[0], tmp32[1], tmp32[2], tmp32[3]);
(o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);
}
clean(xk);
return _out;
},
decrypt(ciphertext, dst) {
validateBlockDecrypt(ciphertext);
const xk = expandKeyDecLE(key);
dst = getOutput(ciphertext.length, dst);
const toClean = [xk];
if (!isAligned32(ciphertext))
toClean.push((ciphertext = copyBytes(ciphertext)));
complexOverlapBytes(ciphertext, dst);
const b = u32(ciphertext);
const o = u32(dst);
for (let i = 0; i + 4 <= b.length;) {
const { s0, s1, s2, s3 } = decrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);
(o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);
}
clean(...toClean);
return validatePCKS(dst, pcks5);
},
};
});
/**
* CBC: Cipher-Block-Chaining. Key is previous rounds block.
* Fragile: needs proper padding. Unauthenticated: needs MAC.
*/
export const cbc = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 16 }, function aescbc(key, iv, opts = {}) {
const pcks5 = !opts.disablePadding;
return {
encrypt(plaintext, dst) {
const xk = expandKeyLE(key);
const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst);
let _iv = iv;
const toClean = [xk];
if (!isAligned32(_iv))
toClean.push((_iv = copyBytes(_iv)));
const n32 = u32(_iv);
// prettier-ignore
let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];
let i = 0;
for (; i + 4 <= b.length;) {
(s0 ^= b[i + 0]), (s1 ^= b[i + 1]), (s2 ^= b[i + 2]), (s3 ^= b[i + 3]);
({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));
(o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);
}
if (pcks5) {
const tmp32 = padPCKS(plaintext.subarray(i * 4));
(s0 ^= tmp32[0]), (s1 ^= tmp32[1]), (s2 ^= tmp32[2]), (s3 ^= tmp32[3]);
({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));
(o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);
}
clean(...toClean);
return _out;
},
decrypt(ciphertext, dst) {
validateBlockDecrypt(ciphertext);
const xk = expandKeyDecLE(key);
let _iv = iv;
const toClean = [xk];
if (!isAligned32(_iv))
toClean.push((_iv = copyBytes(_iv)));
const n32 = u32(_iv);
dst = getOutput(ciphertext.length, dst);
if (!isAligned32(ciphertext))
toClean.push((ciphertext = copyBytes(ciphertext)));
complexOverlapBytes(ciphertext, dst);
const b = u32(ciphertext);
const o = u32(dst);
// prettier-ignore
let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];
for (let i = 0; i + 4 <= b.length;) {
// prettier-ignore
const ps0 = s0, ps1 = s1, ps2 = s2, ps3 = s3;
(s0 = b[i + 0]), (s1 = b[i + 1]), (s2 = b[i + 2]), (s3 = b[i + 3]);
const { s0: o0, s1: o1, s2: o2, s3: o3 } = decrypt(xk, s0, s1, s2, s3);
(o[i++] = o0 ^ ps0), (o[i++] = o1 ^ ps1), (o[i++] = o2 ^ ps2), (o[i++] = o3 ^ ps3);
}
clean(...toClean);
return validatePCKS(dst, pcks5);
},
};
});
/**
* CFB: Cipher Feedback Mode. The input for the block cipher is the previous cipher output.
* Unauthenticated: needs MAC.
*/
export const cfb = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 16 }, function aescfb(key, iv) {
function processCfb(src, isEncrypt, dst) {
abytes(src);
const srcLen = src.length;
dst = getOutput(srcLen, dst);
if (overlapBytes(src, dst))
throw new Error('overlapping src and dst not supported.');
const xk = expandKeyLE(key);
let _iv = iv;
const toClean = [xk];
if (!isAligned32(_iv))
toClean.push((_iv = copyBytes(_iv)));
if (!isAligned32(src))
toClean.push((src = copyBytes(src)));
const src32 = u32(src);
const dst32 = u32(dst);
const next32 = isEncrypt ? dst32 : src32;
const n32 = u32(_iv);
// prettier-ignore
let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];
for (let i = 0; i + 4 <= src32.length;) {
const { s0: e0, s1: e1, s2: e2, s3: e3 } = encrypt(xk, s0, s1, s2, s3);
dst32[i + 0] = src32[i + 0] ^ e0;
dst32[i + 1] = src32[i + 1] ^ e1;
dst32[i + 2] = src32[i + 2] ^ e2;
dst32[i + 3] = src32[i + 3] ^ e3;
(s0 = next32[i++]), (s1 = next32[i++]), (s2 = next32[i++]), (s3 = next32[i++]);
}
// leftovers (less than block)
const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);
if (start < srcLen) {
({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));
const buf = u8(new Uint32Array([s0, s1, s2, s3]));
for (let i = start, pos = 0; i < srcLen; i++, pos++)
dst[i] = src[i] ^ buf[pos];
clean(buf);
}
clean(...toClean);
return dst;
}
return {
encrypt: (plaintext, dst) => processCfb(plaintext, true, dst),
decrypt: (ciphertext, dst) => processCfb(ciphertext, false, dst),
};
});
// TODO: merge with chacha, however gcm has bitLen while chacha has byteLen
function computeTag(fn, isLE, key, data, AAD) {
const aadLength = AAD ? AAD.length : 0;
const h = fn.create(key, data.length + aadLength);
if (AAD)
h.update(AAD);
const num = u64Lengths(8 * data.length, 8 * aadLength, isLE);
h.update(data);
h.update(num);
const res = h.digest();
clean(num);
return res;
}
/**
* GCM: Galois/Counter Mode.
* Modern, parallel version of CTR, with MAC.
* Be careful: MACs can be forged.
* Unsafe to use random nonces under the same key, due to collision chance.
* As for nonce size, prefer 12-byte, instead of 8-byte.
*/
export const gcm = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16, varSizeNonce: true }, function aesgcm(key, nonce, AAD) {
// NIST 800-38d doesn't enforce minimum nonce length.
// We enforce 8 bytes for compat with openssl.
// 12 bytes are recommended. More than 12 bytes would be converted into 12.
if (nonce.length < 8)
throw new Error('aes/gcm: invalid nonce length');
const tagLength = 16;
function _computeTag(authKey, tagMask, data) {
const tag = computeTag(ghash, false, authKey, data, AAD);
for (let i = 0; i < tagMask.length; i++)
tag[i] ^= tagMask[i];
return tag;
}
function deriveKeys() {
const xk = expandKeyLE(key);
const authKey = EMPTY_BLOCK.slice();
const counter = EMPTY_BLOCK.slice();
ctr32(xk, false, counter, counter, authKey);
// NIST 800-38d, page 15: different behavior for 96-bit and non-96-bit nonces
if (nonce.length === 12) {
counter.set(nonce);
}
else {
const nonceLen = EMPTY_BLOCK.slice();
const view = createView(nonceLen);
setBigUint64(view, 8, BigInt(nonce.length * 8), false);
// ghash(nonce || u64be(0) || u64be(nonceLen*8))
const g = ghash.create(authKey).update(nonce).update(nonceLen);
g.digestInto(counter); // digestInto doesn't trigger '.destroy'
g.destroy();
}
const tagMask = ctr32(xk, false, counter, EMPTY_BLOCK);
return { xk, authKey, counter, tagMask };
}
return {
encrypt(plaintext) {
const { xk, authKey, counter, tagMask } = deriveKeys();
const out = new Uint8Array(plaintext.length + tagLength);
const toClean = [xk, authKey, counter, tagMask];
if (!isAligned32(plaintext))
toClean.push((plaintext = copyBytes(plaintext)));
ctr32(xk, false, counter, plaintext, out.subarray(0, plaintext.length));
const tag = _computeTag(authKey, tagMask, out.subarray(0, out.length - tagLength));
toClean.push(tag);
out.set(tag, plaintext.length);
clean(...toClean);
return out;
},
decrypt(ciphertext) {
const { xk, authKey, counter, tagMask } = deriveKeys();
const toClean = [xk, authKey, tagMask, counter];
if (!isAligned32(ciphertext))
toClean.push((ciphertext = copyBytes(ciphertext)));
const data = ciphertext.subarray(0, -tagLength);
const passedTag = ciphertext.subarray(-tagLength);
const tag = _computeTag(authKey, tagMask, data);
toClean.push(tag);
if (!equalBytes(tag, passedTag))
throw new Error('aes/gcm: invalid ghash tag');
const out = ctr32(xk, false, counter, data);
clean(...toClean);
return out;
},
};
});
const limit = (name, min, max) => (value) => {
if (!Number.isSafeInteger(value) || min > value || value > max) {
const minmax = '[' + min + '..' + max + ']';
throw new Error('' + name + ': expected value in range ' + minmax + ', got ' + value);
}
};
/**
* AES-GCM-SIV: classic AES-GCM with nonce-misuse resistance.
* Guarantees that, when a nonce is repeated, the only security loss is that identical
* plaintexts will produce identical ciphertexts.
* RFC 8452, https://datatracker.ietf.org/doc/html/rfc8452
*/
export const gcmsiv = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16, varSizeNonce: true }, function aessiv(key, nonce, AAD) {
const tagLength = 16;
// From RFC 8452: Section 6
const AAD_LIMIT = limit('AAD', 0, 2 ** 36);
const PLAIN_LIMIT = limit('plaintext', 0, 2 ** 36);
const NONCE_LIMIT = limit('nonce', 12, 12);
const CIPHER_LIMIT = limit('ciphertext', 16, 2 ** 36 + 16);
abytes(key, 16, 24, 32);
NONCE_LIMIT(nonce.length);
if (AAD !== undefined)
AAD_LIMIT(AAD.length);
function deriveKeys() {
const xk = expandKeyLE(key);
const encKey = new Uint8Array(key.length);
const authKey = new Uint8Array(16);
const toClean = [xk, encKey];
let _nonce = nonce;
if (!isAligned32(_nonce))
toClean.push((_nonce = copyBytes(_nonce)));
const n32 = u32(_nonce);
// prettier-ignore
let s0 = 0, s1 = n32[0], s2 = n32[1], s3 = n32[2];
let counter = 0;
for (const derivedKey of [authKey, encKey].map(u32)) {
const d32 = u32(derivedKey);
for (let i = 0; i < d32.length; i += 2) {
// aes(u32le(0) || nonce)[:8] || aes(u32le(1) || nonce)[:8] ...
const { s0: o0, s1: o1 } = encrypt(xk, s0, s1, s2, s3);
d32[i + 0] = o0;
d32[i + 1] = o1;
s0 = ++counter; // increment counter inside state
}
}
const res = { authKey, encKey: expandKeyLE(encKey) };
// Cleanup
clean(...toClean);
return res;
}
function _computeTag(encKey, authKey, data) {
const tag = computeTag(polyval, true, authKey, data, AAD);
// Compute the expected tag by XORing S_s and the nonce, clearing the
// most significant bit of the last byte and encrypting with the
// message-encryption key.
for (let i = 0; i < 12; i++)
tag[i] ^= nonce[i];
tag[15] &= 0x7f; // Clear the highest bit
// encrypt tag as block
const t32 = u32(tag);
// prettier-ignore
let s0 = t32[0], s1 = t32[1], s2 = t32[2], s3 = t32[3];
({ s0, s1, s2, s3 } = encrypt(encKey, s0, s1, s2, s3));
(t32[0] = s0), (t32[1] = s1), (t32[2] = s2), (t32[3] = s3);
return tag;
}
// actual decrypt/encrypt of message.
function processSiv(encKey, tag, input) {
let block = copyBytes(tag);
block[15] |= 0x80; // Force highest bit
const res = ctr32(encKey, true, block, input);
// Cleanup
clean(block);
return res;
}
return {
encrypt(plaintext) {
PLAIN_LIMIT(plaintext.length);
const { encKey, authKey } = deriveKeys();
const tag = _computeTag(encKey, authKey, plaintext);
const toClean = [encKey, authKey, tag];
if (!isAligned32(plaintext))
toClean.push((plaintext = copyBytes(plaintext)));
const out = new Uint8Array(plaintext.length + tagLength);
out.set(tag, plaintext.length);
out.set(processSiv(encKey, tag, plaintext));
// Cleanup
clean(...toClean);
return out;
},
decrypt(ciphertext) {
CIPHER_LIMIT(ciphertext.length);
const tag = ciphertext.subarray(-tagLength);
const { encKey, authKey } = deriveKeys();
const toClean = [encKey, authKey];
if (!isAligned32(ciphertext))
toClean.push((ciphertext = copyBytes(ciphertext)));
const plaintext = processSiv(encKey, tag, ciphertext.subarray(0, -tagLength));
const expectedTag = _computeTag(encKey, authKey, plaintext);
toClean.push(expectedTag);
if (!equalBytes(tag, expectedTag)) {
clean(...toClean);
throw new Error('invalid polyval tag');
}
// Cleanup
clean(...toClean);
return plaintext;
},
};
});
/**
* AES-GCM-SIV, not AES-SIV.
* This is legace name, use `gcmsiv` export instead.
* @deprecated
*/
export const siv = gcmsiv;
function isBytes32(a) {
return (a instanceof Uint32Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint32Array'));
}
function encryptBlock(xk, block) {
abytes(block, 16);
if (!isBytes32(xk))
throw new Error('_encryptBlock accepts result of expandKeyLE');
const b32 = u32(block);
let { s0, s1, s2, s3 } = encrypt(xk, b32[0], b32[1], b32[2], b32[3]);
(b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3);
return block;
}
function decryptBlock(xk, block) {
abytes(block, 16);
if (!isBytes32(xk))
throw new Error('_decryptBlock accepts result of expandKeyLE');
const b32 = u32(block);
let { s0, s1, s2, s3 } = decrypt(xk, b32[0], b32[1], b32[2], b32[3]);
(b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3);
return block;
}
/**
* AES-W (base for AESKW/AESKWP).
* Specs: [SP800-38F](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf),
* [RFC 3394](https://datatracker.ietf.org/doc/rfc3394/),
* [RFC 5649](https://datatracker.ietf.org/doc/rfc5649/).
*/
const AESW = {
/*
High-level pseudocode:
```
A: u64 = IV
out = []
for (let i=0, ctr = 0; i<6; i++) {
for (const chunk of chunks(plaintext, 8)) {
A ^= swapEndianess(ctr++)
[A, res] = chunks(encrypt(A || chunk), 8);
out ||= res
}
}
out = A || out
```
Decrypt is the same, but reversed.
*/
encrypt(kek, out) {
// Size is limited to 4GB, otherwise ctr will overflow and we'll need to switch to bigints.
// If you need it larger, open an issue.
if (out.length >= 2 ** 32)
throw new Error('plaintext should be less than 4gb');
const xk = expandKeyLE(kek);
if (out.length === 16)
encryptBlock(xk, out);
else {
const o32 = u32(out);
// prettier-ignore
let a0 = o32[0], a1 = o32[1]; // A
for (let j = 0, ctr = 1; j < 6; j++) {
for (let pos = 2; pos < o32.length; pos += 2, ctr++) {
const { s0, s1, s2, s3 } = encrypt(xk, a0, a1, o32[pos], o32[pos + 1]);
// A = MSB(64, B) ^ t where t = (n*j)+i
(a0 = s0), (a1 = s1 ^ byteSwap(ctr)), (o32[pos] = s2), (o32[pos + 1] = s3);
}
}
(o32[0] = a0), (o32[1] = a1); // out = A || out
}
xk.fill(0);
},
decrypt(kek, out) {
if (out.length - 8 >= 2 ** 32)
throw new Error('ciphertext should be less than 4gb');
const xk = expandKeyDecLE(kek);
const chunks = out.length / 8 - 1; // first chunk is IV
if (chunks === 1)
decryptBlock(xk, out);
else {
const o32 = u32(out);
// prettier-ignore
let a0 = o32[0], a1 = o32[1]; // A
for (let j = 0, ctr = chunks * 6; j < 6; j++) {
for (let pos = chunks * 2; pos >= 1; pos -= 2, ctr--) {
a1 ^= byteSwap(ctr);
const { s0, s1, s2, s3 } = decrypt(xk, a0, a1, o32[pos], o32[pos + 1]);
(a0 = s0), (a1 = s1), (o32[pos] = s2), (o32[pos + 1] = s3);
}
}
(o32[0] = a0), (o32[1] = a1);
}
xk.fill(0);
},
};
const AESKW_IV = /* @__PURE__ */ new Uint8Array(8).fill(0xa6); // A6A6A6A6A6A6A6A6
/**
* AES-KW (key-wrap). Injects static IV into plaintext, adds counter, encrypts 6 times.
* Reduces block size from 16 to 8 bytes.
* For padded version, use aeskwp.
* [RFC 3394](https://datatracker.ietf.org/doc/rfc3394/),
* [NIST.SP.800-38F](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf).
*/
export const aeskw = /* @__PURE__ */ wrapCipher({ blockSize: 8 }, (kek) => ({
encrypt(plaintext) {
if (!plaintext.length || plaintext.length % 8 !== 0)
throw new Error('invalid plaintext length');
if (plaintext.length === 8)
throw new Error('8-byte keys not allowed in AESKW, use AESKWP instead');
const out = concatBytes(AESKW_IV, plaintext);
AESW.encrypt(kek, out);
return out;
},
decrypt(ciphertext) {
// ciphertext must be at least 24 bytes and a multiple of 8 bytes
// 24 because should have at least two block (1 iv + 2).
// Replace with 16 to enable '8-byte keys'
if (ciphertext.length % 8 !== 0 || ciphertext.length < 3 * 8)
throw new Error('invalid ciphertext length');
const out = copyBytes(ciphertext);
AESW.decrypt(kek, out);
if (!equalBytes(out.subarray(0, 8), AESKW_IV))
throw new Error('integrity check failed');
out.subarray(0, 8).fill(0); // ciphertext.subarray(0, 8) === IV, but we clean it anyway
return out.subarray(8);
},
}));
/*
We don't support 8-byte keys. The rabbit hole:
- Wycheproof says: "NIST SP 800-38F does not define the wrapping of 8 byte keys.
RFC 3394 Section 2 on the other hand specifies that 8 byte keys are wrapped
by directly encrypting one block with AES."
- https://github.com/C2SP/wycheproof/blob/master/doc/key_wrap.md
- "RFC 3394 specifies in Section 2, that the input for the key wrap
algorithm must be at least two blocks and otherwise the constant
field and key are simply encrypted with ECB as a single block"
- What RFC 3394 actually says (in Section 2):
- "Before being wrapped, the key data is parsed into n blocks of 64 bits.
The only restriction the key wrap algorithm places on n is that n be
at least two"
- "For key data with length less than or equal to 64 bits, the constant
field used in this specification and the key data form a single
128-bit codebook input making this key wrap unnecessary."
- Which means "assert(n >= 2)" and "use something else for 8 byte keys"
- NIST SP800-38F actually prohibits 8-byte in "5.3.1 Mandatory Limits".
It states that plaintext for KW should be "2 to 2^54 -1 semiblocks".
- So, where does "directly encrypt single block with AES" come from?
- Not RFC 3394. Pseudocode of key wrap in 2.2 explicitly uses
loop of 6 for any code path
- There is a weird W3C spec:
https://www.w3.org/TR/2002/REC-xmlenc-core-20021210/Overview.html#kw-aes128
- This spec is outdated, as admitted by Wycheproof authors
- There is RFC 5649 for padded key wrap, which is padding construction on
top of AESKW. In '4.1.2' it says: "If the padded plaintext contains exactly
eight octets, then prepend the AIV as defined in Section 3 above to P[1] and
encrypt the resulting 128-bit block using AES in ECB mode [Modes] with key
K (the KEK). In this case, the output is two 64-bit blocks C[0] and C[1]:"
- Browser subtle crypto is actually crashes on wrapping keys less than 16 bytes:
`Error: error:1C8000E6:Provider routines::invalid input length] { opensslErrorStack: [ 'error:030000BD:digital envelope routines::update error' ]`
In the end, seems like a bug in Wycheproof.
The 8-byte check can be easily disabled inside of AES_W.
*/
const AESKWP_IV = 0xa65959a6; // single u32le value
/**
* AES-KW, but with padding and allows random keys.
* Second u32 of IV is used as counter for length.
* [RFC 5649](https://www.rfc-editor.org/rfc/rfc5649)
*/
export const aeskwp = /* @__PURE__ */ wrapCipher({ blockSize: 8 }, (kek) => ({
encrypt(plaintext) {
if (!plaintext.length)
throw new Error('invalid plaintext length');
const padded = Math.ceil(plaintext.length / 8) * 8;
const out = new Uint8Array(8 + padded);
out.set(plaintext, 8);
const out32 = u32(out);
out32[0] = AESKWP_IV;
out32[1] = byteSwap(plaintext.length);
AESW.encrypt(kek, out);
return out;
},
decrypt(ciphertext) {
// 16 because should have at least one block
if (ciphertext.length < 16)
throw new Error('invalid ciphertext length');
const out = copyBytes(ciphertext);
const o32 = u32(out);
AESW.decrypt(kek, out);
const len = byteSwap(o32[1]) >>> 0;
const padded = Math.ceil(len / 8) * 8;
if (o32[0] !== AESKWP_IV || out.length - 8 !== padded)
throw new Error('integrity check failed');
for (let i = len; i < padded; i++)
if (out[8 + i] !== 0)
throw new Error('integrity check failed');
out.subarray(0, 8).fill(0); // ciphertext.subarray(0, 8) === IV, but we clean it anyway
return out.subarray(8, 8 + len);
},
}));
/** Unsafe low-level internal methods. May change at any time. */
export const unsafe = {
expandKeyLE,
expandKeyDecLE,
encrypt,
decrypt,
encryptBlock,
decryptBlock,
ctrCounter,
ctr32,
};
//# sourceMappingURL=aes.js.map
File diff suppressed because one or more lines are too long
+56
View File
@@ -0,0 +1,56 @@
import { type ARXCipher, type CipherWithOutput, type XorStream } from './utils.ts';
/**
* hchacha helper method, used primarily in xchacha, to hash
* key and nonce into key' and nonce'.
* Same as chachaCore, but there doesn't seem to be a way to move the block
* out without 25% performance hit.
*/
export declare function hchacha(s: Uint32Array, k: Uint32Array, i: Uint32Array, o32: Uint32Array): void;
/**
* Original, non-RFC chacha20 from DJB. 8-byte nonce, 8-byte counter.
*/
export declare const chacha20orig: XorStream;
/**
* ChaCha stream cipher. Conforms to RFC 8439 (IETF, TLS). 12-byte nonce, 4-byte counter.
* With 12-byte nonce, it's not safe to use fill it with random (CSPRNG), due to collision chance.
*/
export declare const chacha20: XorStream;
/**
* XChaCha eXtended-nonce ChaCha. 24-byte nonce.
* With 24-byte nonce, it's safe to use fill it with random (CSPRNG).
* https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha
*/
export declare const xchacha20: XorStream;
/**
* Reduced 8-round chacha, described in original paper.
*/
export declare const chacha8: XorStream;
/**
* Reduced 12-round chacha, described in original paper.
*/
export declare const chacha12: XorStream;
/**
* AEAD algorithm from RFC 8439.
* Salsa20 and chacha (RFC 8439) use poly1305 differently.
* We could have composed them similar to:
* https://github.com/paulmillr/scure-base/blob/b266c73dde977b1dd7ef40ef7a23cc15aab526b3/index.ts#L250
* 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: XorStream) => (key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array) => CipherWithOutput;
/**
* ChaCha20-Poly1305 from RFC 8439.
*
* Unsafe to use random nonces under the same key, due to collision chance.
* Prefer XChaCha instead.
*/
export declare const chacha20poly1305: ARXCipher;
/**
* XChaCha20-Poly1305 extended-nonce chacha.
*
* Can be safely used with random nonces (CSPRNG).
* See [IRTF draft](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha).
*/
export declare const xchacha20poly1305: ARXCipher;
//# sourceMappingURL=chacha.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"chacha.d.ts","sourceRoot":"","sources":["../src/chacha.ts"],"names":[],"mappings":"AAgBA,OAAO,EACL,KAAK,SAAS,EACd,KAAK,gBAAgB,EACrB,KAAK,SAAS,EAMf,MAAM,YAAY,CAAC;AAsEpB;;;;;GAKG;AAEH,wBAAgB,OAAO,CACrB,CAAC,EAAE,WAAW,EAAE,CAAC,EAAE,WAAW,EAAE,CAAC,EAAE,WAAW,EAAE,GAAG,EAAE,WAAW,GAC/D,IAAI,CAmDN;AACD;;GAEG;AACH,eAAO,MAAM,YAAY,EAAE,SAIzB,CAAC;AACH;;;GAGG;AACH,eAAO,MAAM,QAAQ,EAAE,SAIrB,CAAC;AAEH;;;;GAIG;AACH,eAAO,MAAM,SAAS,EAAE,SAKtB,CAAC;AAEH;;GAEG;AACH,eAAO,MAAM,OAAO,EAAE,SAIpB,CAAC;AAEH;;GAEG;AACH,eAAO,MAAM,QAAQ,EAAE,SAIrB,CAAC;AA6BH;;;;;;;;GAQG;AACH,eAAO,MAAM,cAAc,GACxB,WAAW,SAAS,MACpB,KAAK,UAAU,EAAE,OAAO,UAAU,EAAE,MAAM,UAAU,KAAG,gBA0BvD,CAAC;AAEJ;;;;;GAKG;AACH,eAAO,MAAM,gBAAgB,EAAE,SAG9B,CAAC;AACF;;;;;GAKG;AACH,eAAO,MAAM,iBAAiB,EAAE,SAG/B,CAAC"}
+315
View File
@@ -0,0 +1,315 @@
/**
* [ChaCha20](https://cr.yp.to/chacha.html) stream cipher, released
* in 2008. Developed after Salsa20, ChaCha aims to increase diffusion per round.
* It was standardized in [RFC 8439](https://datatracker.ietf.org/doc/html/rfc8439) and
* is now used in TLS 1.3.
*
* [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 [PDF](http://cr.yp.to/chacha/chacha-20080128.pdf) and
* [wiki](https://en.wikipedia.org/wiki/Salsa20).
* @module
*/
import { createCipher, rotl } from "./_arx.js";
import { poly1305 } from "./_poly1305.js";
import { clean, equalBytes, getOutput, u64Lengths, wrapCipher, } from "./utils.js";
/**
* ChaCha core function.
*/
// 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 Counter 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);
}
// 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;
}
/**
* hchacha helper method, used primarily in xchacha, to hash
* key and nonce into key' and nonce'.
* Same as chachaCore, but there doesn't seem to be a way to move the block
* out without 25% performance hit.
*/
// prettier-ignore
export function hchacha(s, k, i, o32) {
let x00 = s[0], x01 = s[1], x02 = s[2], x03 = s[3], x04 = k[0], x05 = k[1], x06 = k[2], x07 = k[3], x08 = k[4], x09 = k[5], x10 = k[6], x11 = k[7], x12 = i[0], x13 = i[1], x14 = i[2], x15 = 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);
}
let oi = 0;
o32[oi++] = x00;
o32[oi++] = x01;
o32[oi++] = x02;
o32[oi++] = x03;
o32[oi++] = x12;
o32[oi++] = x13;
o32[oi++] = x14;
o32[oi++] = x15;
}
/**
* Original, non-RFC chacha20 from DJB. 8-byte nonce, 8-byte counter.
*/
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 12-byte nonce, it's not safe to use fill it with random (CSPRNG), due to collision chance.
*/
export const chacha20 = /* @__PURE__ */ createCipher(chachaCore, {
counterRight: false,
counterLength: 4,
allowShortKeys: false,
});
/**
* XChaCha eXtended-nonce ChaCha. 24-byte nonce.
* With 24-byte nonce, it's safe to use fill it with random (CSPRNG).
* https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha
*/
export const xchacha20 = /* @__PURE__ */ createCipher(chachaCore, {
counterRight: false,
counterLength: 8,
extendNonceFn: hchacha,
allowShortKeys: false,
});
/**
* Reduced 8-round chacha, described in original paper.
*/
export const chacha8 = /* @__PURE__ */ createCipher(chachaCore, {
counterRight: false,
counterLength: 4,
rounds: 8,
});
/**
* Reduced 12-round chacha, described in original paper.
*/
export const chacha12 = /* @__PURE__ */ createCipher(chachaCore, {
counterRight: false,
counterLength: 4,
rounds: 12,
});
const ZEROS16 = /* @__PURE__ */ new Uint8Array(16);
// Pad to digest size with zeros
const updatePadded = (h, msg) => {
h.update(msg);
const left = msg.length % 16;
if (left)
h.update(ZEROS16.subarray(left));
};
const ZEROS32 = /* @__PURE__ */ new Uint8Array(32);
function computeTag(fn, key, nonce, data, AAD) {
const authKey = fn(key, nonce, ZEROS32);
const h = poly1305.create(authKey);
if (AAD)
updatePadded(h, AAD);
updatePadded(h, data);
const num = u64Lengths(data.length, AAD ? AAD.length : 0, true);
h.update(num);
const res = h.digest();
clean(authKey, num);
return res;
}
/**
* AEAD algorithm from RFC 8439.
* Salsa20 and chacha (RFC 8439) use poly1305 differently.
* We could have composed them similar to:
* https://github.com/paulmillr/scure-base/blob/b266c73dde977b1dd7ef40ef7a23cc15aab526b3/index.ts#L250
* 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) => {
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);
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);
if (!equalBytes(passedTag, tag))
throw new Error('invalid tag');
output.set(ciphertext.subarray(0, -tagLength));
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.
*/
export const chacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 12, tagLength: 16 }, _poly1305_aead(chacha20));
/**
* XChaCha20-Poly1305 extended-nonce chacha.
*
* Can be safely used with random nonces (CSPRNG).
* See [IRTF draft](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha).
*/
export const xchacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 24, tagLength: 16 }, _poly1305_aead(xchacha20));
//# sourceMappingURL=chacha.js.map
File diff suppressed because one or more lines are too long
+2
View File
@@ -0,0 +1,2 @@
export declare const crypto: any;
//# sourceMappingURL=crypto.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"crypto.d.ts","sourceRoot":"","sources":["../src/crypto.ts"],"names":[],"mappings":"AAOA,eAAO,MAAM,MAAM,EAAE,GACqE,CAAC"}
+2
View File
@@ -0,0 +1,2 @@
export const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
//# sourceMappingURL=crypto.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"crypto.js","sourceRoot":"","sources":["../src/crypto.ts"],"names":[],"mappings":"AAOA,MAAM,CAAC,MAAM,MAAM,GACjB,OAAO,UAAU,KAAK,QAAQ,IAAI,QAAQ,IAAI,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC"}
+2
View File
@@ -0,0 +1,2 @@
export declare const crypto: any;
//# sourceMappingURL=cryptoNode.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"cryptoNode.d.ts","sourceRoot":"","sources":["../src/cryptoNode.ts"],"names":[],"mappings":"AASA,eAAO,MAAM,MAAM,EAAE,GAKJ,CAAC"}
+15
View File
@@ -0,0 +1,15 @@
/**
* Internal webcrypto alias.
* We prefer WebCrypto aka globalThis.crypto, which exists in node.js 16+.
* Falls back to Node.js built-in crypto for Node.js <=v14.
* See utils.ts for details.
* @module
*/
// @ts-ignore
import * as nc from 'node:crypto';
export const crypto = nc && typeof nc === 'object' && 'webcrypto' in nc
? nc.webcrypto
: nc && typeof nc === 'object' && 'randomBytes' in nc
? nc
: undefined;
//# sourceMappingURL=cryptoNode.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"cryptoNode.js","sourceRoot":"","sources":["../src/cryptoNode.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,aAAa;AACb,OAAO,KAAK,EAAE,MAAM,aAAa,CAAC;AAClC,MAAM,CAAC,MAAM,MAAM,GACjB,EAAE,IAAI,OAAO,EAAE,KAAK,QAAQ,IAAI,WAAW,IAAI,EAAE;IAC/C,CAAC,CAAE,EAAE,CAAC,SAAiB;IACvB,CAAC,CAAC,EAAE,IAAI,OAAO,EAAE,KAAK,QAAQ,IAAI,aAAa,IAAI,EAAE;QACnD,CAAC,CAAC,EAAE;QACJ,CAAC,CAAC,SAAS,CAAC"}
+9
View File
@@ -0,0 +1,9 @@
import { type Cipher } from './utils.ts';
/** FPE-FF1 format-preserving encryption */
export declare function FF1(radix: number, key: Uint8Array, tweak?: Uint8Array): {
encrypt(x: number[]): number[];
decrypt(x: number[]): number[];
};
/** Binary version of FPE-FF1 format-preserving encryption. */
export declare function BinaryFF1(key: Uint8Array, tweak?: Uint8Array): Cipher;
//# sourceMappingURL=ff1.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"ff1.d.ts","sourceRoot":"","sources":["../src/ff1.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,KAAK,MAAM,EAA4D,MAAM,YAAY,CAAC;AA0FnG,2CAA2C;AAC3C,wBAAgB,GAAG,CACjB,KAAK,EAAE,MAAM,EACb,GAAG,EAAE,UAAU,EACf,KAAK,GAAE,UAAsB,GAC5B;IAAE,OAAO,CAAC,CAAC,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,CAAC;IAAC,OAAO,CAAC,CAAC,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,CAAA;CAAE,CAgCpE;AAqBD,8DAA8D;AAC9D,wBAAgB,SAAS,CAAC,GAAG,EAAE,UAAU,EAAE,KAAK,GAAE,UAAsB,GAAG,MAAM,CAMhF"}
+160
View File
@@ -0,0 +1,160 @@
/**
* FPE-FF1 (Format-preserving encryption algorithm) specified in
* [NIST 800-38G](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf).
* @module
*/
import { unsafe } from "./aes.js";
import { abytes, anumber, bytesToNumberBE, clean, numberToBytesBE } from "./utils.js";
// 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 NIST Special Publication 800-38G.
// https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf
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');
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);
view.setUint16(4, radix, false);
view.setUint32(8, x.length, false);
view.setUint32(12, tweak.length, false);
// Q = T || [0](tb1) 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);
// PRF
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 */
export function FF1(radix, key, tweak = EMPTY_BUF) {
anumber(radix);
abytes(key);
abytes(tweak);
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 string which encodes each byte in little-endian byte order
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 version of FPE-FF1 format-preserving encryption. */
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
File diff suppressed because one or more lines are too long
+2
View File
@@ -0,0 +1,2 @@
export {};
//# sourceMappingURL=index.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":""}
+28
View File
@@ -0,0 +1,28 @@
/**
* Audited & minimal JS implementation of Salsa20, ChaCha and AES. Check out individual modules.
* @example
```js
import { gcm, siv } from '@noble/ciphers/aes';
import { xsalsa20poly1305 } from '@noble/ciphers/salsa';
import { secretbox } from '@noble/ciphers/salsa'; // == xsalsa20poly1305
import { chacha20poly1305, xchacha20poly1305 } from '@noble/ciphers/chacha';
// Unauthenticated encryption: make sure to use HMAC or similar
import { ctr, cfb, cbc, ecb } from '@noble/ciphers/aes';
import { salsa20, xsalsa20 } from '@noble/ciphers/salsa';
import { chacha20, xchacha20, chacha8, chacha12 } from '@noble/ciphers/chacha';
// KW
import { aeskw, aeskwp } from '@noble/ciphers/aes';
// Utilities
import { bytesToHex, hexToBytes, bytesToUtf8, utf8ToBytes } from '@noble/ciphers/utils';
import { managedNonce, randomBytes } from '@noble/ciphers/webcrypto';
import { poly1305 } from '@noble/ciphers/_poly1305';
import { ghash, polyval } from '@noble/ciphers/_polyval';
```
* @module
*/
throw new Error('root module cannot be imported: import submodules instead. Check out README');
export {};
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,MAAM,IAAI,KAAK,CAAC,6EAA6E,CAAC,CAAC"}
+10
View File
@@ -0,0 +1,10 @@
{
"type": "module",
"sideEffects": false,
"browser": {
"node:crypto": false
},
"node": {
"./crypto": "./esm/cryptoNode.js"
}
}
+33
View File
@@ -0,0 +1,33 @@
import { type ARXCipher, type XorStream } from './utils.ts';
/**
* hsalsa hashing function, used primarily in xsalsa, to hash
* key and nonce into key' and nonce'.
* Same as salsaCore, but there doesn't seem to be a way to move the block
* out without 25% performance hit.
*/
export declare function hsalsa(s: Uint32Array, k: Uint32Array, i: Uint32Array, o32: Uint32Array): void;
/**
* Salsa20 from original paper.
* Unsafe to use random nonces under the same key, due to collision chance.
* Prefer XSalsa instead.
*/
export declare const salsa20: XorStream;
/**
* xsalsa20 eXtended-nonce salsa.
* Can be safely used with random 24-byte nonces (CSPRNG).
*/
export declare const xsalsa20: XorStream;
/**
* xsalsa20-poly1305 eXtended-nonce salsa.
* Can be safely used with random 24-byte nonces (CSPRNG).
* Also known as secretbox from libsodium / nacl.
*/
export declare const xsalsa20poly1305: ARXCipher;
/**
* Alias to `xsalsa20poly1305`, for compatibility with libsodium / nacl
*/
export declare function secretbox(key: Uint8Array, nonce: Uint8Array): {
seal: (plaintext: Uint8Array, output?: Uint8Array) => Uint8Array;
open: (ciphertext: Uint8Array, output?: Uint8Array) => Uint8Array;
};
//# sourceMappingURL=salsa.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"salsa.d.ts","sourceRoot":"","sources":["../src/salsa.ts"],"names":[],"mappings":"AAiBA,OAAO,EAEL,KAAK,SAAS,EAMd,KAAK,SAAS,EACf,MAAM,YAAY,CAAC;AA+CpB;;;;;GAKG;AAEH,wBAAgB,MAAM,CACpB,CAAC,EAAE,WAAW,EAAE,CAAC,EAAE,WAAW,EAAE,CAAC,EAAE,WAAW,EAAE,GAAG,EAAE,WAAW,GAC/D,IAAI,CA4BN;AAED;;;;GAIG;AACH,eAAO,MAAM,OAAO,EAAE,SAGpB,CAAC;AAEH;;;GAGG;AACH,eAAO,MAAM,QAAQ,EAAE,SAGrB,CAAC;AAEH;;;;GAIG;AACH,eAAO,MAAM,gBAAgB,EAAE,SAsC9B,CAAC;AAEF;;GAEG;AACH,wBAAgB,SAAS,CACvB,GAAG,EAAE,UAAU,EACf,KAAK,EAAE,UAAU,GAChB;IACD,IAAI,EAAE,CAAC,SAAS,EAAE,UAAU,EAAE,MAAM,CAAC,EAAE,UAAU,KAAK,UAAU,CAAC;IACjE,IAAI,EAAE,CAAC,UAAU,EAAE,UAAU,EAAE,MAAM,CAAC,EAAE,UAAU,KAAK,UAAU,CAAC;CACnE,CAGA"}
+201
View File
@@ -0,0 +1,201 @@
/**
* [Salsa20](https://cr.yp.to/snuffle.html) 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.
*
* Check out [PDF](https://cr.yp.to/snuffle/salsafamily-20071225.pdf) and
* [wiki](https://en.wikipedia.org/wiki/Salsa20).
* @module
*/
import { createCipher, rotl } from "./_arx.js";
import { poly1305 } from "./_poly1305.js";
import { abytes, clean, equalBytes, getOutput, wrapCipher, } from "./utils.js";
/** Salsa20 core function. */
// prettier-ignore
function salsaCore(s, k, n, out, cnt, rounds = 20) {
// Based on https://cr.yp.to/salsa20.html
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 hashing function, used primarily in xsalsa, to hash
* key and nonce into key' and nonce'.
* Same as salsaCore, but there doesn't seem to be a way to move the block
* out without 25% performance hit.
*/
// prettier-ignore
export function hsalsa(s, k, i, o32) {
let x00 = s[0], x01 = k[0], x02 = k[1], x03 = k[2], x04 = k[3], x05 = s[1], x06 = i[0], x07 = i[1], x08 = i[2], x09 = i[3], x10 = s[2], x11 = k[4], x12 = k[5], x13 = k[6], x14 = k[7], x15 = 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;
o32[oi++] = x00;
o32[oi++] = x05;
o32[oi++] = x10;
o32[oi++] = x15;
o32[oi++] = x06;
o32[oi++] = x07;
o32[oi++] = x08;
o32[oi++] = x09;
}
/**
* Salsa20 from original paper.
* Unsafe to use random nonces under the same key, due to collision chance.
* Prefer XSalsa instead.
*/
export const salsa20 = /* @__PURE__ */ createCipher(salsaCore, {
allowShortKeys: true,
counterRight: true,
});
/**
* xsalsa20 eXtended-nonce salsa.
* Can be safely used with random 24-byte nonces (CSPRNG).
*/
export const xsalsa20 = /* @__PURE__ */ createCipher(salsaCore, {
counterRight: true,
extendNonceFn: hsalsa,
});
/**
* xsalsa20-poly1305 eXtended-nonce salsa.
* Can be safely used with random 24-byte nonces (CSPRNG).
* Also known as secretbox from libsodium / nacl.
*/
export const xsalsa20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 24, tagLength: 16 }, (key, nonce) => {
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.
output = getOutput(plaintext.length + 32, output, false); // need 32 additional bytes, see above
const authKey = output.subarray(0, 32); // output[0..32] = poly1305 auth key
const ciphPlaintext = output.subarray(32); // output[32..] = plaintext, then ciphertext
output.set(plaintext, 32);
clean(authKey); // authKey is produced by xoring with zeros
xsalsa20(key, nonce, output, output); // output = stream ^ output; authKey = stream ^ zeros(32)
const tag = poly1305(ciphPlaintext, authKey); // calculate tag over ciphertext
output.set(tag, 16); // output[16..32] = tag
clean(output.subarray(0, 16), tag); // clean-up authKey remnants & copy of tag
return output.subarray(16); // return output[16..]
},
decrypt(ciphertext, output) {
// tmp part passed tag ciphertext
// [0..32] [32..48] [48..]
abytes(ciphertext);
output = getOutput(ciphertext.length + 32, output, false);
const tmp = output.subarray(0, 32); // output[0..32] is used to calc authKey
const passedTag = output.subarray(32, 48); // output[32..48] = passed tag
const ciphPlaintext = output.subarray(48); // output[48..] = ciphertext, then plaintext
output.set(ciphertext, 32); // copy ciphertext into output
clean(tmp); // authKey is produced by xoring with zeros
const authKey = xsalsa20(key, nonce, tmp, tmp); // authKey = stream ^ zeros(32)
const tag = poly1305(ciphPlaintext, authKey); // calculate tag over ciphertext
if (!equalBytes(passedTag, tag))
throw new Error('invalid tag');
xsalsa20(key, nonce, output.subarray(16), output.subarray(16)); // output = stream ^ output[16..]
clean(tmp, passedTag, tag);
return ciphPlaintext; // return output[48..], skipping zeroized output[0..48]
},
};
});
/**
* Alias to `xsalsa20poly1305`, for compatibility with libsodium / nacl
*/
export function secretbox(key, nonce) {
const xs = xsalsa20poly1305(key, nonce);
return { seal: xs.encrypt, open: xs.decrypt };
}
//# sourceMappingURL=salsa.js.map
File diff suppressed because one or more lines are too long
+155
View File
@@ -0,0 +1,155 @@
/**
* 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. */
export declare function isBytes(a: unknown): a is Uint8Array;
/** Asserts something is boolean. */
export declare function abool(b: boolean): void;
/** Asserts something is positive integer. */
export declare function anumber(n: number): void;
/** Asserts something is Uint8Array. */
export declare function abytes(b: Uint8Array | undefined, ...lengths: number[]): void;
/**
* Asserts something is hash
* TODO: remove
* @deprecated
*/
export declare function ahash(h: IHash): void;
/** Asserts a hash instance has not been destroyed / finished */
export declare function aexists(instance: any, checkFinished?: boolean): void;
/** Asserts output is properly-sized byte array */
export declare function aoutput(out: any, instance: any): void;
export type IHash = {
(data: string | Uint8Array): Uint8Array;
blockLen: number;
outputLen: number;
create: any;
};
/** Generic type encompassing 8/16/32-byte arrays - but not 64-byte. */
export type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array | Uint16Array | Int16Array | Uint32Array | Int32Array;
/** Cast u8 / u16 / u32 to u8. */
export declare function u8(arr: TypedArray): Uint8Array;
/** Cast u8 / u16 / u32 to u32. */
export declare function u32(arr: TypedArray): Uint32Array;
/** Zeroize a byte array. Warning: JS provides no guarantees. */
export declare function clean(...arrays: TypedArray[]): void;
/** Create DataView of an array for easy byte-level manipulation. */
export declare function createView(arr: TypedArray): DataView;
/** Is current platform little-endian? Most are. Big-Endian platform: IBM */
export declare const isLE: boolean;
/**
* Convert byte array to hex string. Uses built-in function, when available.
* @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
*/
export declare function bytesToHex(bytes: Uint8Array): string;
/**
* Convert hex string to byte array. Uses built-in function, when available.
* @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
*/
export declare function hexToBytes(hex: string): Uint8Array;
export declare function hexToNumber(hex: string): bigint;
export declare function bytesToNumberBE(bytes: Uint8Array): bigint;
export declare function numberToBytesBE(n: number | bigint, len: number): Uint8Array;
export declare const nextTick: () => Promise<void>;
/**
* Converts string to bytes using UTF8 encoding.
* @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
*/
export declare function utf8ToBytes(str: string): Uint8Array;
/**
* Converts bytes to string using UTF8 encoding.
* @example bytesToUtf8(new Uint8Array([97, 98, 99])) // 'abc'
*/
export declare function bytesToUtf8(bytes: Uint8Array): string;
export type Input = Uint8Array | string;
/**
* Normalizes (non-hex) string or Uint8Array to Uint8Array.
* Warning: when Uint8Array is passed, it would NOT get copied.
* Keep in mind for future mutable operations.
*/
export declare function toBytes(data: string | Uint8Array): Uint8Array;
/**
* Checks if two U8A use same underlying buffer and overlaps.
* This is invalid and can corrupt data.
*/
export declare function overlapBytes(a: Uint8Array, b: 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/salse, which designed with this)
*/
export declare function complexOverlapBytes(input: Uint8Array, output: Uint8Array): void;
/**
* Copies several Uint8Arrays into one.
*/
export declare function concatBytes(...arrays: Uint8Array[]): Uint8Array;
type EmptyObj = {};
export declare function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(defaults: T1, opts: T2): T1 & T2;
/** Compares 2 uint8array-s in kinda constant time. */
export declare function equalBytes(a: Uint8Array, b: Uint8Array): boolean;
/** For runtime check if class implements interface. */
export declare abstract class Hash<T extends Hash<T>> {
abstract blockLen: number;
abstract outputLen: number;
abstract update(buf: string | Uint8Array): this;
abstract digestInto(buf: Uint8Array): void;
abstract digest(): 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.
*/
abstract destroy(): void;
}
/** Sync cipher: takes byte array and returns byte array. */
export type Cipher = {
encrypt(plaintext: Uint8Array): Uint8Array;
decrypt(ciphertext: Uint8Array): Uint8Array;
};
/** Async cipher e.g. from built-in WebCrypto. */
export type AsyncCipher = {
encrypt(plaintext: Uint8Array): Promise<Uint8Array>;
decrypt(ciphertext: Uint8Array): Promise<Uint8Array>;
};
/** Cipher with `output` argument which can optimize by doing 1 less allocation. */
export type CipherWithOutput = Cipher & {
encrypt(plaintext: Uint8Array, output?: Uint8Array): Uint8Array;
decrypt(ciphertext: Uint8Array, output?: Uint8Array): 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 = {
blockSize: number;
nonceLength?: number;
tagLength?: number;
varSizeNonce?: boolean;
};
/** ARX cipher, like salsa or chacha. */
export type ARXCipher = ((key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array) => CipherWithOutput) & {
blockSize: number;
nonceLength: number;
tagLength: number;
};
export type CipherCons<T extends any[]> = (key: Uint8Array, ...args: T) => Cipher;
/**
* Wraps a cipher: validates args, ensures encrypt() can only be called once.
* @__NO_SIDE_EFFECTS__
*/
export declare const wrapCipher: <C extends CipherCons<any>, P extends CipherParams>(params: P, constructor: C) => C & P;
/** Represents salsa / chacha stream. */
export type XorStream = (key: Uint8Array, nonce: Uint8Array, data: Uint8Array, output?: Uint8Array, counter?: number) => Uint8Array;
/**
* By default, returns u8a of length.
* When out is available, it checks it for validity and uses it.
*/
export declare function getOutput(expectedLength: number, out?: Uint8Array, onlyAligned?: boolean): Uint8Array;
/** Polyfill for Safari 14. */
export declare function setBigUint64(view: DataView, byteOffset: number, value: bigint, isLE: boolean): void;
export declare function u64Lengths(dataLength: number, aadLength: number, isLE: boolean): Uint8Array;
export declare function isAligned32(bytes: Uint8Array): boolean;
export declare function copyBytes(bytes: Uint8Array): Uint8Array;
export {};
//# sourceMappingURL=utils.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"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"}
+339
View File
@@ -0,0 +1,339 @@
/**
* 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. */
export function isBytes(a) {
return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
}
/** Asserts something is boolean. */
export function abool(b) {
if (typeof b !== 'boolean')
throw new Error(`boolean expected, not ${b}`);
}
/** Asserts something is positive integer. */
export function anumber(n) {
if (!Number.isSafeInteger(n) || n < 0)
throw new Error('positive integer expected, got ' + n);
}
/** Asserts something is Uint8Array. */
export function abytes(b, ...lengths) {
if (!isBytes(b))
throw new Error('Uint8Array expected');
if (lengths.length > 0 && !lengths.includes(b.length))
throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
}
/**
* Asserts something is hash
* TODO: remove
* @deprecated
*/
export function ahash(h) {
if (typeof h !== 'function' || typeof h.create !== 'function')
throw new Error('Hash should be wrapped by utils.createHasher');
anumber(h.outputLen);
anumber(h.blockLen);
}
/** Asserts a hash instance has not been destroyed / finished */
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 properly-sized byte array */
export function aoutput(out, instance) {
abytes(out);
const min = instance.outputLen;
if (out.length < min) {
throw new Error('digestInto() expects output buffer of length at least ' + min);
}
}
/** Cast u8 / u16 / u32 to u8. */
export function u8(arr) {
return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
}
/** Cast u8 / u16 / u32 to u32. */
export function u32(arr) {
return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
}
/** Zeroize a byte array. Warning: JS provides no guarantees. */
export function clean(...arrays) {
for (let i = 0; i < arrays.length; i++) {
arrays[i].fill(0);
}
}
/** Create DataView of an array for easy byte-level manipulation. */
export function createView(arr) {
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
}
/** Is current platform little-endian? Most are. Big-Endian platform: IBM */
export const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
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.
* @example 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.
* @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
*/
export function hexToBytes(hex) {
if (typeof hex !== 'string')
throw new Error('hex string expected, got ' + typeof hex);
// @ts-ignore
if (hasHexBuiltin)
return Uint8Array.fromHex(hex);
const hl = hex.length;
const al = hl / 2;
if (hl % 2)
throw new Error('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 Error('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
export function hexToNumber(hex) {
if (typeof hex !== 'string')
throw new Error('hex string expected, got ' + typeof hex);
return BigInt(hex === '' ? '0' : '0x' + hex); // Big Endian
}
// Used in ff1
// BE: Big Endian, LE: Little Endian
export function bytesToNumberBE(bytes) {
return hexToNumber(bytesToHex(bytes));
}
// Used in micro, ff1
export function numberToBytesBE(n, len) {
return hexToBytes(n.toString(16).padStart(len * 2, '0'));
}
// TODO: remove
// There is no setImmediate in browser and setTimeout is slow.
// call of async fn will return Promise, which will be fullfiled only on
// next scheduler queue processing step and this is exactly what we need.
export const nextTick = async () => { };
/**
* Converts string to bytes using UTF8 encoding.
* @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
*/
export function utf8ToBytes(str) {
if (typeof str !== 'string')
throw new Error('string expected');
return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
}
/**
* Converts bytes to string using UTF8 encoding.
* @example bytesToUtf8(new Uint8Array([97, 98, 99])) // 'abc'
*/
export function bytesToUtf8(bytes) {
return new TextDecoder().decode(bytes);
}
/**
* Normalizes (non-hex) string or Uint8Array to Uint8Array.
* Warning: when Uint8Array is passed, it would NOT get copied.
* Keep in mind for future mutable operations.
*/
export function toBytes(data) {
if (typeof data === 'string')
data = utf8ToBytes(data);
else if (isBytes(data))
data = copyBytes(data);
else
throw new Error('Uint8Array expected, got ' + typeof data);
return data;
}
/**
* Checks if two U8A use same underlying buffer and overlaps.
* This is invalid and can corrupt data.
*/
export function overlapBytes(a, b) {
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/salse, which designed with this)
*/
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.
*/
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;
}
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 2 uint8array-s in kinda constant time. */
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;
}
// TODO: remove
/** For runtime check if class implements interface. */
export class Hash {
}
/**
* Wraps a cipher: validates args, ensures encrypt() can only be called once.
* @__NO_SIDE_EFFECTS__
*/
export const wrapCipher = (params, constructor) => {
function wrappedCipher(key, ...args) {
// Validate key
abytes(key);
// Big-Endian hardware is rare. Just in case someone still decides to run ciphers:
if (!isLE)
throw new Error('Non little-endian hardware is not yet supported');
// Validate nonce if nonceLength is present
if (params.nonceLength !== undefined) {
const nonce = args[0];
if (!nonce)
throw new Error('nonce / iv required');
if (params.varSizeNonce)
abytes(nonce);
else
abytes(nonce, params.nonceLength);
}
// Validate AAD if tagLength present
const tagl = params.tagLength;
if (tagl && args[1] !== undefined) {
abytes(args[1]);
}
const cipher = constructor(key, ...args);
const checkOutput = (fnLength, output) => {
if (output !== undefined) {
if (fnLength !== 2)
throw new Error('cipher output not supported');
abytes(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('invalid ciphertext length: smaller 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.
*/
export function getOutput(expectedLength, out, onlyAligned = true) {
if (out === undefined)
return new Uint8Array(expectedLength);
if (out.length !== expectedLength)
throw new Error('invalid output length, expected ' + expectedLength + ', got: ' + out.length);
if (onlyAligned && !isAligned32(out))
throw new Error('invalid output, must be aligned');
return out;
}
/** Polyfill for Safari 14. */
export function setBigUint64(view, byteOffset, value, isLE) {
if (typeof view.setBigUint64 === 'function')
return view.setBigUint64(byteOffset, value, isLE);
const _32n = BigInt(32);
const _u32_max = BigInt(0xffffffff);
const wh = Number((value >> _32n) & _u32_max);
const wl = Number(value & _u32_max);
const h = isLE ? 4 : 0;
const l = isLE ? 0 : 4;
view.setUint32(byteOffset + h, wh, isLE);
view.setUint32(byteOffset + l, wl, isLE);
}
export function u64Lengths(dataLength, aadLength, isLE) {
abool(isLE);
const num = new Uint8Array(16);
const view = createView(num);
setBigUint64(view, 0, BigInt(aadLength), isLE);
setBigUint64(view, 8, BigInt(dataLength), isLE);
return num;
}
// Is byte array aligned to 4 byte offset (u32)?
export function isAligned32(bytes) {
return bytes.byteOffset % 4 === 0;
}
// copy bytes to new u8a (aligned). Because Buffer.slice is broken.
export function copyBytes(bytes) {
return Uint8Array.from(bytes);
}
//# sourceMappingURL=utils.js.map
File diff suppressed because one or more lines are too long
+31
View File
@@ -0,0 +1,31 @@
import { type AsyncCipher, type Cipher } from './utils.ts';
/**
* Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.
*/
export declare function randomBytes(bytesLength?: number): Uint8Array;
export declare function getWebcryptoSubtle(): any;
type RemoveNonceInner<T extends any[], Ret> = ((...args: T) => Ret) extends (arg0: any, arg1: any, ...rest: infer R) => any ? (key: Uint8Array, ...args: R) => Ret : never;
type RemoveNonce<T extends (...args: any) => any> = RemoveNonceInner<Parameters<T>, ReturnType<T>>;
type CipherWithNonce = ((key: Uint8Array, nonce: Uint8Array, ...args: any[]) => Cipher) & {
nonceLength: number;
};
/**
* Uses CSPRG for nonce, nonce injected in ciphertext.
* @example
* const gcm = managedNonce(aes.gcm);
* const ciphr = gcm(key).encrypt(data);
* const plain = gcm(key).decrypt(ciph);
*/
export declare function managedNonce<T extends CipherWithNonce>(fn: T): RemoveNonce<T>;
export declare const utils: {
encrypt: (key: Uint8Array, ...all: any[]) => Promise<Uint8Array>;
decrypt: (key: Uint8Array, ...all: any[]) => Promise<Uint8Array>;
};
/** AES-CBC, native webcrypto version */
export declare const cbc: (key: Uint8Array, iv: Uint8Array) => AsyncCipher;
/** AES-CTR, native webcrypto version */
export declare const ctr: (key: Uint8Array, nonce: Uint8Array) => AsyncCipher;
/** AES-GCM, native webcrypto version */
export declare const gcm: (key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array) => AsyncCipher;
export {};
//# sourceMappingURL=webcrypto.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"webcrypto.d.ts","sourceRoot":"","sources":["../src/webcrypto.ts"],"names":[],"mappings":"AAYA,OAAO,EAAmB,KAAK,WAAW,EAAE,KAAK,MAAM,EAAe,MAAM,YAAY,CAAC;AAEzF;;GAEG;AACH,wBAAgB,WAAW,CAAC,WAAW,SAAK,GAAG,UAAU,CASxD;AAED,wBAAgB,kBAAkB,IAAI,GAAG,CAGxC;AAED,KAAK,gBAAgB,CAAC,CAAC,SAAS,GAAG,EAAE,EAAE,GAAG,IAAI,CAAC,CAAC,GAAG,IAAI,EAAE,CAAC,KAAK,GAAG,CAAC,SAAS,CAC1E,IAAI,EAAE,GAAG,EACT,IAAI,EAAE,GAAG,EACT,GAAG,IAAI,EAAE,MAAM,CAAC,KACb,GAAG,GACJ,CAAC,GAAG,EAAE,UAAU,EAAE,GAAG,IAAI,EAAE,CAAC,KAAK,GAAG,GACpC,KAAK,CAAC;AAEV,KAAK,WAAW,CAAC,CAAC,SAAS,CAAC,GAAG,IAAI,EAAE,GAAG,KAAK,GAAG,IAAI,gBAAgB,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC;AACnG,KAAK,eAAe,GAAG,CAAC,CAAC,GAAG,EAAE,UAAU,EAAE,KAAK,EAAE,UAAU,EAAE,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,MAAM,CAAC,GAAG;IACxF,WAAW,EAAE,MAAM,CAAC;CACrB,CAAC;AAEF;;;;;;GAMG;AACH,wBAAgB,YAAY,CAAC,CAAC,SAAS,eAAe,EAAE,EAAE,EAAE,CAAC,GAAG,WAAW,CAAC,CAAC,CAAC,CAiB7E;AAID,eAAO,MAAM,KAAK,EAAE;IAClB,OAAO,EAAE,CAAC,GAAG,EAAE,UAAU,EAAE,GAAG,GAAG,EAAE,GAAG,EAAE,KAAK,OAAO,CAAC,UAAU,CAAC,CAAC;IACjE,OAAO,EAAE,CAAC,GAAG,EAAE,UAAU,EAAE,GAAG,GAAG,EAAE,GAAG,EAAE,KAAK,OAAO,CAAC,UAAU,CAAC,CAAC;CAwBlE,CAAC;AA2CF,wCAAwC;AACxC,eAAO,MAAM,GAAG,EAAE,CAAC,GAAG,EAAE,UAAU,EAAE,EAAE,EAAE,UAAU,KAAK,WAChC,CAAC;AACxB,wCAAwC;AACxC,eAAO,MAAM,GAAG,EAAE,CAAC,GAAG,EAAE,UAAU,EAAE,KAAK,EAAE,UAAU,KAAK,WACnC,CAAC;AACxB,wCAAwC;AACxC,eAAO,MAAM,GAAG,EAAE,CAAC,GAAG,EAAE,UAAU,EAAE,KAAK,EAAE,UAAU,EAAE,GAAG,CAAC,EAAE,UAAU,KAAK,WAC9B,CAAC"}
+135
View File
@@ -0,0 +1,135 @@
/**
* WebCrypto-based AES gcm/ctr/cbc, `managedNonce` and `randomBytes`.
* We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
* node.js versions earlier than v19 don't declare it in global scope.
* For node.js, package.js on#exports field mapping rewrites import
* from `crypto` to `cryptoNode`, which imports native module.
* Makes the utils un-importable in browsers without a bundler.
* Once node.js 18 is deprecated, we can just drop the import.
* @module
*/
// Use full path so that Node.js can rewrite it to `cryptoNode.js`.
import { crypto } from '@noble/ciphers/crypto';
import { abytes, anumber, concatBytes } from "./utils.js";
/**
* Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.
*/
export function randomBytes(bytesLength = 32) {
if (crypto && typeof crypto.getRandomValues === 'function') {
return crypto.getRandomValues(new Uint8Array(bytesLength));
}
// Legacy Node.js compatibility
if (crypto && typeof crypto.randomBytes === 'function') {
return Uint8Array.from(crypto.randomBytes(bytesLength));
}
throw new Error('crypto.getRandomValues must be defined');
}
export function getWebcryptoSubtle() {
if (crypto && typeof crypto.subtle === 'object' && crypto.subtle != null)
return crypto.subtle;
throw new Error('crypto.subtle must be defined');
}
/**
* Uses CSPRG for nonce, nonce injected in ciphertext.
* @example
* const gcm = managedNonce(aes.gcm);
* const ciphr = gcm(key).encrypt(data);
* const plain = gcm(key).decrypt(ciph);
*/
export function managedNonce(fn) {
const { nonceLength } = fn;
anumber(nonceLength);
return ((key, ...args) => ({
encrypt(plaintext, ...argsEnc) {
const nonce = randomBytes(nonceLength);
const ciphertext = fn(key, nonce, ...args).encrypt(plaintext, ...argsEnc);
const out = concatBytes(nonce, ciphertext);
ciphertext.fill(0);
return out;
},
decrypt(ciphertext, ...argsDec) {
const nonce = ciphertext.subarray(0, nonceLength);
const data = ciphertext.subarray(nonceLength);
return fn(key, nonce, ...args).decrypt(data, ...argsDec);
},
}));
}
// Overridable
// @TODO
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 };
if (algo === mode.CTR)
return { name: mode.CTR, counter: nonce, length: 64 };
if (algo === mode.GCM) {
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) {
return (key, nonce, AAD) => {
abytes(key);
abytes(nonce);
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);
},
};
};
}
/** AES-CBC, native webcrypto version */
export const cbc = /* @__PURE__ */ (() => generate(mode.CBC))();
/** AES-CTR, native webcrypto version */
export const ctr = /* @__PURE__ */ (() => generate(mode.CTR))();
/** AES-GCM, native webcrypto version */
export const gcm =
/* @__PURE__ */ (() => generate(mode.GCM))();
// // 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);
//# sourceMappingURL=webcrypto.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"webcrypto.js","sourceRoot":"","sources":["../src/webcrypto.ts"],"names":[],"mappings":"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"}
+9
View File
@@ -0,0 +1,9 @@
import { type Cipher } from './utils.ts';
/** FPE-FF1 format-preserving encryption */
export declare function FF1(radix: number, key: Uint8Array, tweak?: Uint8Array): {
encrypt(x: number[]): number[];
decrypt(x: number[]): number[];
};
/** Binary version of FPE-FF1 format-preserving encryption. */
export declare function BinaryFF1(key: Uint8Array, tweak?: Uint8Array): Cipher;
//# sourceMappingURL=ff1.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"ff1.d.ts","sourceRoot":"","sources":["src/ff1.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,KAAK,MAAM,EAA4D,MAAM,YAAY,CAAC;AA0FnG,2CAA2C;AAC3C,wBAAgB,GAAG,CACjB,KAAK,EAAE,MAAM,EACb,GAAG,EAAE,UAAU,EACf,KAAK,GAAE,UAAsB,GAC5B;IAAE,OAAO,CAAC,CAAC,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,CAAC;IAAC,OAAO,CAAC,CAAC,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,CAAA;CAAE,CAgCpE;AAqBD,8DAA8D;AAC9D,wBAAgB,SAAS,CAAC,GAAG,EAAE,UAAU,EAAE,KAAK,GAAE,UAAsB,GAAG,MAAM,CAMhF"}
+164
View File
@@ -0,0 +1,164 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FF1 = FF1;
exports.BinaryFF1 = BinaryFF1;
/**
* FPE-FF1 (Format-preserving encryption algorithm) specified in
* [NIST 800-38G](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf).
* @module
*/
const aes_ts_1 = require("./aes.js");
const utils_ts_1 = require("./utils.js");
// NOTE: no point in inlining encrypt instead of encryptBlock, since BigInt stuff will be slow
const { expandKeyLE, encryptBlock } = aes_ts_1.unsafe;
// Format-preserving encryption algorithm (FPE-FF1) specified in NIST Special Publication 800-38G.
// https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf
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');
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);
view.setUint16(4, radix, false);
view.setUint32(8, x.length, false);
view.setUint32(12, tweak.length, false);
// Q = T || [0](tb1) mod 16 || [i]1 || [NUMradix(B)]b.
const PQ = new Uint8Array(P.length + tweak.length + padding + 1 + b);
PQ.set(P);
(0, utils_ts_1.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((0, utils_ts_1.numberToBytesBE)(NUMradix(radix, B), b), PQ.length - b);
// PRF
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 = (0, utils_ts_1.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 = (0, utils_ts_1.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 = () => {
(0, utils_ts_1.clean)(xk, PQ);
};
return { u, round, destroy };
}
const EMPTY_BUF = /* @__PURE__ */ Uint8Array.of();
/** FPE-FF1 format-preserving encryption */
function FF1(radix, key, tweak = EMPTY_BUF) {
(0, utils_ts_1.anumber)(radix);
(0, utils_ts_1.abytes)(key);
(0, utils_ts_1.abytes)(tweak);
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 string which encodes each byte in little-endian byte order
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 version of FPE-FF1 format-preserving encryption. */
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
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
//# sourceMappingURL=index.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":""}
+28
View File
@@ -0,0 +1,28 @@
"use strict";
/**
* Audited & minimal JS implementation of Salsa20, ChaCha and AES. Check out individual modules.
* @example
```js
import { gcm, siv } from '@noble/ciphers/aes';
import { xsalsa20poly1305 } from '@noble/ciphers/salsa';
import { secretbox } from '@noble/ciphers/salsa'; // == xsalsa20poly1305
import { chacha20poly1305, xchacha20poly1305 } from '@noble/ciphers/chacha';
// Unauthenticated encryption: make sure to use HMAC or similar
import { ctr, cfb, cbc, ecb } from '@noble/ciphers/aes';
import { salsa20, xsalsa20 } from '@noble/ciphers/salsa';
import { chacha20, xchacha20, chacha8, chacha12 } from '@noble/ciphers/chacha';
// KW
import { aeskw, aeskwp } from '@noble/ciphers/aes';
// Utilities
import { bytesToHex, hexToBytes, bytesToUtf8, utf8ToBytes } from '@noble/ciphers/utils';
import { managedNonce, randomBytes } from '@noble/ciphers/webcrypto';
import { poly1305 } from '@noble/ciphers/_poly1305';
import { ghash, polyval } from '@noble/ciphers/_polyval';
```
* @module
*/
throw new Error('root module cannot be imported: import submodules instead. Check out README');
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,MAAM,IAAI,KAAK,CAAC,6EAA6E,CAAC,CAAC"}
+177
View File
@@ -0,0 +1,177 @@
{
"name": "@noble/ciphers",
"version": "1.3.0",
"description": "Audited & minimal JS implementation of Salsa20, ChaCha and AES",
"files": [
"esm",
"src",
"*.js",
"*.js.map",
"*.d.ts",
"*.d.ts.map"
],
"scripts": {
"bench": "node benchmark/noble.js",
"bench:compare": "node benchmark/compare.js",
"bench:install": "cd benchmark; npm install; npm install .. --install-links",
"build": "npm run build:clean; tsc && tsc -p tsconfig.cjs.json",
"build:release": "npx jsbt esbuild test/build",
"build:clean": "rm *.{js,d.ts,js.map,d.ts.map} esm/*.{js,d.ts,js.map,d.ts.map} 2> /dev/null",
"lint": "prettier --check 'src/**/*.{js,ts}' 'test/**/*.{js,ts,mjs}'",
"format": "prettier --write 'src/**/*.{js,ts}' 'test/**/*.{js,ts,mjs}'",
"test": "node --import ./test/esm-register.js test/index.js",
"test:bun": "bun test/index.js",
"test:deno": "deno --allow-env --allow-read --import-map=./test/import_map.json test/index.js",
"test:big": "node --import ./test/esm-register.js test/crosstest.test.js slow"
},
"author": "Paul Miller (https://paulmillr.com)",
"homepage": "https://paulmillr.com/noble/",
"repository": {
"type": "git",
"url": "git+https://github.com/paulmillr/noble-ciphers.git"
},
"license": "MIT",
"devDependencies": {
"@paulmillr/jsbt": "0.3.3",
"@scure/base": "1.2.5",
"fast-check": "3.0.0",
"micro-bmark": "0.4.1",
"micro-should": "0.5.2",
"prettier": "3.5.3",
"typescript": "5.8.3"
},
"engines": {
"node": "^14.21.3 || >=16"
},
"main": "index.js",
"exports": {
".": {
"import": "./esm/index.js",
"require": "./index.js"
},
"./_micro": {
"import": "./esm/_micro.js",
"require": "./_micro.js"
},
"./_poly1305": {
"import": "./esm/_poly1305.js",
"require": "./_poly1305.js"
},
"./_polyval": {
"import": "./esm/_polyval.js",
"require": "./_polyval.js"
},
"./aes": {
"import": "./esm/aes.js",
"require": "./aes.js"
},
"./chacha": {
"import": "./esm/chacha.js",
"require": "./chacha.js"
},
"./crypto": {
"types": "./crypto.d.ts",
"node": {
"import": "./esm/cryptoNode.js",
"default": "./cryptoNode.js"
},
"import": "./esm/crypto.js",
"default": "./crypto.js"
},
"./ff1": {
"import": "./esm/ff1.js",
"require": "./ff1.js"
},
"./index": {
"import": "./esm/index.js",
"require": "./index.js"
},
"./salsa": {
"import": "./esm/salsa.js",
"require": "./salsa.js"
},
"./utils": {
"import": "./esm/utils.js",
"require": "./utils.js"
},
"./webcrypto": {
"import": "./esm/webcrypto.js",
"require": "./webcrypto.js"
},
"./_micro.js": {
"import": "./esm/_micro.js",
"require": "./_micro.js"
},
"./_poly1305.js": {
"import": "./esm/_poly1305.js",
"require": "./_poly1305.js"
},
"./_polyval.js": {
"import": "./esm/_polyval.js",
"require": "./_polyval.js"
},
"./aes.js": {
"import": "./esm/aes.js",
"require": "./aes.js"
},
"./chacha.js": {
"import": "./esm/chacha.js",
"require": "./chacha.js"
},
"./crypto.js": {
"types": "./crypto.d.ts",
"node": {
"import": "./esm/cryptoNode.js",
"default": "./cryptoNode.js"
},
"import": "./esm/crypto.js",
"default": "./crypto.js"
},
"./ff1.js": {
"import": "./esm/ff1.js",
"require": "./ff1.js"
},
"./index.js": {
"import": "./esm/index.js",
"require": "./index.js"
},
"./salsa.js": {
"import": "./esm/salsa.js",
"require": "./salsa.js"
},
"./utils.js": {
"import": "./esm/utils.js",
"require": "./utils.js"
},
"./webcrypto.js": {
"import": "./esm/webcrypto.js",
"require": "./webcrypto.js"
}
},
"sideEffects": false,
"browser": {
"node:crypto": false,
"./crypto": "./crypto.js"
},
"keywords": [
"salsa20",
"chacha",
"aes",
"cryptography",
"crypto",
"noble",
"cipher",
"ciphers",
"xsalsa20",
"xchacha20",
"poly1305",
"xsalsa20poly1305",
"chacha20poly1305",
"xchacha20poly1305",
"secretbox",
"rijndael",
"siv",
"ff1"
],
"funding": "https://paulmillr.com/funding/"
}
+33
View File
@@ -0,0 +1,33 @@
import { type ARXCipher, type XorStream } from './utils.ts';
/**
* hsalsa hashing function, used primarily in xsalsa, to hash
* key and nonce into key' and nonce'.
* Same as salsaCore, but there doesn't seem to be a way to move the block
* out without 25% performance hit.
*/
export declare function hsalsa(s: Uint32Array, k: Uint32Array, i: Uint32Array, o32: Uint32Array): void;
/**
* Salsa20 from original paper.
* Unsafe to use random nonces under the same key, due to collision chance.
* Prefer XSalsa instead.
*/
export declare const salsa20: XorStream;
/**
* xsalsa20 eXtended-nonce salsa.
* Can be safely used with random 24-byte nonces (CSPRNG).
*/
export declare const xsalsa20: XorStream;
/**
* xsalsa20-poly1305 eXtended-nonce salsa.
* Can be safely used with random 24-byte nonces (CSPRNG).
* Also known as secretbox from libsodium / nacl.
*/
export declare const xsalsa20poly1305: ARXCipher;
/**
* Alias to `xsalsa20poly1305`, for compatibility with libsodium / nacl
*/
export declare function secretbox(key: Uint8Array, nonce: Uint8Array): {
seal: (plaintext: Uint8Array, output?: Uint8Array) => Uint8Array;
open: (ciphertext: Uint8Array, output?: Uint8Array) => Uint8Array;
};
//# sourceMappingURL=salsa.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"salsa.d.ts","sourceRoot":"","sources":["src/salsa.ts"],"names":[],"mappings":"AAiBA,OAAO,EAEL,KAAK,SAAS,EAMd,KAAK,SAAS,EACf,MAAM,YAAY,CAAC;AA+CpB;;;;;GAKG;AAEH,wBAAgB,MAAM,CACpB,CAAC,EAAE,WAAW,EAAE,CAAC,EAAE,WAAW,EAAE,CAAC,EAAE,WAAW,EAAE,GAAG,EAAE,WAAW,GAC/D,IAAI,CA4BN;AAED;;;;GAIG;AACH,eAAO,MAAM,OAAO,EAAE,SAGpB,CAAC;AAEH;;;GAGG;AACH,eAAO,MAAM,QAAQ,EAAE,SAGrB,CAAC;AAEH;;;;GAIG;AACH,eAAO,MAAM,gBAAgB,EAAE,SAsC9B,CAAC;AAEF;;GAEG;AACH,wBAAgB,SAAS,CACvB,GAAG,EAAE,UAAU,EACf,KAAK,EAAE,UAAU,GAChB;IACD,IAAI,EAAE,CAAC,SAAS,EAAE,UAAU,EAAE,MAAM,CAAC,EAAE,UAAU,KAAK,UAAU,CAAC;IACjE,IAAI,EAAE,CAAC,UAAU,EAAE,UAAU,EAAE,MAAM,CAAC,EAAE,UAAU,KAAK,UAAU,CAAC;CACnE,CAGA"}
+206
View File
@@ -0,0 +1,206 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.xsalsa20poly1305 = exports.xsalsa20 = exports.salsa20 = void 0;
exports.hsalsa = hsalsa;
exports.secretbox = secretbox;
/**
* [Salsa20](https://cr.yp.to/snuffle.html) 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.
*
* Check out [PDF](https://cr.yp.to/snuffle/salsafamily-20071225.pdf) and
* [wiki](https://en.wikipedia.org/wiki/Salsa20).
* @module
*/
const _arx_ts_1 = require("./_arx.js");
const _poly1305_ts_1 = require("./_poly1305.js");
const utils_ts_1 = require("./utils.js");
/** Salsa20 core function. */
// prettier-ignore
function salsaCore(s, k, n, out, cnt, rounds = 20) {
// Based on https://cr.yp.to/salsa20.html
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 ^= (0, _arx_ts_1.rotl)(x00 + x12 | 0, 7);
x08 ^= (0, _arx_ts_1.rotl)(x04 + x00 | 0, 9);
x12 ^= (0, _arx_ts_1.rotl)(x08 + x04 | 0, 13);
x00 ^= (0, _arx_ts_1.rotl)(x12 + x08 | 0, 18);
x09 ^= (0, _arx_ts_1.rotl)(x05 + x01 | 0, 7);
x13 ^= (0, _arx_ts_1.rotl)(x09 + x05 | 0, 9);
x01 ^= (0, _arx_ts_1.rotl)(x13 + x09 | 0, 13);
x05 ^= (0, _arx_ts_1.rotl)(x01 + x13 | 0, 18);
x14 ^= (0, _arx_ts_1.rotl)(x10 + x06 | 0, 7);
x02 ^= (0, _arx_ts_1.rotl)(x14 + x10 | 0, 9);
x06 ^= (0, _arx_ts_1.rotl)(x02 + x14 | 0, 13);
x10 ^= (0, _arx_ts_1.rotl)(x06 + x02 | 0, 18);
x03 ^= (0, _arx_ts_1.rotl)(x15 + x11 | 0, 7);
x07 ^= (0, _arx_ts_1.rotl)(x03 + x15 | 0, 9);
x11 ^= (0, _arx_ts_1.rotl)(x07 + x03 | 0, 13);
x15 ^= (0, _arx_ts_1.rotl)(x11 + x07 | 0, 18);
x01 ^= (0, _arx_ts_1.rotl)(x00 + x03 | 0, 7);
x02 ^= (0, _arx_ts_1.rotl)(x01 + x00 | 0, 9);
x03 ^= (0, _arx_ts_1.rotl)(x02 + x01 | 0, 13);
x00 ^= (0, _arx_ts_1.rotl)(x03 + x02 | 0, 18);
x06 ^= (0, _arx_ts_1.rotl)(x05 + x04 | 0, 7);
x07 ^= (0, _arx_ts_1.rotl)(x06 + x05 | 0, 9);
x04 ^= (0, _arx_ts_1.rotl)(x07 + x06 | 0, 13);
x05 ^= (0, _arx_ts_1.rotl)(x04 + x07 | 0, 18);
x11 ^= (0, _arx_ts_1.rotl)(x10 + x09 | 0, 7);
x08 ^= (0, _arx_ts_1.rotl)(x11 + x10 | 0, 9);
x09 ^= (0, _arx_ts_1.rotl)(x08 + x11 | 0, 13);
x10 ^= (0, _arx_ts_1.rotl)(x09 + x08 | 0, 18);
x12 ^= (0, _arx_ts_1.rotl)(x15 + x14 | 0, 7);
x13 ^= (0, _arx_ts_1.rotl)(x12 + x15 | 0, 9);
x14 ^= (0, _arx_ts_1.rotl)(x13 + x12 | 0, 13);
x15 ^= (0, _arx_ts_1.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 hashing function, used primarily in xsalsa, to hash
* key and nonce into key' and nonce'.
* Same as salsaCore, but there doesn't seem to be a way to move the block
* out without 25% performance hit.
*/
// prettier-ignore
function hsalsa(s, k, i, o32) {
let x00 = s[0], x01 = k[0], x02 = k[1], x03 = k[2], x04 = k[3], x05 = s[1], x06 = i[0], x07 = i[1], x08 = i[2], x09 = i[3], x10 = s[2], x11 = k[4], x12 = k[5], x13 = k[6], x14 = k[7], x15 = s[3];
for (let r = 0; r < 20; r += 2) {
x04 ^= (0, _arx_ts_1.rotl)(x00 + x12 | 0, 7);
x08 ^= (0, _arx_ts_1.rotl)(x04 + x00 | 0, 9);
x12 ^= (0, _arx_ts_1.rotl)(x08 + x04 | 0, 13);
x00 ^= (0, _arx_ts_1.rotl)(x12 + x08 | 0, 18);
x09 ^= (0, _arx_ts_1.rotl)(x05 + x01 | 0, 7);
x13 ^= (0, _arx_ts_1.rotl)(x09 + x05 | 0, 9);
x01 ^= (0, _arx_ts_1.rotl)(x13 + x09 | 0, 13);
x05 ^= (0, _arx_ts_1.rotl)(x01 + x13 | 0, 18);
x14 ^= (0, _arx_ts_1.rotl)(x10 + x06 | 0, 7);
x02 ^= (0, _arx_ts_1.rotl)(x14 + x10 | 0, 9);
x06 ^= (0, _arx_ts_1.rotl)(x02 + x14 | 0, 13);
x10 ^= (0, _arx_ts_1.rotl)(x06 + x02 | 0, 18);
x03 ^= (0, _arx_ts_1.rotl)(x15 + x11 | 0, 7);
x07 ^= (0, _arx_ts_1.rotl)(x03 + x15 | 0, 9);
x11 ^= (0, _arx_ts_1.rotl)(x07 + x03 | 0, 13);
x15 ^= (0, _arx_ts_1.rotl)(x11 + x07 | 0, 18);
x01 ^= (0, _arx_ts_1.rotl)(x00 + x03 | 0, 7);
x02 ^= (0, _arx_ts_1.rotl)(x01 + x00 | 0, 9);
x03 ^= (0, _arx_ts_1.rotl)(x02 + x01 | 0, 13);
x00 ^= (0, _arx_ts_1.rotl)(x03 + x02 | 0, 18);
x06 ^= (0, _arx_ts_1.rotl)(x05 + x04 | 0, 7);
x07 ^= (0, _arx_ts_1.rotl)(x06 + x05 | 0, 9);
x04 ^= (0, _arx_ts_1.rotl)(x07 + x06 | 0, 13);
x05 ^= (0, _arx_ts_1.rotl)(x04 + x07 | 0, 18);
x11 ^= (0, _arx_ts_1.rotl)(x10 + x09 | 0, 7);
x08 ^= (0, _arx_ts_1.rotl)(x11 + x10 | 0, 9);
x09 ^= (0, _arx_ts_1.rotl)(x08 + x11 | 0, 13);
x10 ^= (0, _arx_ts_1.rotl)(x09 + x08 | 0, 18);
x12 ^= (0, _arx_ts_1.rotl)(x15 + x14 | 0, 7);
x13 ^= (0, _arx_ts_1.rotl)(x12 + x15 | 0, 9);
x14 ^= (0, _arx_ts_1.rotl)(x13 + x12 | 0, 13);
x15 ^= (0, _arx_ts_1.rotl)(x14 + x13 | 0, 18);
}
let oi = 0;
o32[oi++] = x00;
o32[oi++] = x05;
o32[oi++] = x10;
o32[oi++] = x15;
o32[oi++] = x06;
o32[oi++] = x07;
o32[oi++] = x08;
o32[oi++] = x09;
}
/**
* Salsa20 from original paper.
* Unsafe to use random nonces under the same key, due to collision chance.
* Prefer XSalsa instead.
*/
exports.salsa20 = (0, _arx_ts_1.createCipher)(salsaCore, {
allowShortKeys: true,
counterRight: true,
});
/**
* xsalsa20 eXtended-nonce salsa.
* Can be safely used with random 24-byte nonces (CSPRNG).
*/
exports.xsalsa20 = (0, _arx_ts_1.createCipher)(salsaCore, {
counterRight: true,
extendNonceFn: hsalsa,
});
/**
* xsalsa20-poly1305 eXtended-nonce salsa.
* Can be safely used with random 24-byte nonces (CSPRNG).
* Also known as secretbox from libsodium / nacl.
*/
exports.xsalsa20poly1305 = (0, utils_ts_1.wrapCipher)({ blockSize: 64, nonceLength: 24, tagLength: 16 }, (key, nonce) => {
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.
output = (0, utils_ts_1.getOutput)(plaintext.length + 32, output, false); // need 32 additional bytes, see above
const authKey = output.subarray(0, 32); // output[0..32] = poly1305 auth key
const ciphPlaintext = output.subarray(32); // output[32..] = plaintext, then ciphertext
output.set(plaintext, 32);
(0, utils_ts_1.clean)(authKey); // authKey is produced by xoring with zeros
(0, exports.xsalsa20)(key, nonce, output, output); // output = stream ^ output; authKey = stream ^ zeros(32)
const tag = (0, _poly1305_ts_1.poly1305)(ciphPlaintext, authKey); // calculate tag over ciphertext
output.set(tag, 16); // output[16..32] = tag
(0, utils_ts_1.clean)(output.subarray(0, 16), tag); // clean-up authKey remnants & copy of tag
return output.subarray(16); // return output[16..]
},
decrypt(ciphertext, output) {
// tmp part passed tag ciphertext
// [0..32] [32..48] [48..]
(0, utils_ts_1.abytes)(ciphertext);
output = (0, utils_ts_1.getOutput)(ciphertext.length + 32, output, false);
const tmp = output.subarray(0, 32); // output[0..32] is used to calc authKey
const passedTag = output.subarray(32, 48); // output[32..48] = passed tag
const ciphPlaintext = output.subarray(48); // output[48..] = ciphertext, then plaintext
output.set(ciphertext, 32); // copy ciphertext into output
(0, utils_ts_1.clean)(tmp); // authKey is produced by xoring with zeros
const authKey = (0, exports.xsalsa20)(key, nonce, tmp, tmp); // authKey = stream ^ zeros(32)
const tag = (0, _poly1305_ts_1.poly1305)(ciphPlaintext, authKey); // calculate tag over ciphertext
if (!(0, utils_ts_1.equalBytes)(passedTag, tag))
throw new Error('invalid tag');
(0, exports.xsalsa20)(key, nonce, output.subarray(16), output.subarray(16)); // output = stream ^ output[16..]
(0, utils_ts_1.clean)(tmp, passedTag, tag);
return ciphPlaintext; // return output[48..], skipping zeroized output[0..48]
},
};
});
/**
* Alias to `xsalsa20poly1305`, for compatibility with libsodium / nacl
*/
function secretbox(key, nonce) {
const xs = (0, exports.xsalsa20poly1305)(key, nonce);
return { seal: xs.encrypt, open: xs.decrypt };
}
//# sourceMappingURL=salsa.js.map
File diff suppressed because one or more lines are too long
+224
View File
@@ -0,0 +1,224 @@
/**
* 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) | ctr(2) | s[2] | k(4) | s[3]
chacha: s(4) | k(8) | ctr(1) | nonce(3)
chacha20orig: s(4) | k(8) | ctr(2) | nonce(2)
- Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)`
- Caveat: we can't re-use counter array
xchacha [^2] uses the subkey and remaining 8 byte nonce with ChaCha20 as normal
(prefixed by 4 NUL bytes, since [RFC8439] specifies a 12-byte nonce).
[^1]: https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/
[^2]: https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2
* @module
*/
// prettier-ignore
import {
type XorStream, abool, abytes, anumber, checkOpts, clean, copyBytes, u32
} from './utils.ts';
// We can't make top-level var depend on utils.utf8ToBytes
// because it's not present in all envs. Creating a similar fn here
const _utf8ToBytes = (str: string) => Uint8Array.from(str.split('').map((c) => c.charCodeAt(0)));
const sigma16 = _utf8ToBytes('expand 16-byte k');
const sigma32 = _utf8ToBytes('expand 32-byte k');
const sigma16_32 = u32(sigma16);
const sigma32_32 = u32(sigma32);
export function rotl(a: number, b: number): number {
return (a << b) | (a >>> (32 - b));
}
/** Ciphers must use u32 for efficiency. */
export type CipherCoreFn = (
sigma: Uint32Array,
key: Uint32Array,
nonce: Uint32Array,
output: Uint32Array,
counter: number,
rounds?: number
) => void;
/** Method which extends key + short nonce into larger nonce / diff key. */
export type ExtendNonceFn = (
sigma: Uint32Array,
key: Uint32Array,
input: Uint32Array,
output: Uint32Array
) => void;
/** ARX cipher options.
* * `allowShortKeys` for 16-byte keys
* * `counterLength` in bytes
* * `counterRight`: right: `nonce|counter`; left: `counter|nonce`
* */
export type CipherOpts = {
allowShortKeys?: boolean; // Original salsa / chacha allow 16-byte keys
extendNonceFn?: ExtendNonceFn;
counterLength?: number;
counterRight?: boolean;
rounds?: number;
};
// Is byte array aligned to 4 byte offset (u32)?
function isAligned32(b: Uint8Array) {
return b.byteOffset % 4 === 0;
}
// Salsa and Chacha block length is always 512-bit
const BLOCK_LEN = 64;
const BLOCK_LEN32 = 16;
// new Uint32Array([2**32]) // => Uint32Array(1) [ 0 ]
// new Uint32Array([2**32-1]) // => Uint32Array(1) [ 4294967295 ]
const MAX_COUNTER = 2 ** 32 - 1;
const U32_EMPTY = new Uint32Array();
function runCipher(
core: CipherCoreFn,
sigma: Uint32Array,
key: Uint32Array,
nonce: Uint32Array,
data: Uint8Array,
output: 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 = isAligned32(data) && isAligned32(output);
const d32 = isAligned ? u32(data) : U32_EMPTY;
const o32 = isAligned ? u32(output) : U32_EMPTY;
for (let pos = 0; pos < len; counter++) {
core(sigma, key, nonce, b32, counter, rounds);
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 ARX-like (ChaCha, Salsa) cipher stream from core function. */
export function createCipher(core: CipherCoreFn, opts: CipherOpts): 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: Uint8Array,
nonce: Uint8Array,
data: Uint8Array,
output?: Uint8Array,
counter = 0
): Uint8Array => {
abytes(key);
abytes(nonce);
abytes(data);
const len = data.length;
if (output === undefined) output = new Uint8Array(len);
abytes(output);
anumber(counter);
if (counter < 0 || counter >= MAX_COUNTER) throw new Error('arx: counter overflow');
if (output.length < len)
throw new Error(`arx: output (${output.length}) is shorter than data (${len})`);
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) {
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 {
throw new Error(`arx: invalid 32-byte key, 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)
// Align nonce to 4 bytes
if (!isAligned32(nonce)) toClean.push((nonce = copyBytes(nonce)));
const k32 = u32(k);
// hsalsa & hchacha: handle extended nonce
if (extendNonceFn) {
if (nonce.length !== 24) throw new Error(`arx: extended nonce must be 24 bytes`);
extendNonceFn(sigma, k32, u32(nonce.subarray(0, 16)), k32);
nonce = nonce.subarray(16);
}
// Handle nonce counter
const nonceNcLen = 16 - counterLength;
if (nonceNcLen !== nonce.length)
throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);
// Pad counter when nonce is 64 bit
if (nonceNcLen !== 12) {
const nc = new Uint8Array(12);
nc.set(nonce, counterRight ? 0 : 12 - nonce.length);
nonce = nc;
toClean.push(nonce);
}
const n32 = u32(nonce);
runCipher(core, sigma, k32, n32, data, output, counter, rounds);
clean(...toClean);
return output;
};
}
+25
View File
@@ -0,0 +1,25 @@
/**
* Internal assertion helpers.
* @module
* @deprecated
*/
import {
abytes as ab,
abool as abool_,
aexists as ae,
anumber as an,
aoutput as ao,
type IHash as H,
} from './utils.ts';
/** @deprecated Use import from `noble/hashes/utils` module */
export const abool: typeof abool_ = abool_;
/** @deprecated Use import from `noble/hashes/utils` module */
export const abytes: typeof ab = ab;
/** @deprecated Use import from `noble/hashes/utils` module */
export const aexists: typeof ae = ae;
/** @deprecated Use import from `noble/hashes/utils` module */
export const anumber: typeof an = an;
/** @deprecated Use import from `noble/hashes/utils` module */
export const aoutput: typeof ao = ao;
/** @deprecated Use import from `noble/hashes/utils` module */
export type Hash = H;
+311
View File
@@ -0,0 +1,311 @@
/**
* noble-ciphers-micro: more auditable, but 4x slower version of salsa20, chacha & poly1305.
* Implements the same algorithms that are present in other files, but without
* unrolled loops (https://en.wikipedia.org/wiki/Loop_unrolling).
* @module
*/
/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
// prettier-ignore
import { createCipher, rotl } from './_arx.ts';
import {
type Cipher,
type XorStream,
abytes,
bytesToHex,
concatBytes,
equalBytes,
hexToNumber,
numberToBytesBE,
u64Lengths,
wrapCipher,
} from './utils.ts';
export type ARXCipherN = ((key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array) => Cipher) & {
blockSize: number;
nonceLength: number;
tagLength: number;
};
function bytesToNumberLE(bytes: Uint8Array): bigint {
abytes(bytes);
return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
}
function numberToBytesLE(n: number | bigint, len: number): Uint8Array {
return numberToBytesBE(n, len).reverse();
}
function salsaQR(x: 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);
}
// prettier-ignore
function chachaQR(x: 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);
}
function salsaRound(x: 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);
}
}
function chachaRound(x: Uint32Array, rounds = 20) {
for (let r = 0; r < rounds; r += 2) {
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);
}
}
function salsaCore(
s: Uint32Array,
k: Uint32Array,
n: Uint32Array,
out: Uint32Array,
cnt: number,
rounds = 20
): void {
// prettier-ignore
const y = new Uint32Array([
s[0], k[0], k[1], k[2], // "expa" Key Key Key
k[3], s[1], n[0], n[1], // Key "nd 3" Nonce Nonce
cnt, 0, s[2], k[4], // Pos. Pos. "2-by" Key
k[5], k[6], k[7], s[3], // Key Key Key "te k"
]);
const x = y.slice();
salsaRound(x, rounds);
for (let i = 0; i < 16; i++) out[i] = (y[i] + x[i]) | 0;
}
/** hsalsa hashes key and nonce into key' and nonce'. */
// prettier-ignore
export function hsalsa(s: Uint32Array, k: Uint32Array, i: Uint32Array, o32: Uint32Array): void {
const x = new Uint32Array([
s[0], k[0], k[1], k[2],
k[3], s[1], i[0], i[1],
i[2], i[3], s[2], k[4],
k[5], k[6], k[7], s[3]
]);
salsaRound(x, 20);
let oi = 0;
o32[oi++] = x[0]; o32[oi++] = x[5];
o32[oi++] = x[10]; o32[oi++] = x[15];
o32[oi++] = x[6]; o32[oi++] = x[7];
o32[oi++] = x[8]; o32[oi++] = x[9];
}
function chachaCore(
s: Uint32Array,
k: Uint32Array,
n: Uint32Array,
out: Uint32Array,
cnt: number,
rounds = 20
): void {
// prettier-ignore
const y = new Uint32Array([
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
cnt, n[0], n[1], n[2], // Counter Counter Nonce Nonce
]);
const x = y.slice();
chachaRound(x, rounds);
for (let i = 0; i < 16; i++) out[i] = (y[i] + x[i]) | 0;
}
/** hchacha hashes key and nonce into key' and nonce'. */
// prettier-ignore
export function hchacha(s: Uint32Array, k: Uint32Array, i: Uint32Array, o32: Uint32Array): void {
const x = new Uint32Array([
s[0], s[1], s[2], s[3],
k[0], k[1], k[2], k[3],
k[4], k[5], k[6], k[7],
i[0], i[1], i[2], i[3],
]);
chachaRound(x, 20);
let oi = 0;
o32[oi++] = x[0]; o32[oi++] = x[1];
o32[oi++] = x[2]; o32[oi++] = x[3];
o32[oi++] = x[12]; o32[oi++] = x[13];
o32[oi++] = x[14]; o32[oi++] = x[15];
}
/** salsa20, 12-byte nonce. */
export const salsa20: XorStream = /* @__PURE__ */ createCipher(salsaCore, {
allowShortKeys: true,
counterRight: true,
});
/** xsalsa20, 24-byte nonce. */
export const xsalsa20: XorStream = /* @__PURE__ */ createCipher(salsaCore, {
counterRight: true,
extendNonceFn: hsalsa,
});
/** chacha20 non-RFC, original version by djb. 8-byte nonce, 8-byte counter. */
export const chacha20orig: XorStream = /* @__PURE__ */ createCipher(chachaCore, {
allowShortKeys: true,
counterRight: false,
counterLength: 8,
});
/** chacha20 RFC 8439 (IETF / TLS). 12-byte nonce, 4-byte counter. */
export const chacha20: XorStream = /* @__PURE__ */ createCipher(chachaCore, {
counterRight: false,
counterLength: 4,
});
/** xchacha20 eXtended-nonce. https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha */
export const xchacha20: XorStream = /* @__PURE__ */ createCipher(chachaCore, {
counterRight: false,
counterLength: 8,
extendNonceFn: hchacha,
});
/** 8-round chacha from the original paper. */
export const chacha8: XorStream = /* @__PURE__ */ createCipher(chachaCore, {
counterRight: false,
counterLength: 4,
rounds: 8,
});
/** 12-round chacha from the original paper. */
export const chacha12: XorStream = /* @__PURE__ */ createCipher(chachaCore, {
counterRight: false,
counterLength: 4,
rounds: 12,
});
const POW_2_130_5 = BigInt(2) ** BigInt(130) - BigInt(5);
const POW_2_128_1 = BigInt(2) ** BigInt(16 * 8) - BigInt(1);
const CLAMP_R = BigInt('0x0ffffffc0ffffffc0ffffffc0fffffff');
const _0 = BigInt(0);
const _1 = BigInt(1);
/** Poly1305 polynomial MAC. Can be speed-up using BigUint64Array, at the cost of complexity. */
export function poly1305(msg: Uint8Array, key: Uint8Array): Uint8Array {
abytes(msg);
abytes(key, 32);
let acc = _0;
const r = bytesToNumberLE(key.subarray(0, 16)) & CLAMP_R;
const s = bytesToNumberLE(key.subarray(16));
// Process by 16 byte chunks
for (let i = 0; i < msg.length; i += 16) {
const m = msg.subarray(i, i + 16);
const n = bytesToNumberLE(m) | (_1 << BigInt(8 * m.length));
acc = ((acc + n) * r) % POW_2_130_5;
}
const res = (acc + s) & POW_2_128_1;
return numberToBytesLE(res, 16);
}
function computeTag(
fn: XorStream,
key: Uint8Array,
nonce: Uint8Array,
ciphertext: Uint8Array,
AAD?: Uint8Array
): Uint8Array {
const res = [];
if (AAD) {
res.push(AAD);
const leftover = AAD.length % 16;
if (leftover > 0) res.push(new Uint8Array(16 - leftover));
}
res.push(ciphertext);
const leftover = ciphertext.length % 16;
if (leftover > 0) res.push(new Uint8Array(16 - leftover));
res.push(u64Lengths(ciphertext.length, AAD ? AAD.length : 0, true));
const authKey = fn(key, nonce, new Uint8Array(32));
return poly1305(concatBytes(...res), authKey);
}
/** xsalsa20-poly1305 eXtended-nonce (24 bytes) salsa. */
export const xsalsa20poly1305: ARXCipherN = /* @__PURE__ */ wrapCipher(
{ blockSize: 64, nonceLength: 24, tagLength: 16 },
function xsalsapoly(key: Uint8Array, nonce: Uint8Array) {
return {
encrypt(plaintext: Uint8Array) {
const m = concatBytes(new Uint8Array(32), plaintext);
const c = xsalsa20(key, nonce, m);
const authKey = c.subarray(0, 32);
const data = c.subarray(32);
const tag = poly1305(data, authKey);
return concatBytes(tag, data);
},
decrypt(ciphertext: Uint8Array) {
const c = concatBytes(new Uint8Array(16), ciphertext);
const passedTag = c.subarray(16, 32);
const authKey = xsalsa20(key, nonce, new Uint8Array(32));
const tag = poly1305(c.subarray(32), authKey);
if (!equalBytes(tag, passedTag)) throw new Error('invalid poly1305 tag');
return xsalsa20(key, nonce, c).subarray(32);
},
};
}
);
/** Alias to `xsalsa20poly1305`. */
export function secretbox(
key: Uint8Array,
nonce: Uint8Array
): {
seal: (plaintext: Uint8Array) => Uint8Array;
open: (ciphertext: Uint8Array) => Uint8Array;
} {
const xs = xsalsa20poly1305(key, nonce);
return { seal: xs.encrypt, open: xs.decrypt };
}
export const _poly1305_aead =
(fn: XorStream) =>
(key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array): Cipher => {
const tagLength = 16;
return {
encrypt(plaintext: Uint8Array) {
const data = fn(key, nonce, plaintext, undefined, 1); // stream from i=1
const tag = computeTag(fn, key, nonce, data, AAD);
return concatBytes(data, tag);
},
decrypt(ciphertext: Uint8Array) {
const passedTag = ciphertext.subarray(-tagLength);
const data = ciphertext.subarray(0, -tagLength);
const tag = computeTag(fn, key, nonce, data, AAD);
if (!equalBytes(tag, passedTag)) throw new Error('invalid poly1305 tag');
return fn(key, nonce, data, undefined, 1); // stream from i=1
},
};
};
/** chacha20-poly1305 12-byte-nonce chacha. */
export const chacha20poly1305: ARXCipherN = /* @__PURE__ */ wrapCipher(
{ blockSize: 64, nonceLength: 12, tagLength: 16 },
_poly1305_aead(chacha20)
);
/**
* XChaCha20-Poly1305 extended-nonce chacha. Can be safely used with random nonces (CSPRNG).
*/
export const xchacha20poly1305: ARXCipherN = /* @__PURE__ */ wrapCipher(
{ blockSize: 64, nonceLength: 24, tagLength: 16 },
_poly1305_aead(xchacha20)
);
+305
View File
@@ -0,0 +1,305 @@
/**
* Poly1305 ([PDF](https://cr.yp.to/mac/poly1305-20050329.pdf),
* [wiki](https://en.wikipedia.org/wiki/Poly1305))
* is a fast and parallel secret-key message-authentication code suitable for
* a wide variety of applications. It was standardized in
* [RFC 8439](https://datatracker.ietf.org/doc/html/rfc8439) 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 [invisible salamanders attack](https://keymaterial.net/2020/09/07/invisible-salamanders-in-aes-gcm-siv/).
* 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 [original website](https://cr.yp.to/mac.html).
* @module
*/
import { Hash, type Input, abytes, aexists, aoutput, clean, toBytes } from './utils.ts';
// Based on Public Domain poly1305-donna https://github.com/floodyberry/poly1305-donna
const u8to16 = (a: Uint8Array, i: number) => (a[i++] & 0xff) | ((a[i++] & 0xff) << 8);
class Poly1305 implements Hash<Poly1305> {
readonly blockLen = 16;
readonly outputLen = 16;
private buffer = new Uint8Array(16);
private r = new Uint16Array(10);
private h = new Uint16Array(10);
private pad = new Uint16Array(8);
private pos = 0;
protected finished = false;
constructor(key: Input) {
key = toBytes(key);
abytes(key, 32);
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);
// https://github.com/floodyberry/poly1305-donna/blob/e6ad6e091d30d7f4ec2d4f978be1fcfcbce72781/poly1305-donna-16.h#L47
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: Uint8Array, offset: number, isLast = false) {
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;
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: Input): this {
aexists(this);
data = toBytes(data);
abytes(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() {
clean(this.h, this.r, this.buffer, this.pad);
}
digestInto(out: Uint8Array) {
aexists(this);
aoutput(out, this);
this.finished = true;
const { buffer, h } = this;
let { pos } = this;
if (pos) {
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;
}
return out;
}
digest(): Uint8Array {
const { buffer, outputLen } = this;
this.digestInto(buffer);
const res = buffer.slice(0, outputLen);
this.destroy();
return res;
}
}
export type CHash = ReturnType<typeof wrapConstructorWithKey>;
export function wrapConstructorWithKey<H extends Hash<H>>(
hashCons: (key: Input) => Hash<H>
): {
(msg: Input, key: Input): Uint8Array;
outputLen: number;
blockLen: number;
create(key: Input): Hash<H>;
} {
const hashC = (msg: Input, key: Input): Uint8Array => hashCons(key).update(toBytes(msg)).digest();
const tmp = hashCons(new Uint8Array(32));
hashC.outputLen = tmp.outputLen;
hashC.blockLen = tmp.blockLen;
hashC.create = (key: Input) => hashCons(key);
return hashC;
}
/** Poly1305 MAC from RFC 8439. */
export const poly1305: CHash = wrapConstructorWithKey((key) => new Poly1305(key));
+267
View File
@@ -0,0 +1,267 @@
/**
* 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
* [NIST SP800-38d](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf),
* SIV from
* [RFC 8452](https://datatracker.ietf.org/doc/html/rfc8452).
*
* GHASH modulo: x^128 + x^7 + x^2 + x + 1
* POLYVAL modulo: x^128 + x^127 + x^126 + x^121 + 1
*
* @module
*/
// prettier-ignore
import {
abytes, aexists, aoutput,
clean, copyBytes, createView, Hash, type Input, toBytes, u32,
} from './utils.ts';
const BLOCK_SIZE = 16;
// TODO: rewrite
// temporary padding buffer
const ZEROS16 = /* @__PURE__ */ new Uint8Array(16);
const ZEROS32 = u32(ZEROS16);
const POLY = 0xe1; // v = 2*v % POLY
// v = 2*v % POLY
// NOTE: because x + x = 0 (add/sub is same), mul2(x) != x+x
// We can multiply any number using montgomery ladder and this function (works as double, add is 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),
s0: (s0 >>> 1) ^ ((POLY << 24) & -(hiBit & 1)), // reduce % poly
};
};
const swapLE = (n: number) =>
(((n >>> 0) & 0xff) << 24) |
(((n >>> 8) & 0xff) << 16) |
(((n >>> 16) & 0xff) << 8) |
((n >>> 24) & 0xff) |
0;
/**
* `mulX_POLYVAL(ByteReverse(H))` from spec
* @param k mutated in place
*/
export function _toGHASHKey(k: Uint8Array): Uint8Array {
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;
}
type Value = { s0: number; s1: number; s2: number; s3: number };
const estimateWindow = (bytes: number) => {
if (bytes > 64 * 1024) return 8;
if (bytes > 1024) return 4;
return 2;
};
class GHASH implements Hash<GHASH> {
readonly blockLen = BLOCK_SIZE;
readonly outputLen = BLOCK_SIZE;
protected s0 = 0;
protected s1 = 0;
protected s2 = 0;
protected s3 = 0;
protected finished = false;
protected t: Value[];
private W: number;
private windowSize: number;
// We select bits per window adaptively based on expectedLength
constructor(key: Input, expectedLength?: number) {
key = toBytes(key);
abytes(key, 16);
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) {
(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;
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: Input): this {
aexists(this);
data = toBytes(data);
abytes(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(b32[i * 4 + 0], b32[i * 4 + 1], b32[i * 4 + 2], b32[i * 4 + 3]);
}
if (left) {
ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));
this._updateBlock(ZEROS32[0], ZEROS32[1], ZEROS32[2], ZEROS32[3]);
clean(ZEROS32); // clean tmp buffer
}
return this;
}
destroy() {
const { t } = this;
// clean precompute table
for (const elm of t) {
(elm.s0 = 0), (elm.s1 = 0), (elm.s2 = 0), (elm.s3 = 0);
}
}
digestInto(out: Uint8Array) {
aexists(this);
aoutput(out, this);
this.finished = true;
const { s0, s1, s2, s3 } = this;
const o32 = u32(out);
o32[0] = s0;
o32[1] = s1;
o32[2] = s2;
o32[3] = s3;
return out;
}
digest(): Uint8Array {
const res = new Uint8Array(BLOCK_SIZE);
this.digestInto(res);
this.destroy();
return res;
}
}
class Polyval extends GHASH {
constructor(key: Input, expectedLength?: number) {
key = toBytes(key);
abytes(key);
const ghKey = _toGHASHKey(copyBytes(key));
super(ghKey, expectedLength);
clean(ghKey);
}
update(data: Input): this {
data = toBytes(data);
aexists(this);
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++) {
this._updateBlock(
swapLE(b32[i * 4 + 3]),
swapLE(b32[i * 4 + 2]),
swapLE(b32[i * 4 + 1]),
swapLE(b32[i * 4 + 0])
);
}
if (left) {
ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));
this._updateBlock(
swapLE(ZEROS32[3]),
swapLE(ZEROS32[2]),
swapLE(ZEROS32[1]),
swapLE(ZEROS32[0])
);
clean(ZEROS32);
}
return this;
}
digestInto(out: Uint8Array) {
aexists(this);
aoutput(out, this);
this.finished = true;
// tmp ugly hack
const { s0, s1, s2, s3 } = this;
const o32 = u32(out);
o32[0] = s0;
o32[1] = s1;
o32[2] = s2;
o32[3] = s3;
return out.reverse();
}
}
export type CHashPV = ReturnType<typeof wrapConstructorWithKey>;
function wrapConstructorWithKey<H extends Hash<H>>(
hashCons: (key: Input, expectedLength?: number) => Hash<H>
): {
(msg: Input, key: Input): Uint8Array;
outputLen: number;
blockLen: number;
create(key: Input, expectedLength?: number): Hash<H>;
} {
const hashC = (msg: Input, key: Input): Uint8Array =>
hashCons(key, msg.length).update(toBytes(msg)).digest();
const tmp = hashCons(new Uint8Array(16), 0);
hashC.outputLen = tmp.outputLen;
hashC.blockLen = tmp.blockLen;
hashC.create = (key: Input, expectedLength?: number) => hashCons(key, expectedLength);
return hashC;
}
/** GHash MAC for AES-GCM. */
export const ghash: CHashPV = wrapConstructorWithKey(
(key, expectedLength) => new GHASH(key, expectedLength)
);
/** Polyval MAC for AES-SIV. */
export const polyval: CHashPV = wrapConstructorWithKey(
(key, expectedLength) => new Polyval(key, expectedLength)
);
+1016
View File
@@ -0,0 +1,1016 @@
/**
* [AES](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard)
* a.k.a. Advanced Encryption Standard
* is a variant of Rijndael block cipher, standardized by NIST in 2001.
* We provide the fastest available pure JS implementation.
*
* Data is split into 128-bit blocks. Encrypted in 10/12/14 rounds (128/192/256 bits). In every round:
* 1. **S-box**, table substitution
* 2. **Shift rows**, cyclic shift left of all rows of data array
* 3. **Mix columns**, multiplying every column by fixed polynomial
* 4. **Add round key**, round_key xor i-th column of array
*
* Check out [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)
* @module
*/
import { ghash, polyval } from './_polyval.ts';
// prettier-ignore
import {
abytes, clean, complexOverlapBytes, concatBytes,
copyBytes, createView, equalBytes, getOutput, isAligned32, overlapBytes,
setBigUint64, u32, u64Lengths, u8, wrapCipher,
type Cipher, type CipherWithOutput,
} from './utils.ts';
const BLOCK_SIZE = 16;
const BLOCK_SIZE32 = 4;
const EMPTY_BLOCK = /* @__PURE__ */ new Uint8Array(BLOCK_SIZE);
const POLY = 0x11b; // 1 + x + x**3 + x**4 + x**8
// TODO: remove multiplication, binary ops only
function mul2(n: number) {
return (n << 1) ^ (POLY & -(n >> 7));
}
function mul(a: number, b: number) {
let res = 0;
for (; b > 0; b >>= 1) {
// Montgomery ladder
res ^= a & -(b & 1); // if (b&1) res ^=a (but const-time).
a = mul2(a); // a = 2*a
}
return res;
}
// AES S-box is generated using finite field inversion,
// an affine transform, and xor of a constant 0x63.
const sbox = /* @__PURE__ */ (() => {
const t = new Uint8Array(256);
for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x)) t[i] = x;
const box = new Uint8Array(256);
box[0] = 0x63; // first elm
for (let i = 0; i < 255; i++) {
let x = t[255 - i];
x |= x << 8;
box[t[i]] = (x ^ (x >> 4) ^ (x >> 5) ^ (x >> 6) ^ (x >> 7) ^ 0x63) & 0xff;
}
clean(t);
return box;
})();
// Inverted S-box
const invSbox = /* @__PURE__ */ sbox.map((_, j) => sbox.indexOf(j));
// Rotate u32 by 8
const rotr32_8 = (n: number) => (n << 24) | (n >>> 8);
const rotl32_8 = (n: number) => (n << 8) | (n >>> 24);
// The byte swap operation for uint32 (LE<->BE)
const byteSwap = (word: number) =>
((word << 24) & 0xff000000) |
((word << 8) & 0xff0000) |
((word >>> 8) & 0xff00) |
((word >>> 24) & 0xff);
// T-table is optimization suggested in 5.2 of original proposal (missed from FIPS-197). Changes:
// - LE instead of BE
// - bigger tables: T0 and T1 are merged into T01 table and T2 & T3 into T23;
// so index is u16, instead of u8. This speeds up things, unexpectedly
function genTtable(sbox: Uint8Array, fn: (n: number) => number) {
if (sbox.length !== 256) throw new Error('Wrong sbox length');
const T0 = new Uint32Array(256).map((_, j) => fn(sbox[j]));
const T1 = T0.map(rotl32_8);
const T2 = T1.map(rotl32_8);
const T3 = T2.map(rotl32_8);
const T01 = new Uint32Array(256 * 256);
const T23 = new Uint32Array(256 * 256);
const sbox2 = new Uint16Array(256 * 256);
for (let i = 0; i < 256; i++) {
for (let j = 0; j < 256; j++) {
const idx = i * 256 + j;
T01[idx] = T0[i] ^ T1[j];
T23[idx] = T2[i] ^ T3[j];
sbox2[idx] = (sbox[i] << 8) | sbox[j];
}
}
return { sbox, sbox2, T0, T1, T2, T3, T01, T23 };
}
const tableEncoding = /* @__PURE__ */ genTtable(
sbox,
(s: number) => (mul(s, 3) << 24) | (s << 16) | (s << 8) | mul(s, 2)
);
const tableDecoding = /* @__PURE__ */ genTtable(
invSbox,
(s) => (mul(s, 11) << 24) | (mul(s, 13) << 16) | (mul(s, 9) << 8) | mul(s, 14)
);
const xPowers = /* @__PURE__ */ (() => {
const p = new Uint8Array(16);
for (let i = 0, x = 1; i < 16; i++, x = mul2(x)) p[i] = x;
return p;
})();
/** Key expansion used in CTR. */
function expandKeyLE(key: Uint8Array): Uint32Array {
abytes(key);
const len = key.length;
if (![16, 24, 32].includes(len))
throw new Error('aes: invalid key size, should be 16, 24 or 32, got ' + len);
const { sbox2 } = tableEncoding;
const toClean = [];
if (!isAligned32(key)) toClean.push((key = copyBytes(key)));
const k32 = u32(key);
const Nk = k32.length;
const subByte = (n: number) => applySbox(sbox2, n, n, n, n);
const xk = new Uint32Array(len + 28); // expanded key
xk.set(k32);
// 4.3.1 Key expansion
for (let i = Nk; i < xk.length; i++) {
let t = xk[i - 1];
if (i % Nk === 0) t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1];
else if (Nk > 6 && i % Nk === 4) t = subByte(t);
xk[i] = xk[i - Nk] ^ t;
}
clean(...toClean);
return xk;
}
function expandKeyDecLE(key: Uint8Array): Uint32Array {
const encKey = expandKeyLE(key);
const xk = encKey.slice();
const Nk = encKey.length;
const { sbox2 } = tableEncoding;
const { T0, T1, T2, T3 } = tableDecoding;
// Inverse key by chunks of 4 (rounds)
for (let i = 0; i < Nk; i += 4) {
for (let j = 0; j < 4; j++) xk[i + j] = encKey[Nk - i - 4 + j];
}
clean(encKey);
// apply InvMixColumn except first & last round
for (let i = 4; i < Nk - 4; i++) {
const x = xk[i];
const w = applySbox(sbox2, x, x, x, x);
xk[i] = T0[w & 0xff] ^ T1[(w >>> 8) & 0xff] ^ T2[(w >>> 16) & 0xff] ^ T3[w >>> 24];
}
return xk;
}
// Apply tables
function apply0123(
T01: Uint32Array,
T23: Uint32Array,
s0: number,
s1: number,
s2: number,
s3: number
) {
return (
T01[((s0 << 8) & 0xff00) | ((s1 >>> 8) & 0xff)] ^
T23[((s2 >>> 8) & 0xff00) | ((s3 >>> 24) & 0xff)]
);
}
function applySbox(sbox2: Uint16Array, s0: number, s1: number, s2: number, s3: number) {
return (
sbox2[(s0 & 0xff) | (s1 & 0xff00)] |
(sbox2[((s2 >>> 16) & 0xff) | ((s3 >>> 16) & 0xff00)] << 16)
);
}
function encrypt(
xk: Uint32Array,
s0: number,
s1: number,
s2: number,
s3: number
): { s0: number; s1: number; s2: number; s3: number } {
const { sbox2, T01, T23 } = tableEncoding;
let k = 0;
(s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]);
const rounds = xk.length / 4 - 2;
for (let i = 0; i < rounds; i++) {
const t0 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3);
const t1 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0);
const t2 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1);
const t3 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2);
(s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3);
}
// last round (without mixcolumns, so using SBOX2 table)
const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3);
const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0);
const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1);
const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2);
return { s0: t0, s1: t1, s2: t2, s3: t3 };
}
// Can't be merged with encrypt: arg positions for apply0123 / applySbox are different
function decrypt(
xk: Uint32Array,
s0: number,
s1: number,
s2: number,
s3: number
): {
s0: number;
s1: number;
s2: number;
s3: number;
} {
const { sbox2, T01, T23 } = tableDecoding;
let k = 0;
(s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]);
const rounds = xk.length / 4 - 2;
for (let i = 0; i < rounds; i++) {
const t0 = xk[k++] ^ apply0123(T01, T23, s0, s3, s2, s1);
const t1 = xk[k++] ^ apply0123(T01, T23, s1, s0, s3, s2);
const t2 = xk[k++] ^ apply0123(T01, T23, s2, s1, s0, s3);
const t3 = xk[k++] ^ apply0123(T01, T23, s3, s2, s1, s0);
(s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3);
}
// Last round
const t0: number = xk[k++] ^ applySbox(sbox2, s0, s3, s2, s1);
const t1: number = xk[k++] ^ applySbox(sbox2, s1, s0, s3, s2);
const t2: number = xk[k++] ^ applySbox(sbox2, s2, s1, s0, s3);
const t3: number = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0);
return { s0: t0, s1: t1, s2: t2, s3: t3 };
}
// TODO: investigate merging with ctr32
function ctrCounter(
xk: Uint32Array,
nonce: Uint8Array,
src: Uint8Array,
dst?: Uint8Array
): Uint8Array {
abytes(nonce, BLOCK_SIZE);
abytes(src);
const srcLen = src.length;
dst = getOutput(srcLen, dst);
complexOverlapBytes(src, dst);
const ctr = nonce;
const c32 = u32(ctr);
// Fill block (empty, ctr=0)
let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]);
const src32 = u32(src);
const dst32 = u32(dst);
// process blocks
for (let i = 0; i + 4 <= src32.length; i += 4) {
dst32[i + 0] = src32[i + 0] ^ s0;
dst32[i + 1] = src32[i + 1] ^ s1;
dst32[i + 2] = src32[i + 2] ^ s2;
dst32[i + 3] = src32[i + 3] ^ s3;
// Full 128 bit counter with wrap around
let carry = 1;
for (let i = ctr.length - 1; i >= 0; i--) {
carry = (carry + (ctr[i] & 0xff)) | 0;
ctr[i] = carry & 0xff;
carry >>>= 8;
}
({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]));
}
// leftovers (less than block)
// It's possible to handle > u32 fast, but is it worth it?
const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);
if (start < srcLen) {
const b32 = new Uint32Array([s0, s1, s2, s3]);
const buf = u8(b32);
for (let i = start, pos = 0; i < srcLen; i++, pos++) dst[i] = src[i] ^ buf[pos];
clean(b32);
}
return dst;
}
// AES CTR with overflowing 32 bit counter
// It's possible to do 32le significantly simpler (and probably faster) by using u32.
// But, we need both, and perf bottleneck is in ghash anyway.
function ctr32(
xk: Uint32Array,
isLE: boolean,
nonce: Uint8Array,
src: Uint8Array,
dst?: Uint8Array
): Uint8Array {
abytes(nonce, BLOCK_SIZE);
abytes(src);
dst = getOutput(src.length, dst);
const ctr = nonce; // write new value to nonce, so it can be re-used
const c32 = u32(ctr);
const view = createView(ctr);
const src32 = u32(src);
const dst32 = u32(dst);
const ctrPos = isLE ? 0 : 12;
const srcLen = src.length;
// Fill block (empty, ctr=0)
let ctrNum = view.getUint32(ctrPos, isLE); // read current counter value
let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]);
// process blocks
for (let i = 0; i + 4 <= src32.length; i += 4) {
dst32[i + 0] = src32[i + 0] ^ s0;
dst32[i + 1] = src32[i + 1] ^ s1;
dst32[i + 2] = src32[i + 2] ^ s2;
dst32[i + 3] = src32[i + 3] ^ s3;
ctrNum = (ctrNum + 1) >>> 0; // u32 wrap
view.setUint32(ctrPos, ctrNum, isLE);
({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]));
}
// leftovers (less than a block)
const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);
if (start < srcLen) {
const b32 = new Uint32Array([s0, s1, s2, s3]);
const buf = u8(b32);
for (let i = start, pos = 0; i < srcLen; i++, pos++) dst[i] = src[i] ^ buf[pos];
clean(b32);
}
return dst;
}
/**
* CTR: counter mode. Creates stream cipher.
* Requires good IV. Parallelizable. OK, but no MAC.
*/
export const ctr: ((key: Uint8Array, nonce: Uint8Array) => CipherWithOutput) & {
blockSize: number;
nonceLength: number;
} = /* @__PURE__ */ wrapCipher(
{ blockSize: 16, nonceLength: 16 },
function aesctr(key: Uint8Array, nonce: Uint8Array): CipherWithOutput {
function processCtr(buf: Uint8Array, dst?: Uint8Array) {
abytes(buf);
if (dst !== undefined) {
abytes(dst);
if (!isAligned32(dst)) throw new Error('unaligned destination');
}
const xk = expandKeyLE(key);
const n = copyBytes(nonce); // align + avoid changing
const toClean = [xk, n];
if (!isAligned32(buf)) toClean.push((buf = copyBytes(buf)));
const out = ctrCounter(xk, n, buf, dst);
clean(...toClean);
return out;
}
return {
encrypt: (plaintext: Uint8Array, dst?: Uint8Array) => processCtr(plaintext, dst),
decrypt: (ciphertext: Uint8Array, dst?: Uint8Array) => processCtr(ciphertext, dst),
};
}
);
function validateBlockDecrypt(data: Uint8Array) {
abytes(data);
if (data.length % BLOCK_SIZE !== 0) {
throw new Error(
'aes-(cbc/ecb).decrypt ciphertext should consist of blocks with size ' + BLOCK_SIZE
);
}
}
function validateBlockEncrypt(plaintext: Uint8Array, pcks5: boolean, dst?: Uint8Array) {
abytes(plaintext);
let outLen = plaintext.length;
const remaining = outLen % BLOCK_SIZE;
if (!pcks5 && remaining !== 0)
throw new Error('aec/(cbc-ecb): unpadded plaintext with disabled padding');
if (!isAligned32(plaintext)) plaintext = copyBytes(plaintext);
const b = u32(plaintext);
if (pcks5) {
let left = BLOCK_SIZE - remaining;
if (!left) left = BLOCK_SIZE; // if no bytes left, create empty padding block
outLen = outLen + left;
}
dst = getOutput(outLen, dst);
complexOverlapBytes(plaintext, dst);
const o = u32(dst);
return { b, o, out: dst };
}
function validatePCKS(data: Uint8Array, pcks5: boolean) {
if (!pcks5) return data;
const len = data.length;
if (!len) throw new Error('aes/pcks5: empty ciphertext not allowed');
const lastByte = data[len - 1];
if (lastByte <= 0 || lastByte > 16) throw new Error('aes/pcks5: wrong padding');
const out = data.subarray(0, -lastByte);
for (let i = 0; i < lastByte; i++)
if (data[len - i - 1] !== lastByte) throw new Error('aes/pcks5: wrong padding');
return out;
}
function padPCKS(left: Uint8Array) {
const tmp = new Uint8Array(16);
const tmp32 = u32(tmp);
tmp.set(left);
const paddingByte = BLOCK_SIZE - left.length;
for (let i = BLOCK_SIZE - paddingByte; i < BLOCK_SIZE; i++) tmp[i] = paddingByte;
return tmp32;
}
/** Options for ECB and CBC. */
export type BlockOpts = { disablePadding?: boolean };
/**
* ECB: Electronic CodeBook. Simple deterministic replacement.
* Dangerous: always map x to y. See [AES Penguin](https://words.filippo.io/the-ecb-penguin/).
*/
export const ecb: ((key: Uint8Array, opts?: BlockOpts) => CipherWithOutput) & {
blockSize: number;
} = /* @__PURE__ */ wrapCipher(
{ blockSize: 16 },
function aesecb(key: Uint8Array, opts: BlockOpts = {}): CipherWithOutput {
const pcks5 = !opts.disablePadding;
return {
encrypt(plaintext: Uint8Array, dst?: Uint8Array) {
const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst);
const xk = expandKeyLE(key);
let i = 0;
for (; i + 4 <= b.length; ) {
const { s0, s1, s2, s3 } = encrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);
(o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);
}
if (pcks5) {
const tmp32 = padPCKS(plaintext.subarray(i * 4));
const { s0, s1, s2, s3 } = encrypt(xk, tmp32[0], tmp32[1], tmp32[2], tmp32[3]);
(o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);
}
clean(xk);
return _out;
},
decrypt(ciphertext: Uint8Array, dst?: Uint8Array) {
validateBlockDecrypt(ciphertext);
const xk = expandKeyDecLE(key);
dst = getOutput(ciphertext.length, dst);
const toClean: (Uint8Array | Uint32Array)[] = [xk];
if (!isAligned32(ciphertext)) toClean.push((ciphertext = copyBytes(ciphertext)));
complexOverlapBytes(ciphertext, dst);
const b = u32(ciphertext);
const o = u32(dst);
for (let i = 0; i + 4 <= b.length; ) {
const { s0, s1, s2, s3 } = decrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);
(o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);
}
clean(...toClean);
return validatePCKS(dst, pcks5);
},
};
}
);
/**
* CBC: Cipher-Block-Chaining. Key is previous rounds block.
* Fragile: needs proper padding. Unauthenticated: needs MAC.
*/
export const cbc: ((key: Uint8Array, iv: Uint8Array, opts?: BlockOpts) => CipherWithOutput) & {
blockSize: number;
nonceLength: number;
} = /* @__PURE__ */ wrapCipher(
{ blockSize: 16, nonceLength: 16 },
function aescbc(key: Uint8Array, iv: Uint8Array, opts: BlockOpts = {}): CipherWithOutput {
const pcks5 = !opts.disablePadding;
return {
encrypt(plaintext: Uint8Array, dst?: Uint8Array) {
const xk = expandKeyLE(key);
const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst);
let _iv = iv;
const toClean: (Uint8Array | Uint32Array)[] = [xk];
if (!isAligned32(_iv)) toClean.push((_iv = copyBytes(_iv)));
const n32 = u32(_iv);
// prettier-ignore
let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];
let i = 0;
for (; i + 4 <= b.length; ) {
(s0 ^= b[i + 0]), (s1 ^= b[i + 1]), (s2 ^= b[i + 2]), (s3 ^= b[i + 3]);
({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));
(o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);
}
if (pcks5) {
const tmp32 = padPCKS(plaintext.subarray(i * 4));
(s0 ^= tmp32[0]), (s1 ^= tmp32[1]), (s2 ^= tmp32[2]), (s3 ^= tmp32[3]);
({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));
(o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);
}
clean(...toClean);
return _out;
},
decrypt(ciphertext: Uint8Array, dst?: Uint8Array) {
validateBlockDecrypt(ciphertext);
const xk = expandKeyDecLE(key);
let _iv = iv;
const toClean: (Uint8Array | Uint32Array)[] = [xk];
if (!isAligned32(_iv)) toClean.push((_iv = copyBytes(_iv)));
const n32 = u32(_iv);
dst = getOutput(ciphertext.length, dst);
if (!isAligned32(ciphertext)) toClean.push((ciphertext = copyBytes(ciphertext)));
complexOverlapBytes(ciphertext, dst);
const b = u32(ciphertext);
const o = u32(dst);
// prettier-ignore
let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];
for (let i = 0; i + 4 <= b.length; ) {
// prettier-ignore
const ps0 = s0, ps1 = s1, ps2 = s2, ps3 = s3;
(s0 = b[i + 0]), (s1 = b[i + 1]), (s2 = b[i + 2]), (s3 = b[i + 3]);
const { s0: o0, s1: o1, s2: o2, s3: o3 } = decrypt(xk, s0, s1, s2, s3);
(o[i++] = o0 ^ ps0), (o[i++] = o1 ^ ps1), (o[i++] = o2 ^ ps2), (o[i++] = o3 ^ ps3);
}
clean(...toClean);
return validatePCKS(dst, pcks5);
},
};
}
);
/**
* CFB: Cipher Feedback Mode. The input for the block cipher is the previous cipher output.
* Unauthenticated: needs MAC.
*/
export const cfb: ((key: Uint8Array, iv: Uint8Array) => CipherWithOutput) & {
blockSize: number;
nonceLength: number;
} = /* @__PURE__ */ wrapCipher(
{ blockSize: 16, nonceLength: 16 },
function aescfb(key: Uint8Array, iv: Uint8Array): CipherWithOutput {
function processCfb(src: Uint8Array, isEncrypt: boolean, dst?: Uint8Array) {
abytes(src);
const srcLen = src.length;
dst = getOutput(srcLen, dst);
if (overlapBytes(src, dst)) throw new Error('overlapping src and dst not supported.');
const xk = expandKeyLE(key);
let _iv = iv;
const toClean: (Uint8Array | Uint32Array)[] = [xk];
if (!isAligned32(_iv)) toClean.push((_iv = copyBytes(_iv)));
if (!isAligned32(src)) toClean.push((src = copyBytes(src)));
const src32 = u32(src);
const dst32 = u32(dst);
const next32 = isEncrypt ? dst32 : src32;
const n32 = u32(_iv);
// prettier-ignore
let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];
for (let i = 0; i + 4 <= src32.length; ) {
const { s0: e0, s1: e1, s2: e2, s3: e3 } = encrypt(xk, s0, s1, s2, s3);
dst32[i + 0] = src32[i + 0] ^ e0;
dst32[i + 1] = src32[i + 1] ^ e1;
dst32[i + 2] = src32[i + 2] ^ e2;
dst32[i + 3] = src32[i + 3] ^ e3;
(s0 = next32[i++]), (s1 = next32[i++]), (s2 = next32[i++]), (s3 = next32[i++]);
}
// leftovers (less than block)
const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);
if (start < srcLen) {
({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));
const buf = u8(new Uint32Array([s0, s1, s2, s3]));
for (let i = start, pos = 0; i < srcLen; i++, pos++) dst[i] = src[i] ^ buf[pos];
clean(buf);
}
clean(...toClean);
return dst;
}
return {
encrypt: (plaintext: Uint8Array, dst?: Uint8Array) => processCfb(plaintext, true, dst),
decrypt: (ciphertext: Uint8Array, dst?: Uint8Array) => processCfb(ciphertext, false, dst),
};
}
);
// TODO: merge with chacha, however gcm has bitLen while chacha has byteLen
function computeTag(
fn: typeof ghash,
isLE: boolean,
key: Uint8Array,
data: Uint8Array,
AAD?: Uint8Array
) {
const aadLength = AAD ? AAD.length : 0;
const h = fn.create(key, data.length + aadLength);
if (AAD) h.update(AAD);
const num = u64Lengths(8 * data.length, 8 * aadLength, isLE);
h.update(data);
h.update(num);
const res = h.digest();
clean(num);
return res;
}
/**
* GCM: Galois/Counter Mode.
* Modern, parallel version of CTR, with MAC.
* Be careful: MACs can be forged.
* Unsafe to use random nonces under the same key, due to collision chance.
* As for nonce size, prefer 12-byte, instead of 8-byte.
*/
export const gcm: ((key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array) => Cipher) & {
blockSize: number;
nonceLength: number;
tagLength: number;
varSizeNonce: true;
} = /* @__PURE__ */ wrapCipher(
{ blockSize: 16, nonceLength: 12, tagLength: 16, varSizeNonce: true },
function aesgcm(key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array): Cipher {
// NIST 800-38d doesn't enforce minimum nonce length.
// We enforce 8 bytes for compat with openssl.
// 12 bytes are recommended. More than 12 bytes would be converted into 12.
if (nonce.length < 8) throw new Error('aes/gcm: invalid nonce length');
const tagLength = 16;
function _computeTag(authKey: Uint8Array, tagMask: Uint8Array, data: Uint8Array) {
const tag = computeTag(ghash, false, authKey, data, AAD);
for (let i = 0; i < tagMask.length; i++) tag[i] ^= tagMask[i];
return tag;
}
function deriveKeys() {
const xk = expandKeyLE(key);
const authKey = EMPTY_BLOCK.slice();
const counter = EMPTY_BLOCK.slice();
ctr32(xk, false, counter, counter, authKey);
// NIST 800-38d, page 15: different behavior for 96-bit and non-96-bit nonces
if (nonce.length === 12) {
counter.set(nonce);
} else {
const nonceLen = EMPTY_BLOCK.slice();
const view = createView(nonceLen);
setBigUint64(view, 8, BigInt(nonce.length * 8), false);
// ghash(nonce || u64be(0) || u64be(nonceLen*8))
const g = ghash.create(authKey).update(nonce).update(nonceLen);
g.digestInto(counter); // digestInto doesn't trigger '.destroy'
g.destroy();
}
const tagMask = ctr32(xk, false, counter, EMPTY_BLOCK);
return { xk, authKey, counter, tagMask };
}
return {
encrypt(plaintext: Uint8Array) {
const { xk, authKey, counter, tagMask } = deriveKeys();
const out = new Uint8Array(plaintext.length + tagLength);
const toClean: (Uint8Array | Uint32Array)[] = [xk, authKey, counter, tagMask];
if (!isAligned32(plaintext)) toClean.push((plaintext = copyBytes(plaintext)));
ctr32(xk, false, counter, plaintext, out.subarray(0, plaintext.length));
const tag = _computeTag(authKey, tagMask, out.subarray(0, out.length - tagLength));
toClean.push(tag);
out.set(tag, plaintext.length);
clean(...toClean);
return out;
},
decrypt(ciphertext: Uint8Array) {
const { xk, authKey, counter, tagMask } = deriveKeys();
const toClean: (Uint8Array | Uint32Array)[] = [xk, authKey, tagMask, counter];
if (!isAligned32(ciphertext)) toClean.push((ciphertext = copyBytes(ciphertext)));
const data = ciphertext.subarray(0, -tagLength);
const passedTag = ciphertext.subarray(-tagLength);
const tag = _computeTag(authKey, tagMask, data);
toClean.push(tag);
if (!equalBytes(tag, passedTag)) throw new Error('aes/gcm: invalid ghash tag');
const out = ctr32(xk, false, counter, data);
clean(...toClean);
return out;
},
};
}
);
const limit = (name: string, min: number, max: number) => (value: number) => {
if (!Number.isSafeInteger(value) || min > value || value > max) {
const minmax = '[' + min + '..' + max + ']';
throw new Error('' + name + ': expected value in range ' + minmax + ', got ' + value);
}
};
/**
* AES-GCM-SIV: classic AES-GCM with nonce-misuse resistance.
* Guarantees that, when a nonce is repeated, the only security loss is that identical
* plaintexts will produce identical ciphertexts.
* RFC 8452, https://datatracker.ietf.org/doc/html/rfc8452
*/
export const gcmsiv: ((key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array) => Cipher) & {
blockSize: number;
nonceLength: number;
tagLength: number;
varSizeNonce: true;
} = /* @__PURE__ */ wrapCipher(
{ blockSize: 16, nonceLength: 12, tagLength: 16, varSizeNonce: true },
function aessiv(key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array): Cipher {
const tagLength = 16;
// From RFC 8452: Section 6
const AAD_LIMIT = limit('AAD', 0, 2 ** 36);
const PLAIN_LIMIT = limit('plaintext', 0, 2 ** 36);
const NONCE_LIMIT = limit('nonce', 12, 12);
const CIPHER_LIMIT = limit('ciphertext', 16, 2 ** 36 + 16);
abytes(key, 16, 24, 32);
NONCE_LIMIT(nonce.length);
if (AAD !== undefined) AAD_LIMIT(AAD.length);
function deriveKeys() {
const xk = expandKeyLE(key);
const encKey = new Uint8Array(key.length);
const authKey = new Uint8Array(16);
const toClean: (Uint8Array | Uint32Array)[] = [xk, encKey];
let _nonce = nonce;
if (!isAligned32(_nonce)) toClean.push((_nonce = copyBytes(_nonce)));
const n32 = u32(_nonce);
// prettier-ignore
let s0 = 0, s1 = n32[0], s2 = n32[1], s3 = n32[2];
let counter = 0;
for (const derivedKey of [authKey, encKey].map(u32)) {
const d32 = u32(derivedKey);
for (let i = 0; i < d32.length; i += 2) {
// aes(u32le(0) || nonce)[:8] || aes(u32le(1) || nonce)[:8] ...
const { s0: o0, s1: o1 } = encrypt(xk, s0, s1, s2, s3);
d32[i + 0] = o0;
d32[i + 1] = o1;
s0 = ++counter; // increment counter inside state
}
}
const res = { authKey, encKey: expandKeyLE(encKey) };
// Cleanup
clean(...toClean);
return res;
}
function _computeTag(encKey: Uint32Array, authKey: Uint8Array, data: Uint8Array) {
const tag = computeTag(polyval, true, authKey, data, AAD);
// Compute the expected tag by XORing S_s and the nonce, clearing the
// most significant bit of the last byte and encrypting with the
// message-encryption key.
for (let i = 0; i < 12; i++) tag[i] ^= nonce[i];
tag[15] &= 0x7f; // Clear the highest bit
// encrypt tag as block
const t32 = u32(tag);
// prettier-ignore
let s0 = t32[0], s1 = t32[1], s2 = t32[2], s3 = t32[3];
({ s0, s1, s2, s3 } = encrypt(encKey, s0, s1, s2, s3));
(t32[0] = s0), (t32[1] = s1), (t32[2] = s2), (t32[3] = s3);
return tag;
}
// actual decrypt/encrypt of message.
function processSiv(encKey: Uint32Array, tag: Uint8Array, input: Uint8Array) {
let block = copyBytes(tag);
block[15] |= 0x80; // Force highest bit
const res = ctr32(encKey, true, block, input);
// Cleanup
clean(block);
return res;
}
return {
encrypt(plaintext: Uint8Array) {
PLAIN_LIMIT(plaintext.length);
const { encKey, authKey } = deriveKeys();
const tag = _computeTag(encKey, authKey, plaintext);
const toClean: (Uint8Array | Uint32Array)[] = [encKey, authKey, tag];
if (!isAligned32(plaintext)) toClean.push((plaintext = copyBytes(plaintext)));
const out = new Uint8Array(plaintext.length + tagLength);
out.set(tag, plaintext.length);
out.set(processSiv(encKey, tag, plaintext));
// Cleanup
clean(...toClean);
return out;
},
decrypt(ciphertext: Uint8Array) {
CIPHER_LIMIT(ciphertext.length);
const tag = ciphertext.subarray(-tagLength);
const { encKey, authKey } = deriveKeys();
const toClean: (Uint8Array | Uint32Array)[] = [encKey, authKey];
if (!isAligned32(ciphertext)) toClean.push((ciphertext = copyBytes(ciphertext)));
const plaintext = processSiv(encKey, tag, ciphertext.subarray(0, -tagLength));
const expectedTag = _computeTag(encKey, authKey, plaintext);
toClean.push(expectedTag);
if (!equalBytes(tag, expectedTag)) {
clean(...toClean);
throw new Error('invalid polyval tag');
}
// Cleanup
clean(...toClean);
return plaintext;
},
};
}
);
/**
* AES-GCM-SIV, not AES-SIV.
* This is legace name, use `gcmsiv` export instead.
* @deprecated
*/
export const siv: typeof gcmsiv = gcmsiv;
function isBytes32(a: unknown): a is Uint32Array {
return (
a instanceof Uint32Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint32Array')
);
}
function encryptBlock(xk: Uint32Array, block: Uint8Array): Uint8Array {
abytes(block, 16);
if (!isBytes32(xk)) throw new Error('_encryptBlock accepts result of expandKeyLE');
const b32 = u32(block);
let { s0, s1, s2, s3 } = encrypt(xk, b32[0], b32[1], b32[2], b32[3]);
(b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3);
return block;
}
function decryptBlock(xk: Uint32Array, block: Uint8Array): Uint8Array {
abytes(block, 16);
if (!isBytes32(xk)) throw new Error('_decryptBlock accepts result of expandKeyLE');
const b32 = u32(block);
let { s0, s1, s2, s3 } = decrypt(xk, b32[0], b32[1], b32[2], b32[3]);
(b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3);
return block;
}
/**
* AES-W (base for AESKW/AESKWP).
* Specs: [SP800-38F](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf),
* [RFC 3394](https://datatracker.ietf.org/doc/rfc3394/),
* [RFC 5649](https://datatracker.ietf.org/doc/rfc5649/).
*/
const AESW = {
/*
High-level pseudocode:
```
A: u64 = IV
out = []
for (let i=0, ctr = 0; i<6; i++) {
for (const chunk of chunks(plaintext, 8)) {
A ^= swapEndianess(ctr++)
[A, res] = chunks(encrypt(A || chunk), 8);
out ||= res
}
}
out = A || out
```
Decrypt is the same, but reversed.
*/
encrypt(kek: Uint8Array, out: Uint8Array) {
// Size is limited to 4GB, otherwise ctr will overflow and we'll need to switch to bigints.
// If you need it larger, open an issue.
if (out.length >= 2 ** 32) throw new Error('plaintext should be less than 4gb');
const xk = expandKeyLE(kek);
if (out.length === 16) encryptBlock(xk, out);
else {
const o32 = u32(out);
// prettier-ignore
let a0 = o32[0], a1 = o32[1]; // A
for (let j = 0, ctr = 1; j < 6; j++) {
for (let pos = 2; pos < o32.length; pos += 2, ctr++) {
const { s0, s1, s2, s3 } = encrypt(xk, a0, a1, o32[pos], o32[pos + 1]);
// A = MSB(64, B) ^ t where t = (n*j)+i
(a0 = s0), (a1 = s1 ^ byteSwap(ctr)), (o32[pos] = s2), (o32[pos + 1] = s3);
}
}
(o32[0] = a0), (o32[1] = a1); // out = A || out
}
xk.fill(0);
},
decrypt(kek: Uint8Array, out: Uint8Array) {
if (out.length - 8 >= 2 ** 32) throw new Error('ciphertext should be less than 4gb');
const xk = expandKeyDecLE(kek);
const chunks = out.length / 8 - 1; // first chunk is IV
if (chunks === 1) decryptBlock(xk, out);
else {
const o32 = u32(out);
// prettier-ignore
let a0 = o32[0], a1 = o32[1]; // A
for (let j = 0, ctr = chunks * 6; j < 6; j++) {
for (let pos = chunks * 2; pos >= 1; pos -= 2, ctr--) {
a1 ^= byteSwap(ctr);
const { s0, s1, s2, s3 } = decrypt(xk, a0, a1, o32[pos], o32[pos + 1]);
(a0 = s0), (a1 = s1), (o32[pos] = s2), (o32[pos + 1] = s3);
}
}
(o32[0] = a0), (o32[1] = a1);
}
xk.fill(0);
},
};
const AESKW_IV = /* @__PURE__ */ new Uint8Array(8).fill(0xa6); // A6A6A6A6A6A6A6A6
/**
* AES-KW (key-wrap). Injects static IV into plaintext, adds counter, encrypts 6 times.
* Reduces block size from 16 to 8 bytes.
* For padded version, use aeskwp.
* [RFC 3394](https://datatracker.ietf.org/doc/rfc3394/),
* [NIST.SP.800-38F](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf).
*/
export const aeskw: ((kek: Uint8Array) => Cipher) & {
blockSize: number;
} = /* @__PURE__ */ wrapCipher(
{ blockSize: 8 },
(kek: Uint8Array): Cipher => ({
encrypt(plaintext: Uint8Array) {
if (!plaintext.length || plaintext.length % 8 !== 0)
throw new Error('invalid plaintext length');
if (plaintext.length === 8)
throw new Error('8-byte keys not allowed in AESKW, use AESKWP instead');
const out = concatBytes(AESKW_IV, plaintext);
AESW.encrypt(kek, out);
return out;
},
decrypt(ciphertext: Uint8Array) {
// ciphertext must be at least 24 bytes and a multiple of 8 bytes
// 24 because should have at least two block (1 iv + 2).
// Replace with 16 to enable '8-byte keys'
if (ciphertext.length % 8 !== 0 || ciphertext.length < 3 * 8)
throw new Error('invalid ciphertext length');
const out = copyBytes(ciphertext);
AESW.decrypt(kek, out);
if (!equalBytes(out.subarray(0, 8), AESKW_IV)) throw new Error('integrity check failed');
out.subarray(0, 8).fill(0); // ciphertext.subarray(0, 8) === IV, but we clean it anyway
return out.subarray(8);
},
})
);
/*
We don't support 8-byte keys. The rabbit hole:
- Wycheproof says: "NIST SP 800-38F does not define the wrapping of 8 byte keys.
RFC 3394 Section 2 on the other hand specifies that 8 byte keys are wrapped
by directly encrypting one block with AES."
- https://github.com/C2SP/wycheproof/blob/master/doc/key_wrap.md
- "RFC 3394 specifies in Section 2, that the input for the key wrap
algorithm must be at least two blocks and otherwise the constant
field and key are simply encrypted with ECB as a single block"
- What RFC 3394 actually says (in Section 2):
- "Before being wrapped, the key data is parsed into n blocks of 64 bits.
The only restriction the key wrap algorithm places on n is that n be
at least two"
- "For key data with length less than or equal to 64 bits, the constant
field used in this specification and the key data form a single
128-bit codebook input making this key wrap unnecessary."
- Which means "assert(n >= 2)" and "use something else for 8 byte keys"
- NIST SP800-38F actually prohibits 8-byte in "5.3.1 Mandatory Limits".
It states that plaintext for KW should be "2 to 2^54 -1 semiblocks".
- So, where does "directly encrypt single block with AES" come from?
- Not RFC 3394. Pseudocode of key wrap in 2.2 explicitly uses
loop of 6 for any code path
- There is a weird W3C spec:
https://www.w3.org/TR/2002/REC-xmlenc-core-20021210/Overview.html#kw-aes128
- This spec is outdated, as admitted by Wycheproof authors
- There is RFC 5649 for padded key wrap, which is padding construction on
top of AESKW. In '4.1.2' it says: "If the padded plaintext contains exactly
eight octets, then prepend the AIV as defined in Section 3 above to P[1] and
encrypt the resulting 128-bit block using AES in ECB mode [Modes] with key
K (the KEK). In this case, the output is two 64-bit blocks C[0] and C[1]:"
- Browser subtle crypto is actually crashes on wrapping keys less than 16 bytes:
`Error: error:1C8000E6:Provider routines::invalid input length] { opensslErrorStack: [ 'error:030000BD:digital envelope routines::update error' ]`
In the end, seems like a bug in Wycheproof.
The 8-byte check can be easily disabled inside of AES_W.
*/
const AESKWP_IV = 0xa65959a6; // single u32le value
/**
* AES-KW, but with padding and allows random keys.
* Second u32 of IV is used as counter for length.
* [RFC 5649](https://www.rfc-editor.org/rfc/rfc5649)
*/
export const aeskwp: ((kek: Uint8Array) => Cipher) & {
blockSize: number;
} = /* @__PURE__ */ wrapCipher(
{ blockSize: 8 },
(kek: Uint8Array): Cipher => ({
encrypt(plaintext: Uint8Array) {
if (!plaintext.length) throw new Error('invalid plaintext length');
const padded = Math.ceil(plaintext.length / 8) * 8;
const out = new Uint8Array(8 + padded);
out.set(plaintext, 8);
const out32 = u32(out);
out32[0] = AESKWP_IV;
out32[1] = byteSwap(plaintext.length);
AESW.encrypt(kek, out);
return out;
},
decrypt(ciphertext: Uint8Array) {
// 16 because should have at least one block
if (ciphertext.length < 16) throw new Error('invalid ciphertext length');
const out = copyBytes(ciphertext);
const o32 = u32(out);
AESW.decrypt(kek, out);
const len = byteSwap(o32[1]) >>> 0;
const padded = Math.ceil(len / 8) * 8;
if (o32[0] !== AESKWP_IV || out.length - 8 !== padded)
throw new Error('integrity check failed');
for (let i = len; i < padded; i++)
if (out[8 + i] !== 0) throw new Error('integrity check failed');
out.subarray(0, 8).fill(0); // ciphertext.subarray(0, 8) === IV, but we clean it anyway
return out.subarray(8, 8 + len);
},
})
);
/** Unsafe low-level internal methods. May change at any time. */
export 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;
} = {
expandKeyLE,
expandKeyDecLE,
encrypt,
decrypt,
encryptBlock,
decryptBlock,
ctrCounter,
ctr32,
};
+290
View File
@@ -0,0 +1,290 @@
/**
* [ChaCha20](https://cr.yp.to/chacha.html) stream cipher, released
* in 2008. Developed after Salsa20, ChaCha aims to increase diffusion per round.
* It was standardized in [RFC 8439](https://datatracker.ietf.org/doc/html/rfc8439) and
* is now used in TLS 1.3.
*
* [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 [PDF](http://cr.yp.to/chacha/chacha-20080128.pdf) and
* [wiki](https://en.wikipedia.org/wiki/Salsa20).
* @module
*/
import { createCipher, rotl } from './_arx.ts';
import { poly1305 } from './_poly1305.ts';
import {
type ARXCipher,
type CipherWithOutput,
type XorStream,
clean,
equalBytes,
getOutput,
u64Lengths,
wrapCipher,
} from './utils.ts';
/**
* ChaCha core function.
*/
// prettier-ignore
function chachaCore(
s: Uint32Array, k: Uint32Array, n: Uint32Array, out: 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 Counter 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);
}
// 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;
}
/**
* hchacha helper method, used primarily in xchacha, to hash
* key and nonce into key' and nonce'.
* Same as chachaCore, but there doesn't seem to be a way to move the block
* out without 25% performance hit.
*/
// prettier-ignore
export function hchacha(
s: Uint32Array, k: Uint32Array, i: Uint32Array, o32: Uint32Array
): void {
let x00 = s[0], x01 = s[1], x02 = s[2], x03 = s[3],
x04 = k[0], x05 = k[1], x06 = k[2], x07 = k[3],
x08 = k[4], x09 = k[5], x10 = k[6], x11 = k[7],
x12 = i[0], x13 = i[1], x14 = i[2], x15 = 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);
}
let oi = 0;
o32[oi++] = x00; o32[oi++] = x01;
o32[oi++] = x02; o32[oi++] = x03;
o32[oi++] = x12; o32[oi++] = x13;
o32[oi++] = x14; o32[oi++] = x15;
}
/**
* Original, non-RFC chacha20 from DJB. 8-byte nonce, 8-byte counter.
*/
export const chacha20orig: 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 12-byte nonce, it's not safe to use fill it with random (CSPRNG), due to collision chance.
*/
export const chacha20: XorStream = /* @__PURE__ */ createCipher(chachaCore, {
counterRight: false,
counterLength: 4,
allowShortKeys: false,
});
/**
* XChaCha eXtended-nonce ChaCha. 24-byte nonce.
* With 24-byte nonce, it's safe to use fill it with random (CSPRNG).
* https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha
*/
export const xchacha20: XorStream = /* @__PURE__ */ createCipher(chachaCore, {
counterRight: false,
counterLength: 8,
extendNonceFn: hchacha,
allowShortKeys: false,
});
/**
* Reduced 8-round chacha, described in original paper.
*/
export const chacha8: XorStream = /* @__PURE__ */ createCipher(chachaCore, {
counterRight: false,
counterLength: 4,
rounds: 8,
});
/**
* Reduced 12-round chacha, described in original paper.
*/
export const chacha12: XorStream = /* @__PURE__ */ createCipher(chachaCore, {
counterRight: false,
counterLength: 4,
rounds: 12,
});
const ZEROS16 = /* @__PURE__ */ new Uint8Array(16);
// Pad to digest size with zeros
const updatePadded = (h: ReturnType<typeof poly1305.create>, msg: Uint8Array) => {
h.update(msg);
const left = msg.length % 16;
if (left) h.update(ZEROS16.subarray(left));
};
const ZEROS32 = /* @__PURE__ */ new Uint8Array(32);
function computeTag(
fn: XorStream,
key: Uint8Array,
nonce: Uint8Array,
data: Uint8Array,
AAD?: Uint8Array
): Uint8Array {
const authKey = fn(key, nonce, ZEROS32);
const h = poly1305.create(authKey);
if (AAD) updatePadded(h, AAD);
updatePadded(h, data);
const num = u64Lengths(data.length, AAD ? AAD.length : 0, true);
h.update(num);
const res = h.digest();
clean(authKey, num);
return res;
}
/**
* AEAD algorithm from RFC 8439.
* Salsa20 and chacha (RFC 8439) use poly1305 differently.
* We could have composed them similar to:
* https://github.com/paulmillr/scure-base/blob/b266c73dde977b1dd7ef40ef7a23cc15aab526b3/index.ts#L250
* 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: XorStream) =>
(key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array): CipherWithOutput => {
const tagLength = 16;
return {
encrypt(plaintext: Uint8Array, output?: Uint8Array) {
const plength = plaintext.length;
output = getOutput(plength + tagLength, output, false);
output.set(plaintext);
const oPlain = output.subarray(0, -tagLength);
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: Uint8Array, output?: 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);
if (!equalBytes(passedTag, tag)) throw new Error('invalid tag');
output.set(ciphertext.subarray(0, -tagLength));
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.
*/
export const chacha20poly1305: ARXCipher = /* @__PURE__ */ wrapCipher(
{ blockSize: 64, nonceLength: 12, tagLength: 16 },
_poly1305_aead(chacha20)
);
/**
* XChaCha20-Poly1305 extended-nonce chacha.
*
* Can be safely used with random nonces (CSPRNG).
* See [IRTF draft](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha).
*/
export const xchacha20poly1305: ARXCipher = /* @__PURE__ */ wrapCipher(
{ blockSize: 64, nonceLength: 24, tagLength: 16 },
_poly1305_aead(xchacha20)
);
+9
View File
@@ -0,0 +1,9 @@
/**
* Internal webcrypto alias.
* We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
* See utils.ts for details.
* @module
*/
declare const globalThis: Record<string, any> | undefined;
export const crypto: any =
typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
+15
View File
@@ -0,0 +1,15 @@
/**
* Internal webcrypto alias.
* We prefer WebCrypto aka globalThis.crypto, which exists in node.js 16+.
* Falls back to Node.js built-in crypto for Node.js <=v14.
* See utils.ts for details.
* @module
*/
// @ts-ignore
import * as nc from 'node:crypto';
export const crypto: any =
nc && typeof nc === 'object' && 'webcrypto' in nc
? (nc.webcrypto as any)
: nc && typeof nc === 'object' && 'randomBytes' in nc
? nc
: undefined;
+162
View File
@@ -0,0 +1,162 @@
/**
* FPE-FF1 (Format-preserving encryption algorithm) specified in
* [NIST 800-38G](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf).
* @module
*/
import { unsafe } from './aes.ts';
import { type Cipher, abytes, anumber, bytesToNumberBE, clean, numberToBytesBE } from './utils.ts';
// 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 NIST Special Publication 800-38G.
// https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf
const BLOCK_LEN = 16;
// Calculates a modulo b
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: Uint8Array, tweak: 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');
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);
view.setUint16(4, radix, false);
view.setUint32(8, x.length, false);
view.setUint32(12, tweak.length, false);
// Q = T || [0](tb1) 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);
// PRF
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 */
export function FF1(
radix: number,
key: Uint8Array,
tweak: Uint8Array = EMPTY_BUF
): { encrypt(x: number[]): number[]; decrypt(x: number[]): number[] } {
anumber(radix);
abytes(key);
abytes(tweak);
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 string which encodes each byte in little-endian byte order
const binLE = {
encode(bytes: 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[]): 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;
},
};
/** Binary version of FPE-FF1 format-preserving encryption. */
export function BinaryFF1(key: Uint8Array, tweak: Uint8Array = EMPTY_BUF): Cipher {
const ff1 = FF1(2, key, tweak);
return {
encrypt: (x: Uint8Array) => binLE.decode(ff1.encrypt(binLE.encode(x))),
decrypt: (x: Uint8Array) => binLE.decode(ff1.decrypt(binLE.encode(x))),
};
}
+26
View File
@@ -0,0 +1,26 @@
/**
* Audited & minimal JS implementation of Salsa20, ChaCha and AES. Check out individual modules.
* @example
```js
import { gcm, siv } from '@noble/ciphers/aes';
import { xsalsa20poly1305 } from '@noble/ciphers/salsa';
import { secretbox } from '@noble/ciphers/salsa'; // == xsalsa20poly1305
import { chacha20poly1305, xchacha20poly1305 } from '@noble/ciphers/chacha';
// Unauthenticated encryption: make sure to use HMAC or similar
import { ctr, cfb, cbc, ecb } from '@noble/ciphers/aes';
import { salsa20, xsalsa20 } from '@noble/ciphers/salsa';
import { chacha20, xchacha20, chacha8, chacha12 } from '@noble/ciphers/chacha';
// KW
import { aeskw, aeskwp } from '@noble/ciphers/aes';
// Utilities
import { bytesToHex, hexToBytes, bytesToUtf8, utf8ToBytes } from '@noble/ciphers/utils';
import { managedNonce, randomBytes } from '@noble/ciphers/webcrypto';
import { poly1305 } from '@noble/ciphers/_poly1305';
import { ghash, polyval } from '@noble/ciphers/_polyval';
```
* @module
*/
throw new Error('root module cannot be imported: import submodules instead. Check out README');
+3
View File
@@ -0,0 +1,3 @@
{
"type": "module"
}
+189
View File
@@ -0,0 +1,189 @@
/**
* [Salsa20](https://cr.yp.to/snuffle.html) 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.
*
* Check out [PDF](https://cr.yp.to/snuffle/salsafamily-20071225.pdf) and
* [wiki](https://en.wikipedia.org/wiki/Salsa20).
* @module
*/
import { createCipher, rotl } from './_arx.ts';
import { poly1305 } from './_poly1305.ts';
import {
abytes,
type ARXCipher,
type CipherWithOutput,
clean,
equalBytes,
getOutput,
wrapCipher,
type XorStream,
} from './utils.ts';
/** Salsa20 core function. */
// prettier-ignore
function salsaCore(
s: Uint32Array, k: Uint32Array, n: Uint32Array, out: Uint32Array, cnt: number, rounds = 20
): void {
// Based on https://cr.yp.to/salsa20.html
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 hashing function, used primarily in xsalsa, to hash
* key and nonce into key' and nonce'.
* Same as salsaCore, but there doesn't seem to be a way to move the block
* out without 25% performance hit.
*/
// prettier-ignore
export function hsalsa(
s: Uint32Array, k: Uint32Array, i: Uint32Array, o32: Uint32Array
): void {
let x00 = s[0], x01 = k[0], x02 = k[1], x03 = k[2],
x04 = k[3], x05 = s[1], x06 = i[0], x07 = i[1],
x08 = i[2], x09 = i[3], x10 = s[2], x11 = k[4],
x12 = k[5], x13 = k[6], x14 = k[7], x15 = 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;
o32[oi++] = x00; o32[oi++] = x05;
o32[oi++] = x10; o32[oi++] = x15;
o32[oi++] = x06; o32[oi++] = x07;
o32[oi++] = x08; o32[oi++] = x09;
}
/**
* Salsa20 from original paper.
* Unsafe to use random nonces under the same key, due to collision chance.
* Prefer XSalsa instead.
*/
export const salsa20: XorStream = /* @__PURE__ */ createCipher(salsaCore, {
allowShortKeys: true,
counterRight: true,
});
/**
* xsalsa20 eXtended-nonce salsa.
* Can be safely used with random 24-byte nonces (CSPRNG).
*/
export const xsalsa20: XorStream = /* @__PURE__ */ createCipher(salsaCore, {
counterRight: true,
extendNonceFn: hsalsa,
});
/**
* xsalsa20-poly1305 eXtended-nonce salsa.
* Can be safely used with random 24-byte nonces (CSPRNG).
* Also known as secretbox from libsodium / nacl.
*/
export const xsalsa20poly1305: ARXCipher = /* @__PURE__ */ wrapCipher(
{ blockSize: 64, nonceLength: 24, tagLength: 16 },
(key: Uint8Array, nonce: Uint8Array): CipherWithOutput => {
return {
encrypt(plaintext: Uint8Array, output?: 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.
output = getOutput(plaintext.length + 32, output, false); // need 32 additional bytes, see above
const authKey = output.subarray(0, 32); // output[0..32] = poly1305 auth key
const ciphPlaintext = output.subarray(32); // output[32..] = plaintext, then ciphertext
output.set(plaintext, 32);
clean(authKey); // authKey is produced by xoring with zeros
xsalsa20(key, nonce, output, output); // output = stream ^ output; authKey = stream ^ zeros(32)
const tag = poly1305(ciphPlaintext, authKey); // calculate tag over ciphertext
output.set(tag, 16); // output[16..32] = tag
clean(output.subarray(0, 16), tag); // clean-up authKey remnants & copy of tag
return output.subarray(16); // return output[16..]
},
decrypt(ciphertext: Uint8Array, output?: Uint8Array) {
// tmp part passed tag ciphertext
// [0..32] [32..48] [48..]
abytes(ciphertext);
output = getOutput(ciphertext.length + 32, output, false);
const tmp = output.subarray(0, 32); // output[0..32] is used to calc authKey
const passedTag = output.subarray(32, 48); // output[32..48] = passed tag
const ciphPlaintext = output.subarray(48); // output[48..] = ciphertext, then plaintext
output.set(ciphertext, 32); // copy ciphertext into output
clean(tmp); // authKey is produced by xoring with zeros
const authKey = xsalsa20(key, nonce, tmp, tmp); // authKey = stream ^ zeros(32)
const tag = poly1305(ciphPlaintext, authKey); // calculate tag over ciphertext
if (!equalBytes(passedTag, tag)) throw new Error('invalid tag');
xsalsa20(key, nonce, output.subarray(16), output.subarray(16)); // output = stream ^ output[16..]
clean(tmp, passedTag, tag);
return ciphPlaintext; // return output[48..], skipping zeroized output[0..48]
},
};
}
);
/**
* Alias to `xsalsa20poly1305`, for compatibility with libsodium / nacl
*/
export function secretbox(
key: Uint8Array,
nonce: Uint8Array
): {
seal: (plaintext: Uint8Array, output?: Uint8Array) => Uint8Array;
open: (ciphertext: Uint8Array, output?: Uint8Array) => Uint8Array;
} {
const xs = xsalsa20poly1305(key, nonce);
return { seal: xs.encrypt, open: xs.decrypt };
}
+453
View File
@@ -0,0 +1,453 @@
/**
* 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. */
export function isBytes(a: unknown): a is Uint8Array {
return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
}
/** Asserts something is boolean. */
export function abool(b: boolean): void {
if (typeof b !== 'boolean') throw new Error(`boolean expected, not ${b}`);
}
/** Asserts something is positive integer. */
export function anumber(n: number): void {
if (!Number.isSafeInteger(n) || n < 0) throw new Error('positive integer expected, got ' + n);
}
/** Asserts something is Uint8Array. */
export function abytes(b: Uint8Array | undefined, ...lengths: number[]): void {
if (!isBytes(b)) throw new Error('Uint8Array expected');
if (lengths.length > 0 && !lengths.includes(b.length))
throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
}
/**
* Asserts something is hash
* TODO: remove
* @deprecated
*/
export function ahash(h: IHash): void {
if (typeof h !== 'function' || typeof h.create !== 'function')
throw new Error('Hash should be wrapped by utils.createHasher');
anumber(h.outputLen);
anumber(h.blockLen);
}
/** Asserts a hash instance has not been destroyed / finished */
export function aexists(instance: any, checkFinished = true): void {
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 properly-sized byte array */
export function aoutput(out: any, instance: any): void {
abytes(out);
const min = instance.outputLen;
if (out.length < min) {
throw new Error('digestInto() expects output buffer of length at least ' + min);
}
}
export type IHash = {
(data: string | Uint8Array): Uint8Array;
blockLen: number;
outputLen: number;
create: any;
};
/** Generic type encompassing 8/16/32-byte arrays - but not 64-byte. */
// prettier-ignore
export type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |
Uint16Array | Int16Array | Uint32Array | Int32Array;
/** Cast u8 / u16 / u32 to u8. */
export function u8(arr: TypedArray): Uint8Array {
return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
}
/** Cast u8 / u16 / u32 to u32. */
export function u32(arr: TypedArray): Uint32Array {
return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
}
/** Zeroize a byte array. Warning: JS provides no guarantees. */
export function clean(...arrays: TypedArray[]): void {
for (let i = 0; i < arrays.length; i++) {
arrays[i].fill(0);
}
}
/** Create DataView of an array for easy byte-level manipulation. */
export function createView(arr: TypedArray): DataView {
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
}
/** Is current platform little-endian? Most are. Big-Endian platform: IBM */
export const isLE: boolean = /* @__PURE__ */ (() =>
new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
const hasHexBuiltin: boolean = /* @__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.
* @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
*/
export function bytesToHex(bytes: Uint8Array): string {
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 } as const;
function asciiToBase16(ch: number): number | undefined {
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.
* @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
*/
export function hexToBytes(hex: string): Uint8Array {
if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);
// @ts-ignore
if (hasHexBuiltin) return Uint8Array.fromHex(hex);
const hl = hex.length;
const al = hl / 2;
if (hl % 2) throw new Error('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 Error('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
export function hexToNumber(hex: string): bigint {
if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);
return BigInt(hex === '' ? '0' : '0x' + hex); // Big Endian
}
// Used in ff1
// BE: Big Endian, LE: Little Endian
export function bytesToNumberBE(bytes: Uint8Array): bigint {
return hexToNumber(bytesToHex(bytes));
}
// Used in micro, ff1
export function numberToBytesBE(n: number | bigint, len: number): Uint8Array {
return hexToBytes(n.toString(16).padStart(len * 2, '0'));
}
// TODO: remove
// There is no setImmediate in browser and setTimeout is slow.
// call of async fn will return Promise, which will be fullfiled only on
// next scheduler queue processing step and this is exactly what we need.
export const nextTick = async (): Promise<void> => {};
// Global symbols, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535
declare const TextEncoder: any;
declare const TextDecoder: any;
/**
* Converts string to bytes using UTF8 encoding.
* @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
*/
export function utf8ToBytes(str: string): Uint8Array {
if (typeof str !== 'string') throw new Error('string expected');
return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
}
/**
* Converts bytes to string using UTF8 encoding.
* @example bytesToUtf8(new Uint8Array([97, 98, 99])) // 'abc'
*/
export function bytesToUtf8(bytes: Uint8Array): string {
return new TextDecoder().decode(bytes);
}
// TODO: remove
export type Input = Uint8Array | string;
/**
* Normalizes (non-hex) string or Uint8Array to Uint8Array.
* Warning: when Uint8Array is passed, it would NOT get copied.
* Keep in mind for future mutable operations.
*/
export function toBytes(data: string | Uint8Array): Uint8Array {
if (typeof data === 'string') data = utf8ToBytes(data);
else if (isBytes(data)) data = copyBytes(data);
else throw new Error('Uint8Array expected, got ' + typeof data);
return data;
}
/**
* Checks if two U8A use same underlying buffer and overlaps.
* This is invalid and can corrupt data.
*/
export function overlapBytes(a: Uint8Array, b: Uint8Array): boolean {
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/salse, which designed with this)
*/
export function complexOverlapBytes(input: Uint8Array, output: Uint8Array): void {
// 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.
*/
export function concatBytes(...arrays: Uint8Array[]): Uint8Array {
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;
}
// Used in ARX only
type EmptyObj = {};
export function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(
defaults: T1,
opts: T2
): T1 & T2 {
if (opts == null || typeof opts !== 'object') throw new Error('options must be defined');
const merged = Object.assign(defaults, opts);
return merged as T1 & T2;
}
/** Compares 2 uint8array-s in kinda constant time. */
export function equalBytes(a: Uint8Array, b: Uint8Array): boolean {
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;
}
// TODO: remove
/** For runtime check if class implements interface. */
export abstract class Hash<T extends Hash<T>> {
abstract blockLen: number; // Bytes per block
abstract outputLen: number; // Bytes in output
abstract update(buf: string | Uint8Array): this;
// Writes digest into buf
abstract digestInto(buf: Uint8Array): void;
abstract digest(): 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.
*/
abstract destroy(): void;
}
// This will allow to re-use with composable things like packed & base encoders
// Also, we probably can make tags composable
/** Sync cipher: takes byte array and returns byte array. */
export type Cipher = {
encrypt(plaintext: Uint8Array): Uint8Array;
decrypt(ciphertext: Uint8Array): Uint8Array;
};
/** Async cipher e.g. from built-in WebCrypto. */
export type AsyncCipher = {
encrypt(plaintext: Uint8Array): Promise<Uint8Array>;
decrypt(ciphertext: Uint8Array): Promise<Uint8Array>;
};
/** Cipher with `output` argument which can optimize by doing 1 less allocation. */
export type CipherWithOutput = Cipher & {
encrypt(plaintext: Uint8Array, output?: Uint8Array): Uint8Array;
decrypt(ciphertext: Uint8Array, output?: Uint8Array): 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 = {
blockSize: number;
nonceLength?: number;
tagLength?: number;
varSizeNonce?: boolean;
};
/** ARX cipher, like salsa or chacha. */
export type ARXCipher = ((
key: Uint8Array,
nonce: Uint8Array,
AAD?: Uint8Array
) => CipherWithOutput) & {
blockSize: number;
nonceLength: number;
tagLength: number;
};
export type CipherCons<T extends any[]> = (key: Uint8Array, ...args: T) => Cipher;
/**
* Wraps a cipher: validates args, ensures encrypt() can only be called once.
* @__NO_SIDE_EFFECTS__
*/
export const wrapCipher = <C extends CipherCons<any>, P extends CipherParams>(
params: P,
constructor: C
): C & P => {
function wrappedCipher(key: Uint8Array, ...args: any[]): CipherWithOutput {
// Validate key
abytes(key);
// Big-Endian hardware is rare. Just in case someone still decides to run ciphers:
if (!isLE) throw new Error('Non little-endian hardware is not yet supported');
// Validate nonce if nonceLength is present
if (params.nonceLength !== undefined) {
const nonce = args[0];
if (!nonce) throw new Error('nonce / iv required');
if (params.varSizeNonce) abytes(nonce);
else abytes(nonce, params.nonceLength);
}
// Validate AAD if tagLength present
const tagl = params.tagLength;
if (tagl && args[1] !== undefined) {
abytes(args[1]);
}
const cipher = constructor(key, ...args);
const checkOutput = (fnLength: number, output?: Uint8Array) => {
if (output !== undefined) {
if (fnLength !== 2) throw new Error('cipher output not supported');
abytes(output);
}
};
// Create wrapped cipher with validation and single-use encryption
let called = false;
const wrCipher = {
encrypt(data: Uint8Array, output?: Uint8Array) {
if (called) throw new Error('cannot encrypt() twice with same key + nonce');
called = true;
abytes(data);
checkOutput(cipher.encrypt.length, output);
return (cipher as CipherWithOutput).encrypt(data, output);
},
decrypt(data: Uint8Array, output?: Uint8Array) {
abytes(data);
if (tagl && data.length < tagl)
throw new Error('invalid ciphertext length: smaller than tagLength=' + tagl);
checkOutput(cipher.decrypt.length, output);
return (cipher as CipherWithOutput).decrypt(data, output);
},
};
return wrCipher;
}
Object.assign(wrappedCipher, params);
return wrappedCipher as C & P;
};
/** Represents salsa / chacha stream. */
export type XorStream = (
key: Uint8Array,
nonce: Uint8Array,
data: Uint8Array,
output?: Uint8Array,
counter?: number
) => Uint8Array;
/**
* By default, returns u8a of length.
* When out is available, it checks it for validity and uses it.
*/
export function getOutput(
expectedLength: number,
out?: Uint8Array,
onlyAligned = true
): Uint8Array {
if (out === undefined) return new Uint8Array(expectedLength);
if (out.length !== expectedLength)
throw new Error('invalid output length, expected ' + expectedLength + ', got: ' + out.length);
if (onlyAligned && !isAligned32(out)) throw new Error('invalid output, must be aligned');
return out;
}
/** Polyfill for Safari 14. */
export function setBigUint64(
view: DataView,
byteOffset: number,
value: bigint,
isLE: boolean
): void {
if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);
const _32n = BigInt(32);
const _u32_max = BigInt(0xffffffff);
const wh = Number((value >> _32n) & _u32_max);
const wl = Number(value & _u32_max);
const h = isLE ? 4 : 0;
const l = isLE ? 0 : 4;
view.setUint32(byteOffset + h, wh, isLE);
view.setUint32(byteOffset + l, wl, isLE);
}
export function u64Lengths(dataLength: number, aadLength: number, isLE: boolean): Uint8Array {
abool(isLE);
const num = new Uint8Array(16);
const view = createView(num);
setBigUint64(view, 0, BigInt(aadLength), isLE);
setBigUint64(view, 8, BigInt(dataLength), isLE);
return num;
}
// Is byte array aligned to 4 byte offset (u32)?
export function isAligned32(bytes: Uint8Array): boolean {
return bytes.byteOffset % 4 === 0;
}
// copy bytes to new u8a (aligned). Because Buffer.slice is broken.
export function copyBytes(bytes: Uint8Array): Uint8Array {
return Uint8Array.from(bytes);
}
+169
View File
@@ -0,0 +1,169 @@
/**
* WebCrypto-based AES gcm/ctr/cbc, `managedNonce` and `randomBytes`.
* We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
* node.js versions earlier than v19 don't declare it in global scope.
* For node.js, package.js on#exports field mapping rewrites import
* from `crypto` to `cryptoNode`, which imports native module.
* Makes the utils un-importable in browsers without a bundler.
* Once node.js 18 is deprecated, we can just drop the import.
* @module
*/
// Use full path so that Node.js can rewrite it to `cryptoNode.js`.
import { crypto } from '@noble/ciphers/crypto';
import { abytes, anumber, type AsyncCipher, type Cipher, concatBytes } from './utils.ts';
/**
* Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.
*/
export function randomBytes(bytesLength = 32): Uint8Array {
if (crypto && typeof crypto.getRandomValues === 'function') {
return crypto.getRandomValues(new Uint8Array(bytesLength));
}
// Legacy Node.js compatibility
if (crypto && typeof crypto.randomBytes === 'function') {
return Uint8Array.from(crypto.randomBytes(bytesLength));
}
throw new Error('crypto.getRandomValues must be defined');
}
export function getWebcryptoSubtle(): any {
if (crypto && typeof crypto.subtle === 'object' && crypto.subtle != null) return crypto.subtle;
throw new Error('crypto.subtle must be defined');
}
type RemoveNonceInner<T extends any[], Ret> = ((...args: T) => Ret) extends (
arg0: any,
arg1: any,
...rest: infer R
) => any
? (key: Uint8Array, ...args: R) => Ret
: never;
type RemoveNonce<T extends (...args: any) => any> = RemoveNonceInner<Parameters<T>, ReturnType<T>>;
type CipherWithNonce = ((key: Uint8Array, nonce: Uint8Array, ...args: any[]) => Cipher) & {
nonceLength: number;
};
/**
* Uses CSPRG for nonce, nonce injected in ciphertext.
* @example
* const gcm = managedNonce(aes.gcm);
* const ciphr = gcm(key).encrypt(data);
* const plain = gcm(key).decrypt(ciph);
*/
export function managedNonce<T extends CipherWithNonce>(fn: T): RemoveNonce<T> {
const { nonceLength } = fn;
anumber(nonceLength);
return ((key: Uint8Array, ...args: any[]): any => ({
encrypt(plaintext: Uint8Array, ...argsEnc: any[]) {
const nonce = randomBytes(nonceLength);
const ciphertext = (fn(key, nonce, ...args).encrypt as any)(plaintext, ...argsEnc);
const out = concatBytes(nonce, ciphertext);
ciphertext.fill(0);
return out;
},
decrypt(ciphertext: Uint8Array, ...argsDec: any[]) {
const nonce = ciphertext.subarray(0, nonceLength);
const data = ciphertext.subarray(nonceLength);
return (fn(key, nonce, ...args).decrypt as any)(data, ...argsDec);
},
})) as RemoveNonce<T>;
}
// Overridable
// @TODO
export const utils: {
encrypt: (key: Uint8Array, ...all: any[]) => Promise<Uint8Array>;
decrypt: (key: Uint8Array, ...all: any[]) => Promise<Uint8Array>;
} = {
async encrypt(
key: Uint8Array,
keyParams: any,
cryptParams: any,
plaintext: Uint8Array
): Promise<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);
},
async decrypt(
key: Uint8Array,
keyParams: any,
cryptParams: any,
ciphertext: Uint8Array
): Promise<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);
},
};
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: Uint8Array, AAD?: Uint8Array) {
if (algo === mode.CBC) return { name: mode.CBC, iv: nonce };
if (algo === mode.CTR) return { name: mode.CTR, counter: nonce, length: 64 };
if (algo === mode.GCM) {
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) {
return (key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array): AsyncCipher => {
abytes(key);
abytes(nonce);
const keyParams = { name: algo, length: key.length * 8 };
const cryptParams = getCryptParams(algo, nonce, AAD);
let consumed = false;
return {
// keyLength,
encrypt(plaintext: 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: Uint8Array) {
abytes(ciphertext);
return utils.decrypt(key, keyParams, cryptParams, ciphertext);
},
};
};
}
/** AES-CBC, native webcrypto version */
export const cbc: (key: Uint8Array, iv: Uint8Array) => AsyncCipher = /* @__PURE__ */ (() =>
generate(mode.CBC))();
/** AES-CTR, native webcrypto version */
export const ctr: (key: Uint8Array, nonce: Uint8Array) => AsyncCipher = /* @__PURE__ */ (() =>
generate(mode.CTR))();
/** AES-GCM, native webcrypto version */
export const gcm: (key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array) => AsyncCipher =
/* @__PURE__ */ (() => generate(mode.GCM))();
// // 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);
+155
View File
@@ -0,0 +1,155 @@
/**
* 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. */
export declare function isBytes(a: unknown): a is Uint8Array;
/** Asserts something is boolean. */
export declare function abool(b: boolean): void;
/** Asserts something is positive integer. */
export declare function anumber(n: number): void;
/** Asserts something is Uint8Array. */
export declare function abytes(b: Uint8Array | undefined, ...lengths: number[]): void;
/**
* Asserts something is hash
* TODO: remove
* @deprecated
*/
export declare function ahash(h: IHash): void;
/** Asserts a hash instance has not been destroyed / finished */
export declare function aexists(instance: any, checkFinished?: boolean): void;
/** Asserts output is properly-sized byte array */
export declare function aoutput(out: any, instance: any): void;
export type IHash = {
(data: string | Uint8Array): Uint8Array;
blockLen: number;
outputLen: number;
create: any;
};
/** Generic type encompassing 8/16/32-byte arrays - but not 64-byte. */
export type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array | Uint16Array | Int16Array | Uint32Array | Int32Array;
/** Cast u8 / u16 / u32 to u8. */
export declare function u8(arr: TypedArray): Uint8Array;
/** Cast u8 / u16 / u32 to u32. */
export declare function u32(arr: TypedArray): Uint32Array;
/** Zeroize a byte array. Warning: JS provides no guarantees. */
export declare function clean(...arrays: TypedArray[]): void;
/** Create DataView of an array for easy byte-level manipulation. */
export declare function createView(arr: TypedArray): DataView;
/** Is current platform little-endian? Most are. Big-Endian platform: IBM */
export declare const isLE: boolean;
/**
* Convert byte array to hex string. Uses built-in function, when available.
* @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
*/
export declare function bytesToHex(bytes: Uint8Array): string;
/**
* Convert hex string to byte array. Uses built-in function, when available.
* @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
*/
export declare function hexToBytes(hex: string): Uint8Array;
export declare function hexToNumber(hex: string): bigint;
export declare function bytesToNumberBE(bytes: Uint8Array): bigint;
export declare function numberToBytesBE(n: number | bigint, len: number): Uint8Array;
export declare const nextTick: () => Promise<void>;
/**
* Converts string to bytes using UTF8 encoding.
* @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
*/
export declare function utf8ToBytes(str: string): Uint8Array;
/**
* Converts bytes to string using UTF8 encoding.
* @example bytesToUtf8(new Uint8Array([97, 98, 99])) // 'abc'
*/
export declare function bytesToUtf8(bytes: Uint8Array): string;
export type Input = Uint8Array | string;
/**
* Normalizes (non-hex) string or Uint8Array to Uint8Array.
* Warning: when Uint8Array is passed, it would NOT get copied.
* Keep in mind for future mutable operations.
*/
export declare function toBytes(data: string | Uint8Array): Uint8Array;
/**
* Checks if two U8A use same underlying buffer and overlaps.
* This is invalid and can corrupt data.
*/
export declare function overlapBytes(a: Uint8Array, b: 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/salse, which designed with this)
*/
export declare function complexOverlapBytes(input: Uint8Array, output: Uint8Array): void;
/**
* Copies several Uint8Arrays into one.
*/
export declare function concatBytes(...arrays: Uint8Array[]): Uint8Array;
type EmptyObj = {};
export declare function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(defaults: T1, opts: T2): T1 & T2;
/** Compares 2 uint8array-s in kinda constant time. */
export declare function equalBytes(a: Uint8Array, b: Uint8Array): boolean;
/** For runtime check if class implements interface. */
export declare abstract class Hash<T extends Hash<T>> {
abstract blockLen: number;
abstract outputLen: number;
abstract update(buf: string | Uint8Array): this;
abstract digestInto(buf: Uint8Array): void;
abstract digest(): 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.
*/
abstract destroy(): void;
}
/** Sync cipher: takes byte array and returns byte array. */
export type Cipher = {
encrypt(plaintext: Uint8Array): Uint8Array;
decrypt(ciphertext: Uint8Array): Uint8Array;
};
/** Async cipher e.g. from built-in WebCrypto. */
export type AsyncCipher = {
encrypt(plaintext: Uint8Array): Promise<Uint8Array>;
decrypt(ciphertext: Uint8Array): Promise<Uint8Array>;
};
/** Cipher with `output` argument which can optimize by doing 1 less allocation. */
export type CipherWithOutput = Cipher & {
encrypt(plaintext: Uint8Array, output?: Uint8Array): Uint8Array;
decrypt(ciphertext: Uint8Array, output?: Uint8Array): 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 = {
blockSize: number;
nonceLength?: number;
tagLength?: number;
varSizeNonce?: boolean;
};
/** ARX cipher, like salsa or chacha. */
export type ARXCipher = ((key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array) => CipherWithOutput) & {
blockSize: number;
nonceLength: number;
tagLength: number;
};
export type CipherCons<T extends any[]> = (key: Uint8Array, ...args: T) => Cipher;
/**
* Wraps a cipher: validates args, ensures encrypt() can only be called once.
* @__NO_SIDE_EFFECTS__
*/
export declare const wrapCipher: <C extends CipherCons<any>, P extends CipherParams>(params: P, constructor: C) => C & P;
/** Represents salsa / chacha stream. */
export type XorStream = (key: Uint8Array, nonce: Uint8Array, data: Uint8Array, output?: Uint8Array, counter?: number) => Uint8Array;
/**
* By default, returns u8a of length.
* When out is available, it checks it for validity and uses it.
*/
export declare function getOutput(expectedLength: number, out?: Uint8Array, onlyAligned?: boolean): Uint8Array;
/** Polyfill for Safari 14. */
export declare function setBigUint64(view: DataView, byteOffset: number, value: bigint, isLE: boolean): void;
export declare function u64Lengths(dataLength: number, aadLength: number, isLE: boolean): Uint8Array;
export declare function isAligned32(bytes: Uint8Array): boolean;
export declare function copyBytes(bytes: Uint8Array): Uint8Array;
export {};
//# sourceMappingURL=utils.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["src/utils.ts"],"names":[],"mappings":"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"}
+374
View File
@@ -0,0 +1,374 @@
"use strict";
/**
* Utilities for hex, bytes, CSPRNG.
* @module
*/
/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
Object.defineProperty(exports, "__esModule", { value: true });
exports.wrapCipher = exports.Hash = exports.nextTick = exports.isLE = void 0;
exports.isBytes = isBytes;
exports.abool = abool;
exports.anumber = anumber;
exports.abytes = abytes;
exports.ahash = ahash;
exports.aexists = aexists;
exports.aoutput = aoutput;
exports.u8 = u8;
exports.u32 = u32;
exports.clean = clean;
exports.createView = createView;
exports.bytesToHex = bytesToHex;
exports.hexToBytes = hexToBytes;
exports.hexToNumber = hexToNumber;
exports.bytesToNumberBE = bytesToNumberBE;
exports.numberToBytesBE = numberToBytesBE;
exports.utf8ToBytes = utf8ToBytes;
exports.bytesToUtf8 = bytesToUtf8;
exports.toBytes = toBytes;
exports.overlapBytes = overlapBytes;
exports.complexOverlapBytes = complexOverlapBytes;
exports.concatBytes = concatBytes;
exports.checkOpts = checkOpts;
exports.equalBytes = equalBytes;
exports.getOutput = getOutput;
exports.setBigUint64 = setBigUint64;
exports.u64Lengths = u64Lengths;
exports.isAligned32 = isAligned32;
exports.copyBytes = copyBytes;
/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
function isBytes(a) {
return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
}
/** Asserts something is boolean. */
function abool(b) {
if (typeof b !== 'boolean')
throw new Error(`boolean expected, not ${b}`);
}
/** Asserts something is positive integer. */
function anumber(n) {
if (!Number.isSafeInteger(n) || n < 0)
throw new Error('positive integer expected, got ' + n);
}
/** Asserts something is Uint8Array. */
function abytes(b, ...lengths) {
if (!isBytes(b))
throw new Error('Uint8Array expected');
if (lengths.length > 0 && !lengths.includes(b.length))
throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
}
/**
* Asserts something is hash
* TODO: remove
* @deprecated
*/
function ahash(h) {
if (typeof h !== 'function' || typeof h.create !== 'function')
throw new Error('Hash should be wrapped by utils.createHasher');
anumber(h.outputLen);
anumber(h.blockLen);
}
/** Asserts a hash instance has not been destroyed / finished */
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 properly-sized byte array */
function aoutput(out, instance) {
abytes(out);
const min = instance.outputLen;
if (out.length < min) {
throw new Error('digestInto() expects output buffer of length at least ' + min);
}
}
/** Cast u8 / u16 / u32 to u8. */
function u8(arr) {
return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
}
/** Cast u8 / u16 / u32 to u32. */
function u32(arr) {
return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
}
/** Zeroize a byte array. Warning: JS provides no guarantees. */
function clean(...arrays) {
for (let i = 0; i < arrays.length; i++) {
arrays[i].fill(0);
}
}
/** Create DataView of an array for easy byte-level manipulation. */
function createView(arr) {
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
}
/** Is current platform little-endian? Most are. Big-Endian platform: IBM */
exports.isLE = (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
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.
* @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
*/
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.
* @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
*/
function hexToBytes(hex) {
if (typeof hex !== 'string')
throw new Error('hex string expected, got ' + typeof hex);
// @ts-ignore
if (hasHexBuiltin)
return Uint8Array.fromHex(hex);
const hl = hex.length;
const al = hl / 2;
if (hl % 2)
throw new Error('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 Error('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
function hexToNumber(hex) {
if (typeof hex !== 'string')
throw new Error('hex string expected, got ' + typeof hex);
return BigInt(hex === '' ? '0' : '0x' + hex); // Big Endian
}
// Used in ff1
// BE: Big Endian, LE: Little Endian
function bytesToNumberBE(bytes) {
return hexToNumber(bytesToHex(bytes));
}
// Used in micro, ff1
function numberToBytesBE(n, len) {
return hexToBytes(n.toString(16).padStart(len * 2, '0'));
}
// TODO: remove
// There is no setImmediate in browser and setTimeout is slow.
// call of async fn will return Promise, which will be fullfiled only on
// next scheduler queue processing step and this is exactly what we need.
const nextTick = async () => { };
exports.nextTick = nextTick;
/**
* Converts string to bytes using UTF8 encoding.
* @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
*/
function utf8ToBytes(str) {
if (typeof str !== 'string')
throw new Error('string expected');
return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
}
/**
* Converts bytes to string using UTF8 encoding.
* @example bytesToUtf8(new Uint8Array([97, 98, 99])) // 'abc'
*/
function bytesToUtf8(bytes) {
return new TextDecoder().decode(bytes);
}
/**
* Normalizes (non-hex) string or Uint8Array to Uint8Array.
* Warning: when Uint8Array is passed, it would NOT get copied.
* Keep in mind for future mutable operations.
*/
function toBytes(data) {
if (typeof data === 'string')
data = utf8ToBytes(data);
else if (isBytes(data))
data = copyBytes(data);
else
throw new Error('Uint8Array expected, got ' + typeof data);
return data;
}
/**
* Checks if two U8A use same underlying buffer and overlaps.
* This is invalid and can corrupt data.
*/
function overlapBytes(a, b) {
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/salse, which designed with this)
*/
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.
*/
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;
}
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 2 uint8array-s in kinda constant time. */
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;
}
// TODO: remove
/** For runtime check if class implements interface. */
class Hash {
}
exports.Hash = Hash;
/**
* Wraps a cipher: validates args, ensures encrypt() can only be called once.
* @__NO_SIDE_EFFECTS__
*/
const wrapCipher = (params, constructor) => {
function wrappedCipher(key, ...args) {
// Validate key
abytes(key);
// Big-Endian hardware is rare. Just in case someone still decides to run ciphers:
if (!exports.isLE)
throw new Error('Non little-endian hardware is not yet supported');
// Validate nonce if nonceLength is present
if (params.nonceLength !== undefined) {
const nonce = args[0];
if (!nonce)
throw new Error('nonce / iv required');
if (params.varSizeNonce)
abytes(nonce);
else
abytes(nonce, params.nonceLength);
}
// Validate AAD if tagLength present
const tagl = params.tagLength;
if (tagl && args[1] !== undefined) {
abytes(args[1]);
}
const cipher = constructor(key, ...args);
const checkOutput = (fnLength, output) => {
if (output !== undefined) {
if (fnLength !== 2)
throw new Error('cipher output not supported');
abytes(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('invalid ciphertext length: smaller than tagLength=' + tagl);
checkOutput(cipher.decrypt.length, output);
return cipher.decrypt(data, output);
},
};
return wrCipher;
}
Object.assign(wrappedCipher, params);
return wrappedCipher;
};
exports.wrapCipher = wrapCipher;
/**
* By default, returns u8a of length.
* When out is available, it checks it for validity and uses it.
*/
function getOutput(expectedLength, out, onlyAligned = true) {
if (out === undefined)
return new Uint8Array(expectedLength);
if (out.length !== expectedLength)
throw new Error('invalid output length, expected ' + expectedLength + ', got: ' + out.length);
if (onlyAligned && !isAligned32(out))
throw new Error('invalid output, must be aligned');
return out;
}
/** Polyfill for Safari 14. */
function setBigUint64(view, byteOffset, value, isLE) {
if (typeof view.setBigUint64 === 'function')
return view.setBigUint64(byteOffset, value, isLE);
const _32n = BigInt(32);
const _u32_max = BigInt(0xffffffff);
const wh = Number((value >> _32n) & _u32_max);
const wl = Number(value & _u32_max);
const h = isLE ? 4 : 0;
const l = isLE ? 0 : 4;
view.setUint32(byteOffset + h, wh, isLE);
view.setUint32(byteOffset + l, wl, isLE);
}
function u64Lengths(dataLength, aadLength, isLE) {
abool(isLE);
const num = new Uint8Array(16);
const view = createView(num);
setBigUint64(view, 0, BigInt(aadLength), isLE);
setBigUint64(view, 8, BigInt(dataLength), isLE);
return num;
}
// Is byte array aligned to 4 byte offset (u32)?
function isAligned32(bytes) {
return bytes.byteOffset % 4 === 0;
}
// copy bytes to new u8a (aligned). Because Buffer.slice is broken.
function copyBytes(bytes) {
return Uint8Array.from(bytes);
}
//# sourceMappingURL=utils.js.map
File diff suppressed because one or more lines are too long
+31
View File
@@ -0,0 +1,31 @@
import { type AsyncCipher, type Cipher } from './utils.ts';
/**
* Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.
*/
export declare function randomBytes(bytesLength?: number): Uint8Array;
export declare function getWebcryptoSubtle(): any;
type RemoveNonceInner<T extends any[], Ret> = ((...args: T) => Ret) extends (arg0: any, arg1: any, ...rest: infer R) => any ? (key: Uint8Array, ...args: R) => Ret : never;
type RemoveNonce<T extends (...args: any) => any> = RemoveNonceInner<Parameters<T>, ReturnType<T>>;
type CipherWithNonce = ((key: Uint8Array, nonce: Uint8Array, ...args: any[]) => Cipher) & {
nonceLength: number;
};
/**
* Uses CSPRG for nonce, nonce injected in ciphertext.
* @example
* const gcm = managedNonce(aes.gcm);
* const ciphr = gcm(key).encrypt(data);
* const plain = gcm(key).decrypt(ciph);
*/
export declare function managedNonce<T extends CipherWithNonce>(fn: T): RemoveNonce<T>;
export declare const utils: {
encrypt: (key: Uint8Array, ...all: any[]) => Promise<Uint8Array>;
decrypt: (key: Uint8Array, ...all: any[]) => Promise<Uint8Array>;
};
/** AES-CBC, native webcrypto version */
export declare const cbc: (key: Uint8Array, iv: Uint8Array) => AsyncCipher;
/** AES-CTR, native webcrypto version */
export declare const ctr: (key: Uint8Array, nonce: Uint8Array) => AsyncCipher;
/** AES-GCM, native webcrypto version */
export declare const gcm: (key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array) => AsyncCipher;
export {};
//# sourceMappingURL=webcrypto.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"webcrypto.d.ts","sourceRoot":"","sources":["src/webcrypto.ts"],"names":[],"mappings":"AAYA,OAAO,EAAmB,KAAK,WAAW,EAAE,KAAK,MAAM,EAAe,MAAM,YAAY,CAAC;AAEzF;;GAEG;AACH,wBAAgB,WAAW,CAAC,WAAW,SAAK,GAAG,UAAU,CASxD;AAED,wBAAgB,kBAAkB,IAAI,GAAG,CAGxC;AAED,KAAK,gBAAgB,CAAC,CAAC,SAAS,GAAG,EAAE,EAAE,GAAG,IAAI,CAAC,CAAC,GAAG,IAAI,EAAE,CAAC,KAAK,GAAG,CAAC,SAAS,CAC1E,IAAI,EAAE,GAAG,EACT,IAAI,EAAE,GAAG,EACT,GAAG,IAAI,EAAE,MAAM,CAAC,KACb,GAAG,GACJ,CAAC,GAAG,EAAE,UAAU,EAAE,GAAG,IAAI,EAAE,CAAC,KAAK,GAAG,GACpC,KAAK,CAAC;AAEV,KAAK,WAAW,CAAC,CAAC,SAAS,CAAC,GAAG,IAAI,EAAE,GAAG,KAAK,GAAG,IAAI,gBAAgB,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC;AACnG,KAAK,eAAe,GAAG,CAAC,CAAC,GAAG,EAAE,UAAU,EAAE,KAAK,EAAE,UAAU,EAAE,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,MAAM,CAAC,GAAG;IACxF,WAAW,EAAE,MAAM,CAAC;CACrB,CAAC;AAEF;;;;;;GAMG;AACH,wBAAgB,YAAY,CAAC,CAAC,SAAS,eAAe,EAAE,EAAE,EAAE,CAAC,GAAG,WAAW,CAAC,CAAC,CAAC,CAiB7E;AAID,eAAO,MAAM,KAAK,EAAE;IAClB,OAAO,EAAE,CAAC,GAAG,EAAE,UAAU,EAAE,GAAG,GAAG,EAAE,GAAG,EAAE,KAAK,OAAO,CAAC,UAAU,CAAC,CAAC;IACjE,OAAO,EAAE,CAAC,GAAG,EAAE,UAAU,EAAE,GAAG,GAAG,EAAE,GAAG,EAAE,KAAK,OAAO,CAAC,UAAU,CAAC,CAAC;CAwBlE,CAAC;AA2CF,wCAAwC;AACxC,eAAO,MAAM,GAAG,EAAE,CAAC,GAAG,EAAE,UAAU,EAAE,EAAE,EAAE,UAAU,KAAK,WAChC,CAAC;AACxB,wCAAwC;AACxC,eAAO,MAAM,GAAG,EAAE,CAAC,GAAG,EAAE,UAAU,EAAE,KAAK,EAAE,UAAU,KAAK,WACnC,CAAC;AACxB,wCAAwC;AACxC,eAAO,MAAM,GAAG,EAAE,CAAC,GAAG,EAAE,UAAU,EAAE,KAAK,EAAE,UAAU,EAAE,GAAG,CAAC,EAAE,UAAU,KAAK,WAC9B,CAAC"}
+141
View File
@@ -0,0 +1,141 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.gcm = exports.ctr = exports.cbc = exports.utils = void 0;
exports.randomBytes = randomBytes;
exports.getWebcryptoSubtle = getWebcryptoSubtle;
exports.managedNonce = managedNonce;
/**
* WebCrypto-based AES gcm/ctr/cbc, `managedNonce` and `randomBytes`.
* We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
* node.js versions earlier than v19 don't declare it in global scope.
* For node.js, package.js on#exports field mapping rewrites import
* from `crypto` to `cryptoNode`, which imports native module.
* Makes the utils un-importable in browsers without a bundler.
* Once node.js 18 is deprecated, we can just drop the import.
* @module
*/
// Use full path so that Node.js can rewrite it to `cryptoNode.js`.
const crypto_1 = require("@noble/ciphers/crypto");
const utils_ts_1 = require("./utils.js");
/**
* Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.
*/
function randomBytes(bytesLength = 32) {
if (crypto_1.crypto && typeof crypto_1.crypto.getRandomValues === 'function') {
return crypto_1.crypto.getRandomValues(new Uint8Array(bytesLength));
}
// Legacy Node.js compatibility
if (crypto_1.crypto && typeof crypto_1.crypto.randomBytes === 'function') {
return Uint8Array.from(crypto_1.crypto.randomBytes(bytesLength));
}
throw new Error('crypto.getRandomValues must be defined');
}
function getWebcryptoSubtle() {
if (crypto_1.crypto && typeof crypto_1.crypto.subtle === 'object' && crypto_1.crypto.subtle != null)
return crypto_1.crypto.subtle;
throw new Error('crypto.subtle must be defined');
}
/**
* Uses CSPRG for nonce, nonce injected in ciphertext.
* @example
* const gcm = managedNonce(aes.gcm);
* const ciphr = gcm(key).encrypt(data);
* const plain = gcm(key).decrypt(ciph);
*/
function managedNonce(fn) {
const { nonceLength } = fn;
(0, utils_ts_1.anumber)(nonceLength);
return ((key, ...args) => ({
encrypt(plaintext, ...argsEnc) {
const nonce = randomBytes(nonceLength);
const ciphertext = fn(key, nonce, ...args).encrypt(plaintext, ...argsEnc);
const out = (0, utils_ts_1.concatBytes)(nonce, ciphertext);
ciphertext.fill(0);
return out;
},
decrypt(ciphertext, ...argsDec) {
const nonce = ciphertext.subarray(0, nonceLength);
const data = ciphertext.subarray(nonceLength);
return fn(key, nonce, ...args).decrypt(data, ...argsDec);
},
}));
}
// Overridable
// @TODO
exports.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 };
if (algo === mode.CTR)
return { name: mode.CTR, counter: nonce, length: 64 };
if (algo === mode.GCM) {
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) {
return (key, nonce, AAD) => {
(0, utils_ts_1.abytes)(key);
(0, utils_ts_1.abytes)(nonce);
const keyParams = { name: algo, length: key.length * 8 };
const cryptParams = getCryptParams(algo, nonce, AAD);
let consumed = false;
return {
// keyLength,
encrypt(plaintext) {
(0, utils_ts_1.abytes)(plaintext);
if (consumed)
throw new Error('Cannot encrypt() twice with same key / nonce');
consumed = true;
return exports.utils.encrypt(key, keyParams, cryptParams, plaintext);
},
decrypt(ciphertext) {
(0, utils_ts_1.abytes)(ciphertext);
return exports.utils.decrypt(key, keyParams, cryptParams, ciphertext);
},
};
};
}
/** AES-CBC, native webcrypto version */
exports.cbc = (() => generate(mode.CBC))();
/** AES-CTR, native webcrypto version */
exports.ctr = (() => generate(mode.CTR))();
/** AES-GCM, native webcrypto version */
exports.gcm =
/* @__PURE__ */ (() => generate(mode.GCM))();
// // 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);
//# sourceMappingURL=webcrypto.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"webcrypto.js","sourceRoot":"","sources":["src/webcrypto.ts"],"names":[],"mappings":"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"}
+21
View 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.
+521
View File
@@ -0,0 +1,521 @@
# noble-hashes
Audited & minimal JS implementation of hash functions, MACs and KDFs.
- 🔒 [**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: chained / sliding window / DoS tests and fuzzing ensure correctness
- 🔁 No unrolled loops: makes it easier to verify and reduces source code size up to 5x
- 🦘 Includes SHA, RIPEMD, BLAKE, HMAC, HKDF, PBKDF, Scrypt, Argon2 & KangarooTwelve
- 🪶 48KB for everything, 4.8KB (2.36KB gzipped) for single-hash build
Take a glance at [GitHub Discussions](https://github.com/paulmillr/noble-hashes/discussions) for questions and support.
The library's initial development was funded by [Ethereum Foundation](https://ethereum.org/).
### 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),
4kb [secp256k1](https://github.com/paulmillr/noble-secp256k1) /
[ed25519](https://github.com/paulmillr/noble-ed25519)
- [Check out homepage](https://paulmillr.com/noble/)
for reading resources, documentation and apps built with noble
## Usage
> `npm install @noble/hashes`
> `deno add jsr:@noble/hashes`
> `deno doc jsr:@noble/hashes` # command-line documentation
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-hashes.js](https://github.com/paulmillr/noble-hashes/releases) is also available.
```js
// import * from '@noble/hashes'; // Error: use sub-imports, to ensure small app size
import { sha256 } from '@noble/hashes/sha2.js'; // ESM & Common.js
sha256(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // returns Uint8Array
// Available modules
import { sha256, sha384, sha512, sha224, sha512_224, sha512_256 } from '@noble/hashes/sha2.js';
import { sha3_256, sha3_512, keccak_256, keccak_512, shake128, shake256 } from '@noble/hashes/sha3.js';
import { cshake256, turboshake256, kmac256, tuplehash256, k12, m14, keccakprg } from '@noble/hashes/sha3-addons.js';
import { blake3 } from '@noble/hashes/blake3.js';
import { blake2b, blake2s } from '@noble/hashes/blake2.js';
import { blake256, blake512 } from '@noble/hashes/blake1.js';
import { sha1, md5, ripemd160 } from '@noble/hashes/legacy.js';
import { hmac } from '@noble/hashes/hmac.js';
import { hkdf } from '@noble/hashes/hkdf.js';
import { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2.js';
import { scrypt, scryptAsync } from '@noble/hashes/scrypt.js';
import { argon2d, argon2i, argon2id } from '@noble/hashes/argon2.js';
import * as utils from '@noble/hashes/utils'; // bytesToHex, bytesToUtf8, concatBytes...
```
- [sha2: sha256, sha384, sha512](#sha2-sha256-sha384-sha512-and-others)
- [sha3: FIPS, SHAKE, Keccak](#sha3-fips-shake-keccak)
- [sha3-addons: cSHAKE, KMAC, K12, M14, TurboSHAKE](#sha3-addons-cshake-kmac-k12-m14-turboshake)
- [blake, blake2, blake3](#blake-blake2-blake3) | [legacy: sha1, md5, ripemd160](#legacy-sha1-md5-ripemd160)
- MACs: [hmac](#hmac) | [sha3-addons kmac](#sha3-addons-cshake-kmac-k12-m14-turboshake) | [blake3 key mode](#blake2b-blake2s-blake3)
- KDFs: [hkdf](#hkdf) | [pbkdf2](#pbkdf2) | [scrypt](#scrypt) | [argon2](#argon2)
- [utils](#utils)
- [Security](#security) | [Speed](#speed) | [Contributing & testing](#contributing--testing) | [License](#license)
### Implementations
Hash functions:
- `sha256()`: receive & return `Uint8Array`
- `sha256.create().update(a).update(b).digest()`: support partial updates
- `blake3.create({ context: 'e', dkLen: 32 })`: sometimes have options
- support little-endian architecture; also experimentally big-endian
- can hash up to 4GB per chunk, with any amount of chunks
#### sha2: sha256, sha384, sha512 and others
```typescript
import { sha224, sha256, sha384, sha512, sha512_224, sha512_256 } from '@noble/hashes/sha2.js';
const res = sha256(Uint8Array.from([0xbc])); // basic
for (let hash of [sha256, sha384, sha512, sha224, sha512_224, sha512_256]) {
const arr = Uint8Array.from([0x10, 0x20, 0x30]);
const a = hash(arr);
const b = hash.create().update(arr).digest();
}
```
See [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and
[the paper on truncated SHA512/256](https://eprint.iacr.org/2010/548.pdf).
#### sha3: FIPS, SHAKE, Keccak
```typescript
import {
keccak_224, keccak_256, keccak_384, keccak_512,
sha3_224, sha3_256, sha3_384, sha3_512,
shake128, shake256,
} from '@noble/hashes/sha3.js';
for (let hash of [
sha3_224, sha3_256, sha3_384, sha3_512,
keccak_224, keccak_256, keccak_384, keccak_512,
]) {
const arr = Uint8Array.from([0x10, 0x20, 0x30]);
const a = hash(arr);
const b = hash.create().update(arr).digest();
}
const shka = shake128(Uint8Array.from([0x10]), { dkLen: 512 });
const shkb = shake256(Uint8Array.from([0x30]), { dkLen: 512 });
```
See [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),
[Website](https://keccak.team/keccak.html).
Check out [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub)
#### sha3-addons: cSHAKE, KMAC, K12, M14, TurboSHAKE
```typescript
import {
cshake128, cshake256,
k12,
keccakprg,
kmac128, kmac256,
m14,
parallelhash256,
tuplehash256,
turboshake128, turboshake256
} from '@noble/hashes/sha3-addons.js';
const data = Uint8Array.from([0x10, 0x20, 0x30]);
const ec1 = cshake128(data, { personalization: 'def' });
const ec2 = cshake256(data, { personalization: 'def' });
const et1 = turboshake128(data);
const et2 = turboshake256(data, { D: 0x05 });
// tuplehash(['ab', 'c']) !== tuplehash(['a', 'bc']) !== tuplehash([data])
const et3 = tuplehash256([utf8ToBytes('ab'), utf8ToBytes('c')]);
// Not parallel in JS (similar to blake3 / k12), added for compat
const ep1 = parallelhash256(data, { blockLen: 8 });
const kk = Uint8Array.from([0xca]);
const ek10 = kmac128(kk, data);
const ek11 = kmac256(kk, data);
const ek12 = k12(data);
const ek13 = m14(data);
// pseudo-random generator, first argument is capacity. XKCP recommends 254 bits capacity for 128-bit security strength.
// * with a capacity of 254 bits.
const p = keccakprg(254);
p.feed('test');
const rand1b = p.fetch(1);
```
- Full [NIST SP 800-185](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-185.pdf):
cSHAKE, KMAC, TupleHash, ParallelHash + XOF variants
- [Reduced-round Keccak](https://datatracker.ietf.org/doc/draft-irtf-cfrg-kangarootwelve/):
- 🦘 K12 aka KangarooTwelve
- M14 aka MarsupilamiFourteen
- TurboSHAKE
- [KeccakPRG](https://keccak.team/files/CSF-0.1.pdf): Pseudo-random generator based on Keccak
#### blake, blake2, blake3
```typescript
import { blake224, blake256, blake384, blake512 } from '@noble/hashes/blake1.js';
import { blake2b, blake2s } from '@noble/hashes/blake2.js';
import { blake3 } from '@noble/hashes/blake3.js';
for (let hash of [
blake224, blake256, blake384, blake512,
blake2b, blake2s, blake3
]) {
const arr = Uint8Array.from([0x10, 0x20, 0x30]);
const a = hash(arr);
const b = hash.create().update(arr).digest();
}
// blake2 advanced usage
const ab = Uint8Array.from([0x01]);
blake2s(ab);
blake2s(ab, { key: new Uint8Array(32) });
blake2s(ab, { personalization: 'pers1234' });
blake2s(ab, { salt: 'salt1234' });
blake2b(ab);
blake2b(ab, { key: new Uint8Array(64) });
blake2b(ab, { personalization: 'pers1234pers1234' });
blake2b(ab, { salt: 'salt1234salt1234' });
// blake3 advanced usage
blake3(ab);
blake3(ab, { dkLen: 256 });
blake3(ab, { key: new Uint8Array(32) });
blake3(ab, { context: 'application-name' });
```
- Blake1 is legacy hash, one of SHA3 proposals. It is rarely used anywhere. See [pdf](https://www.aumasson.jp/blake/blake.pdf).
- Blake2 is popular fast hash. blake2b focuses on 64-bit platforms while blake2s is for 8-bit to 32-bit ones. See [RFC 7693](https://datatracker.ietf.org/doc/html/rfc7693), [Website](https://www.blake2.net)
- Blake3 is faster, reduced-round blake2. See [Website & specs](https://blake3.io)
#### legacy: sha1, md5, ripemd160
SHA1 (RFC 3174), MD5 (RFC 1321) and RIPEMD160 (RFC 2286) legacy, weak hash functions.
Don't use them in a new protocol. What "weak" means:
- Collisions can be made with 2^18 effort in MD5, 2^60 in SHA1, 2^80 in RIPEMD160.
- No practical pre-image attacks (only theoretical, 2^123.4)
- HMAC seems kinda ok: https://datatracker.ietf.org/doc/html/rfc6151
```typescript
import { md5, ripemd160, sha1 } from '@noble/hashes/legacy.js';
for (let hash of [md5, ripemd160, sha1]) {
const arr = Uint8Array.from([0x10, 0x20, 0x30]);
const a = hash(arr);
const b = hash.create().update(arr).digest();
}
```
#### hmac
```typescript
import { hmac } from '@noble/hashes/hmac.js';
import { sha256 } from '@noble/hashes/sha2.js';
const key = new Uint8Array(32).fill(1);
const msg = new Uint8Array(32).fill(2);
const mac1 = hmac(sha256, key, msg);
const mac2 = hmac.create(sha256, key).update(msg).digest();
```
Matches [RFC 2104](https://datatracker.ietf.org/doc/html/rfc2104).
#### hkdf
```typescript
import { hkdf } from '@noble/hashes/hkdf.js';
import { randomBytes } from '@noble/hashes/utils.js';
import { sha256 } from '@noble/hashes/sha2.js';
const inputKey = randomBytes(32);
const salt = randomBytes(32);
const info = 'application-key';
const hk1 = hkdf(sha256, inputKey, salt, info, 32);
// == same as
import { extract, expand } from '@noble/hashes/hkdf.js';
import { sha256 } from '@noble/hashes/sha2.js';
const prk = extract(sha256, inputKey, salt);
const hk2 = expand(sha256, prk, info, 32);
```
Matches [RFC 5869](https://datatracker.ietf.org/doc/html/rfc5869).
#### pbkdf2
```typescript
import { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2.js';
import { sha256 } from '@noble/hashes/sha2.js';
const pbkey1 = pbkdf2(sha256, 'password', 'salt', { c: 32, dkLen: 32 });
const pbkey2 = await pbkdf2Async(sha256, 'password', 'salt', { c: 32, dkLen: 32 });
const pbkey3 = await pbkdf2Async(sha256, Uint8Array.from([1, 2, 3]), Uint8Array.from([4, 5, 6]), {
c: 32,
dkLen: 32,
});
```
Matches [RFC 2898](https://datatracker.ietf.org/doc/html/rfc2898).
#### scrypt
```typescript
import { scrypt, scryptAsync } from '@noble/hashes/scrypt.js';
const scr1 = scrypt('password', 'salt', { N: 2 ** 16, r: 8, p: 1, dkLen: 32 });
const scr2 = await scryptAsync('password', 'salt', { N: 2 ** 16, r: 8, p: 1, dkLen: 32 });
const scr3 = await scryptAsync(Uint8Array.from([1, 2, 3]), Uint8Array.from([4, 5, 6]), {
N: 2 ** 17,
r: 8,
p: 1,
dkLen: 32,
onProgress(percentage) {
console.log('progress', percentage);
},
maxmem: 2 ** 32 + 128 * 8 * 1, // N * r * p * 128 + (128*r*p)
});
```
Conforms to [RFC 7914](https://datatracker.ietf.org/doc/html/rfc7914),
[Website](https://www.tarsnap.com/scrypt.html)
- `N, r, p` are work factors. To understand them, see [the blog post](https://blog.filippo.io/the-scrypt-parameters/).
`r: 8, p: 1` are common. JS doesn't support parallelization, making increasing p meaningless.
- `dkLen` is the length of output bytes e.g. `32` or `64`
- `onProgress` can be used with async version of the function to report progress to a user.
- `maxmem` prevents DoS and is limited to `1GB + 1KB` (`2**30 + 2**10`), but can be adjusted using formula: `N * r * p * 128 + (128 * r * p)`
Time it takes to derive Scrypt key under different values of N (2\*\*N) on Apple M4 (mobile phones can be 1x-4x slower):
| N pow | Time | RAM |
| ----- | ---- | ----- |
| 16 | 0.1s | 64MB |
| 17 | 0.2s | 128MB |
| 18 | 0.4s | 256MB |
| 19 | 0.8s | 512MB |
| 20 | 1.5s | 1GB |
| 21 | 3.1s | 2GB |
| 22 | 6.2s | 4GB |
| 23 | 13s | 8GB |
| 24 | 27s | 16GB |
> [!NOTE]
> We support N larger than `2**20` where available, however,
> not all JS engines support >= 2GB ArrayBuffer-s.
> When using such N, you'll need to manually adjust `maxmem`, using formula above.
> Other JS implementations don't support large N-s.
#### argon2
```ts
import { argon2d, argon2i, argon2id } from '@noble/hashes/argon2.js';
const arg1 = argon2id('password', 'saltsalt', { t: 2, m: 65536, p: 1, maxmem: 2 ** 32 - 1 });
```
Argon2 [RFC 9106](https://datatracker.ietf.org/doc/html/rfc9106) implementation.
> [!WARNING]
> Argon2 can't be fast in JS, because there is no fast Uint64Array.
> It is suggested to use [Scrypt](#scrypt) instead.
> Being 5x slower than native code means brute-forcing attackers have bigger advantage.
#### utils
```typescript
import { bytesToHex as toHex, randomBytes } from '@noble/hashes/utils';
console.log(toHex(randomBytes(32)));
```
- `bytesToHex` will convert `Uint8Array` to a hex string
- `randomBytes(bytes)` will produce cryptographically secure random `Uint8Array` of length `bytes`
## Security
The library has been independently audited:
- at version 1.0.0, in Jan 2022, by [Cure53](https://cure53.de)
- PDFs: [website](https://cure53.de/pentest-report_hashing-libs.pdf), [in-repo](./audit/2022-01-05-cure53-audit-nbl2.pdf)
- [Changes since audit](https://github.com/paulmillr/noble-hashes/compare/1.0.0..main).
- Scope: everything, besides `blake3`, `sha3-addons`, `sha1` and `argon2`, which have not been audited
- The audit has been funded by [Ethereum Foundation](https://ethereum.org/en/) with help of [Nomic Labs](https://nomiclabs.io)
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.
### Memory dumping
The library shares state buffers between hash
function calls. The buffers are zeroed-out after each call. However, if an attacker
can read application memory, you are doomed in any case:
- At some point, input will be a string and strings are immutable in JS:
there is no way to overwrite them with zeros. For example: deriving
key from `scrypt(password, salt)` where password and salt are strings
- Input from a file will stay in file buffers
- Input / output will be re-used multiple times in application which means it could stay in memory
- `await anything()` will always write all internal variables (including numbers)
to memory. With async functions / Promises there are no guarantees when the code
chunk would be executed. Which means attacker can have plenty of time to read data from memory
- There is no way to guarantee anything about zeroing sensitive data without
complex tests-suite which will dump process memory and verify that there is
no sensitive data left. For JS it means testing all browsers (incl. mobile),
which is complex. And of course it will be useless without using the same
test-suite in the actual application that consumes the library
### Supply chain security
- **Commits** are signed with PGP keys, to prevent forgery. Make sure to verify commit signatures
- **Releases** are transparent and built on GitHub CI. Make sure to verify [provenance](https://docs.npmjs.com/generating-provenance-statements) logs
- Use GitHub CLI to verify single-file builds:
`gh attestation verify --owner paulmillr noble-hashes.js`
- **Rare releasing** is followed to ensure less re-audit need for end-users
- **Dependencies** are minimized and locked-down: any dependency could get hacked and users will be downloading malware with every install.
- We make sure to use as few dependencies as possible
- Automatic dep updates are prevented by locking-down version ranges; diffs are checked with `npm-diff`
- **Dev Dependencies** are disabled for end-users; they are only used to develop / build the source code
For this package, there are 0 dependencies; and a few dev dependencies:
- micro-bmark, micro-should and jsbt are 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. It's hard to audit their source code thoroughly and fully because of their size
### Randomness
We're deferring to built-in
[crypto.getRandomValues](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues)
which is considered cryptographically secure (CSPRNG).
In the past, browsers had bugs that made it weak: it may happen again.
Implementing a userspace CSPRNG to get resilient to the weakness
is even worse: there is no reliable userspace source of quality entropy.
### Quantum computers
Cryptographically relevant quantum computer, if built, will allow to
utilize Grover's algorithm to break hashes in 2^n/2 operations, instead of 2^n.
This means SHA256 should be replaced with SHA512, SHA3-256 with SHA3-512, SHAKE128 with SHAKE256 etc.
Australian ASD prohibits SHA256 and similar hashes [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:install && npm run bench
```
Benchmarks measured on Apple M4.
```
# 32B
sha256 x 1,968,503 ops/sec @ 508ns/op
sha512 x 740,740 ops/sec @ 1μs/op
sha3_256 x 287,686 ops/sec @ 3μs/op
sha3_512 x 288,267 ops/sec @ 3μs/op
k12 x 476,190 ops/sec @ 2μs/op
m14 x 423,190 ops/sec @ 2μs/op
blake2b x 464,252 ops/sec @ 2μs/op
blake2s x 766,871 ops/sec @ 1μs/op
blake3 x 879,507 ops/sec @ 1μs/op
# 1MB
sha256 x 331 ops/sec @ 3ms/op
sha512 x 129 ops/sec @ 7ms/op
sha3_256 x 38 ops/sec @ 25ms/op
sha3_512 x 20 ops/sec @ 47ms/op
k12 x 88 ops/sec @ 11ms/op
m14 x 62 ops/sec @ 15ms/op
blake2b x 69 ops/sec @ 14ms/op
blake2s x 57 ops/sec @ 17ms/op
blake3 x 72 ops/sec @ 13ms/op
# MAC
hmac(sha256) x 599,880 ops/sec @ 1μs/op
hmac(sha512) x 197,122 ops/sec @ 5μs/op
kmac256 x 87,981 ops/sec @ 11μs/op
blake3(key) x 796,812 ops/sec @ 1μs/op
# KDF
hkdf(sha256) x 259,942 ops/sec @ 3μs/op
blake3(context) x 424,808 ops/sec @ 2μs/op
pbkdf2(sha256, c: 2 ** 18) x 5 ops/sec @ 197ms/op
pbkdf2(sha512, c: 2 ** 18) x 1 ops/sec @ 630ms/op
scrypt(n: 2 ** 18, r: 8, p: 1) x 2 ops/sec @ 400ms/op
argon2id(t: 1, m: 256MB) 2881ms
```
Compare to native node.js implementation that uses C bindings instead of pure-js code:
```
# native (node) 32B
sha256 x 2,267,573 ops/sec
sha512 x 983,284 ops/sec
sha3_256 x 1,522,070 ops/sec
blake2b x 1,512,859 ops/sec
blake2s x 1,821,493 ops/sec
hmac(sha256) x 1,085,776 ops/sec
hkdf(sha256) x 312,109 ops/sec
# native (node) KDF
pbkdf2(sha256, c: 2 ** 18) x 5 ops/sec @ 197ms/op
pbkdf2(sha512, c: 2 ** 18) x 1 ops/sec @ 630ms/op
scrypt(n: 2 ** 18, r: 8, p: 1) x 2 ops/sec @ 378ms/op
```
It is possible to [make this library 4x+ faster](./benchmark/README.md) by
_doing code generation of full loop unrolls_. We've decided against it. Reasons:
- the library must be auditable, with minimum amount of code, and zero dependencies
- most method invocations with the lib are going to be something like hashing 32b to 64kb of data
- hashing big inputs is 10x faster with low-level languages, which means you should probably pick 'em instead
The current performance is good enough when compared to other projects; SHA256 takes only 900 nanoseconds to run.
## Contributing & testing
`test/misc` directory contains implementations of loop unrolling and md5.
- `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, which may need their deps first (`npm run bench:install`)
- `npm run build:release` will build single file
- There is **additional** 20-min DoS test `npm run test:dos` and 2-hour "big" multicore test `npm run test:big`.
See [our approach to testing](./test/README.md)
Additional resources:
- NTT hashes are outside of scope of the library. You can view some of them in different repos:
- [Pedersen in micro-zk-proofs](https://github.com/paulmillr/micro-zk-proofs/blob/1ed5ce1253583b2e540eef7f3477fb52bf5344ff/src/pedersen.ts)
- [Poseidon in noble-curves](https://github.com/paulmillr/noble-curves/blob/3d124dd3ecec8b6634cc0b2ba1c183aded5304f9/src/abstract/poseidon.ts)
- Check out [guidelines](https://github.com/paulmillr/guidelines) for coding practices
- 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) 2022 Paul Miller [(https://paulmillr.com)](https://paulmillr.com)
See LICENSE file.
+17
View File
@@ -0,0 +1,17 @@
/**
* Internal assertion helpers.
* @module
* @deprecated
*/
import { abytes as ab, aexists as ae, anumber as an, aoutput as ao, type IHash as H } from './utils.ts';
/** @deprecated Use import from `noble/hashes/utils` module */
export declare const abytes: typeof ab;
/** @deprecated Use import from `noble/hashes/utils` module */
export declare const aexists: typeof ae;
/** @deprecated Use import from `noble/hashes/utils` module */
export declare const anumber: typeof an;
/** @deprecated Use import from `noble/hashes/utils` module */
export declare const aoutput: typeof ao;
/** @deprecated Use import from `noble/hashes/utils` module */
export type Hash = H;
//# sourceMappingURL=_assert.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"_assert.d.ts","sourceRoot":"","sources":["src/_assert.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EACL,MAAM,IAAI,EAAE,EACZ,OAAO,IAAI,EAAE,EACb,OAAO,IAAI,EAAE,EACb,OAAO,IAAI,EAAE,EACb,KAAK,KAAK,IAAI,CAAC,EAChB,MAAM,YAAY,CAAC;AACpB,8DAA8D;AAC9D,eAAO,MAAM,MAAM,EAAE,OAAO,EAAO,CAAC;AACpC,8DAA8D;AAC9D,eAAO,MAAM,OAAO,EAAE,OAAO,EAAO,CAAC;AACrC,8DAA8D;AAC9D,eAAO,MAAM,OAAO,EAAE,OAAO,EAAO,CAAC;AACrC,8DAA8D;AAC9D,eAAO,MAAM,OAAO,EAAE,OAAO,EAAO,CAAC;AACrC,8DAA8D;AAC9D,MAAM,MAAM,IAAI,GAAG,CAAC,CAAC"}
+18
View File
@@ -0,0 +1,18 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.aoutput = exports.anumber = exports.aexists = exports.abytes = void 0;
/**
* Internal assertion helpers.
* @module
* @deprecated
*/
const utils_ts_1 = require("./utils.js");
/** @deprecated Use import from `noble/hashes/utils` module */
exports.abytes = utils_ts_1.abytes;
/** @deprecated Use import from `noble/hashes/utils` module */
exports.aexists = utils_ts_1.aexists;
/** @deprecated Use import from `noble/hashes/utils` module */
exports.anumber = utils_ts_1.anumber;
/** @deprecated Use import from `noble/hashes/utils` module */
exports.aoutput = utils_ts_1.aoutput;
//# sourceMappingURL=_assert.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"_assert.js","sourceRoot":"","sources":["src/_assert.ts"],"names":[],"mappings":";;;AAAA;;;;GAIG;AACH,yCAMoB;AACpB,8DAA8D;AACjD,QAAA,MAAM,GAAc,iBAAE,CAAC;AACpC,8DAA8D;AACjD,QAAA,OAAO,GAAc,kBAAE,CAAC;AACrC,8DAA8D;AACjD,QAAA,OAAO,GAAc,kBAAE,CAAC;AACrC,8DAA8D;AACjD,QAAA,OAAO,GAAc,kBAAE,CAAC"}
+14
View File
@@ -0,0 +1,14 @@
/**
* Internal blake variable.
* For BLAKE2b, the two extra permutations for rounds 10 and 11 are SIGMA[10..11] = SIGMA[0..1].
*/
export declare const BSIGMA: Uint8Array;
export type Num4 = {
a: number;
b: number;
c: number;
d: number;
};
export declare function G1s(a: number, b: number, c: number, d: number, x: number): Num4;
export declare function G2s(a: number, b: number, c: number, d: number, x: number): Num4;
//# sourceMappingURL=_blake.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"_blake.d.ts","sourceRoot":"","sources":["src/_blake.ts"],"names":[],"mappings":"AAMA;;;GAGG;AAEH,eAAO,MAAM,MAAM,EAAE,UAkBnB,CAAC;AAGH,MAAM,MAAM,IAAI,GAAG;IAAE,CAAC,EAAE,MAAM,CAAC;IAAC,CAAC,EAAE,MAAM,CAAC;IAAC,CAAC,EAAE,MAAM,CAAC;IAAC,CAAC,EAAE,MAAM,CAAC;CAAE,CAAC;AAGnE,wBAAgB,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,IAAI,CAM/E;AAED,wBAAgB,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,IAAI,CAM/E"}
+50
View File
@@ -0,0 +1,50 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BSIGMA = void 0;
exports.G1s = G1s;
exports.G2s = G2s;
/**
* Internal helpers for blake hash.
* @module
*/
const utils_ts_1 = require("./utils.js");
/**
* Internal blake variable.
* For BLAKE2b, the two extra permutations for rounds 10 and 11 are SIGMA[10..11] = SIGMA[0..1].
*/
// prettier-ignore
exports.BSIGMA = Uint8Array.from([
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3,
11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4,
7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8,
9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13,
2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9,
12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11,
13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10,
6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5,
10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3,
// Blake1, unused in others
11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4,
7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8,
9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13,
2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9,
]);
// Mixing function G splitted in two halfs
function G1s(a, b, c, d, x) {
a = (a + b + x) | 0;
d = (0, utils_ts_1.rotr)(d ^ a, 16);
c = (c + d) | 0;
b = (0, utils_ts_1.rotr)(b ^ c, 12);
return { a, b, c, d };
}
function G2s(a, b, c, d, x) {
a = (a + b + x) | 0;
d = (0, utils_ts_1.rotr)(d ^ a, 8);
c = (c + d) | 0;
b = (0, utils_ts_1.rotr)(b ^ c, 7);
return { a, b, c, d };
}
//# sourceMappingURL=_blake.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"_blake.js","sourceRoot":"","sources":["src/_blake.ts"],"names":[],"mappings":";;;AAmCA,kBAMC;AAED,kBAMC;AAjDD;;;GAGG;AACH,yCAAkC;AAElC;;;GAGG;AACH,kBAAkB;AACL,QAAA,MAAM,GAA+B,UAAU,CAAC,IAAI,CAAC;IAChE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE;IACpD,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IACpD,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IACpD,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC;IACpD,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE;IACpD,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC;IACpD,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE;IACpD,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE;IACpD,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC;IACpD,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC;IACpD,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE;IACpD,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IACpD,2BAA2B;IAC3B,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IACpD,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC;IACpD,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE;IACpD,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC;CACrD,CAAC,CAAC;AAKH,0CAA0C;AAC1C,SAAgB,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS;IACvE,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;IACpB,CAAC,GAAG,IAAA,eAAI,EAAC,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC;IACpB,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;IAChB,CAAC,GAAG,IAAA,eAAI,EAAC,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC;IACpB,OAAO,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;AACxB,CAAC;AAED,SAAgB,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS;IACvE,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;IACpB,CAAC,GAAG,IAAA,eAAI,EAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC;IACnB,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;IAChB,CAAC,GAAG,IAAA,eAAI,EAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC;IACnB,OAAO,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;AACxB,CAAC"}
+51
View File
@@ -0,0 +1,51 @@
/**
* Internal Merkle-Damgard hash utils.
* @module
*/
import { type Input, Hash } from './utils.ts';
/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */
export declare function setBigUint64(view: DataView, byteOffset: number, value: bigint, isLE: boolean): void;
/** Choice: a ? b : c */
export declare function Chi(a: number, b: number, c: number): number;
/** Majority function, true if any two inputs is true. */
export declare function Maj(a: number, b: number, c: number): number;
/**
* Merkle-Damgard hash construction base class.
* Could be used to create MD5, RIPEMD, SHA1, SHA2.
*/
export declare abstract class HashMD<T extends HashMD<T>> extends Hash<T> {
protected abstract process(buf: DataView, offset: number): void;
protected abstract get(): number[];
protected abstract set(...args: number[]): void;
abstract destroy(): void;
protected abstract roundClean(): void;
readonly blockLen: number;
readonly outputLen: number;
readonly padOffset: number;
readonly isLE: boolean;
protected buffer: Uint8Array;
protected view: DataView;
protected finished: boolean;
protected length: number;
protected pos: number;
protected destroyed: boolean;
constructor(blockLen: number, outputLen: number, padOffset: number, isLE: boolean);
update(data: Input): this;
digestInto(out: Uint8Array): void;
digest(): Uint8Array;
_cloneInto(to?: T): T;
clone(): T;
}
/**
* Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
* Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
*/
/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */
export declare const SHA256_IV: Uint32Array;
/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */
export declare const SHA224_IV: Uint32Array;
/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */
export declare const SHA384_IV: Uint32Array;
/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */
export declare const SHA512_IV: Uint32Array;
//# sourceMappingURL=_md.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"_md.d.ts","sourceRoot":"","sources":["src/_md.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,KAAK,KAAK,EAAE,IAAI,EAAwD,MAAM,YAAY,CAAC;AAEpG,gGAAgG;AAChG,wBAAgB,YAAY,CAC1B,IAAI,EAAE,QAAQ,EACd,UAAU,EAAE,MAAM,EAClB,KAAK,EAAE,MAAM,EACb,IAAI,EAAE,OAAO,GACZ,IAAI,CAUN;AAED,wBAAwB;AACxB,wBAAgB,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CAE3D;AAED,yDAAyD;AACzD,wBAAgB,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CAE3D;AAED;;;GAGG;AACH,8BAAsB,MAAM,CAAC,CAAC,SAAS,MAAM,CAAC,CAAC,CAAC,CAAE,SAAQ,IAAI,CAAC,CAAC,CAAC;IAC/D,SAAS,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI;IAC/D,SAAS,CAAC,QAAQ,CAAC,GAAG,IAAI,MAAM,EAAE;IAClC,SAAS,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,IAAI,EAAE,MAAM,EAAE,GAAG,IAAI;IAC/C,QAAQ,CAAC,OAAO,IAAI,IAAI;IACxB,SAAS,CAAC,QAAQ,CAAC,UAAU,IAAI,IAAI;IAErC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC;IAGvB,SAAS,CAAC,MAAM,EAAE,UAAU,CAAC;IAC7B,SAAS,CAAC,IAAI,EAAE,QAAQ,CAAC;IACzB,SAAS,CAAC,QAAQ,UAAS;IAC3B,SAAS,CAAC,MAAM,SAAK;IACrB,SAAS,CAAC,GAAG,SAAK;IAClB,SAAS,CAAC,SAAS,UAAS;gBAEhB,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO;IASjF,MAAM,CAAC,IAAI,EAAE,KAAK,GAAG,IAAI;IA0BzB,UAAU,CAAC,GAAG,EAAE,UAAU,GAAG,IAAI;IAkCjC,MAAM,IAAI,UAAU;IAOpB,UAAU,CAAC,EAAE,CAAC,EAAE,CAAC,GAAG,CAAC;IAWrB,KAAK,IAAI,CAAC;CAGX;AAED;;;GAGG;AAEH,4EAA4E;AAC5E,eAAO,MAAM,SAAS,EAAE,WAEtB,CAAC;AAEH,8EAA8E;AAC9E,eAAO,MAAM,SAAS,EAAE,WAEtB,CAAC;AAEH,6EAA6E;AAC7E,eAAO,MAAM,SAAS,EAAE,WAGtB,CAAC;AAEH,4EAA4E;AAC5E,eAAO,MAAM,SAAS,EAAE,WAGtB,CAAC"}
+162
View File
@@ -0,0 +1,162 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SHA512_IV = exports.SHA384_IV = exports.SHA224_IV = exports.SHA256_IV = exports.HashMD = void 0;
exports.setBigUint64 = setBigUint64;
exports.Chi = Chi;
exports.Maj = Maj;
/**
* Internal Merkle-Damgard hash utils.
* @module
*/
const utils_ts_1 = require("./utils.js");
/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */
function setBigUint64(view, byteOffset, value, isLE) {
if (typeof view.setBigUint64 === 'function')
return view.setBigUint64(byteOffset, value, isLE);
const _32n = BigInt(32);
const _u32_max = BigInt(0xffffffff);
const wh = Number((value >> _32n) & _u32_max);
const wl = Number(value & _u32_max);
const h = isLE ? 4 : 0;
const l = isLE ? 0 : 4;
view.setUint32(byteOffset + h, wh, isLE);
view.setUint32(byteOffset + l, wl, isLE);
}
/** Choice: a ? b : c */
function Chi(a, b, c) {
return (a & b) ^ (~a & c);
}
/** Majority function, true if any two inputs is true. */
function Maj(a, b, c) {
return (a & b) ^ (a & c) ^ (b & c);
}
/**
* Merkle-Damgard hash construction base class.
* Could be used to create MD5, RIPEMD, SHA1, SHA2.
*/
class HashMD extends utils_ts_1.Hash {
constructor(blockLen, outputLen, padOffset, isLE) {
super();
this.finished = false;
this.length = 0;
this.pos = 0;
this.destroyed = false;
this.blockLen = blockLen;
this.outputLen = outputLen;
this.padOffset = padOffset;
this.isLE = isLE;
this.buffer = new Uint8Array(blockLen);
this.view = (0, utils_ts_1.createView)(this.buffer);
}
update(data) {
(0, utils_ts_1.aexists)(this);
data = (0, utils_ts_1.toBytes)(data);
(0, utils_ts_1.abytes)(data);
const { view, 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, cast it to view and process
if (take === blockLen) {
const dataView = (0, utils_ts_1.createView)(data);
for (; blockLen <= len - pos; pos += blockLen)
this.process(dataView, pos);
continue;
}
buffer.set(data.subarray(pos, pos + take), this.pos);
this.pos += take;
pos += take;
if (this.pos === blockLen) {
this.process(view, 0);
this.pos = 0;
}
}
this.length += data.length;
this.roundClean();
return this;
}
digestInto(out) {
(0, utils_ts_1.aexists)(this);
(0, utils_ts_1.aoutput)(out, this);
this.finished = true;
// Padding
// We can avoid allocation of buffer for padding completely if it
// was previously not allocated here. But it won't change performance.
const { buffer, view, blockLen, isLE } = this;
let { pos } = this;
// append the bit '1' to the message
buffer[pos++] = 0b10000000;
(0, utils_ts_1.clean)(this.buffer.subarray(pos));
// we have less than padOffset left in buffer, so we cannot put length in
// current block, need process it and pad again
if (this.padOffset > blockLen - pos) {
this.process(view, 0);
pos = 0;
}
// Pad until full block byte with zeros
for (let i = pos; i < blockLen; i++)
buffer[i] = 0;
// Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that
// You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.
// So we just write lowest 64 bits of that value.
setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
this.process(view, 0);
const oview = (0, utils_ts_1.createView)(out);
const len = this.outputLen;
// NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT
if (len % 4)
throw new Error('_sha2: outputLen should be aligned to 32bit');
const outLen = len / 4;
const state = this.get();
if (outLen > state.length)
throw new Error('_sha2: outputLen bigger than state');
for (let i = 0; i < outLen; i++)
oview.setUint32(4 * i, state[i], isLE);
}
digest() {
const { buffer, outputLen } = this;
this.digestInto(buffer);
const res = buffer.slice(0, outputLen);
this.destroy();
return res;
}
_cloneInto(to) {
to || (to = new this.constructor());
to.set(...this.get());
const { blockLen, buffer, length, finished, destroyed, pos } = this;
to.destroyed = destroyed;
to.finished = finished;
to.length = length;
to.pos = pos;
if (length % blockLen)
to.buffer.set(buffer);
return to;
}
clone() {
return this._cloneInto();
}
}
exports.HashMD = HashMD;
/**
* Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
* Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
*/
/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */
exports.SHA256_IV = Uint32Array.from([
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
]);
/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */
exports.SHA224_IV = Uint32Array.from([
0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,
]);
/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */
exports.SHA384_IV = Uint32Array.from([
0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,
0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,
]);
/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */
exports.SHA512_IV = Uint32Array.from([
0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,
0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,
]);
//# sourceMappingURL=_md.js.map
File diff suppressed because one or more lines are too long
+55
View File
@@ -0,0 +1,55 @@
declare function fromBig(n: bigint, le?: boolean): {
h: number;
l: number;
};
declare function split(lst: bigint[], le?: boolean): Uint32Array[];
declare const toBig: (h: number, l: number) => bigint;
declare const shrSH: (h: number, _l: number, s: number) => number;
declare const shrSL: (h: number, l: number, s: number) => number;
declare const rotrSH: (h: number, l: number, s: number) => number;
declare const rotrSL: (h: number, l: number, s: number) => number;
declare const rotrBH: (h: number, l: number, s: number) => number;
declare const rotrBL: (h: number, l: number, s: number) => number;
declare const rotr32H: (_h: number, l: number) => number;
declare const rotr32L: (h: number, _l: number) => number;
declare const rotlSH: (h: number, l: number, s: number) => number;
declare const rotlSL: (h: number, l: number, s: number) => number;
declare const rotlBH: (h: number, l: number, s: number) => number;
declare const rotlBL: (h: number, l: number, s: number) => number;
declare function add(Ah: number, Al: number, Bh: number, Bl: number): {
h: number;
l: number;
};
declare const add3L: (Al: number, Bl: number, Cl: number) => number;
declare const add3H: (low: number, Ah: number, Bh: number, Ch: number) => number;
declare const add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number;
declare const add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number;
declare const add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number;
declare const add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number;
export { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig };
declare const u64: {
fromBig: typeof fromBig;
split: typeof split;
toBig: (h: number, l: number) => bigint;
shrSH: (h: number, _l: number, s: number) => number;
shrSL: (h: number, l: number, s: number) => number;
rotrSH: (h: number, l: number, s: number) => number;
rotrSL: (h: number, l: number, s: number) => number;
rotrBH: (h: number, l: number, s: number) => number;
rotrBL: (h: number, l: number, s: number) => number;
rotr32H: (_h: number, l: number) => number;
rotr32L: (h: number, _l: number) => number;
rotlSH: (h: number, l: number, s: number) => number;
rotlSL: (h: number, l: number, s: number) => number;
rotlBH: (h: number, l: number, s: number) => number;
rotlBL: (h: number, l: number, s: number) => number;
add: typeof add;
add3L: (Al: number, Bl: number, Cl: number) => number;
add3H: (low: number, Ah: number, Bh: number, Ch: number) => number;
add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number;
add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number;
add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number;
add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number;
};
export default u64;
//# sourceMappingURL=_u64.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"_u64.d.ts","sourceRoot":"","sources":["src/_u64.ts"],"names":[],"mappings":"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AAK,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;IAAC,KAAK,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;IAAC,MAAM,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;IAAC,MAAM,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;IAAC,MAAM,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;IAAC,MAAM,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;IAAC,OAAO,EAAE,CAAC,EAAE,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;IAAC,OAAO,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,KAAK,MAAM,CAAC;IAAC,MAAM,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;IAAC,MAAM,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;IAAC,MAAM,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;IAAC,MAAM,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;IAAC,GAAG,EAAE,OAAO,GAAG,CAAC;IAAC,KAAK,EAAE,CAAC,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,KAAK,MAAM,CAAC;IAAC,KAAK,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,KAAK,MAAM,CAAC;IAAC,KAAK,EAAE,CAAC,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,KAAK,MAAM,CAAC;IAAC,KAAK,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,KAAK,MAAM,CAAC;IAAC,KAAK,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,KAAK,MAAM,CAAC;IAAC,KAAK,EAAE,CAAC,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,KAAK,MAAM,CAAC;CAOrpC,CAAC;AACF,eAAe,GAAG,CAAC"}
+90
View File
@@ -0,0 +1,90 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.toBig = exports.shrSL = exports.shrSH = exports.rotrSL = exports.rotrSH = exports.rotrBL = exports.rotrBH = exports.rotr32L = exports.rotr32H = exports.rotlSL = exports.rotlSH = exports.rotlBL = exports.rotlBH = exports.add5L = exports.add5H = exports.add4L = exports.add4H = exports.add3L = exports.add3H = void 0;
exports.add = add;
exports.fromBig = fromBig;
exports.split = split;
/**
* Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.
* @todo re-check https://issues.chromium.org/issues/42212588
* @module
*/
const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
const _32n = /* @__PURE__ */ BigInt(32);
function fromBig(n, le = false) {
if (le)
return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
}
function split(lst, le = false) {
const len = lst.length;
let Ah = new Uint32Array(len);
let Al = new Uint32Array(len);
for (let i = 0; i < len; i++) {
const { h, l } = fromBig(lst[i], le);
[Ah[i], Al[i]] = [h, l];
}
return [Ah, Al];
}
const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);
exports.toBig = toBig;
// for Shift in [0, 32)
const shrSH = (h, _l, s) => h >>> s;
exports.shrSH = shrSH;
const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
exports.shrSL = shrSL;
// Right rotate for Shift in [1, 32)
const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));
exports.rotrSH = rotrSH;
const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
exports.rotrSL = rotrSL;
// Right rotate for Shift in (32, 64), NOTE: 32 is special case.
const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));
exports.rotrBH = rotrBH;
const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));
exports.rotrBL = rotrBL;
// Right rotate for shift===32 (just swaps l&h)
const rotr32H = (_h, l) => l;
exports.rotr32H = rotr32H;
const rotr32L = (h, _l) => h;
exports.rotr32L = rotr32L;
// Left rotate for Shift in [1, 32)
const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
exports.rotlSH = rotlSH;
const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
exports.rotlSL = rotlSL;
// Left rotate for Shift in (32, 64), NOTE: 32 is special case.
const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
exports.rotlBH = rotlBH;
const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
exports.rotlBL = rotlBL;
// JS uses 32-bit signed integers for bitwise operations which means we cannot
// simple take carry out of low bit sum by shift, we need to use division.
function add(Ah, Al, Bh, Bl) {
const l = (Al >>> 0) + (Bl >>> 0);
return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
}
// Addition with more than 2 elements
const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
exports.add3L = add3L;
const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
exports.add3H = add3H;
const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
exports.add4L = add4L;
const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
exports.add4H = add4H;
const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
exports.add5L = add5L;
const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;
exports.add5H = add5H;
// prettier-ignore
const u64 = {
fromBig, split, toBig,
shrSH, shrSL,
rotrSH, rotrSL, rotrBH, rotrBL,
rotr32H, rotr32L,
rotlSH, rotlSL, rotlBH, rotlBL,
add, add3L, add3H, add4L, add4H, add5H, add5L,
};
exports.default = u64;
//# sourceMappingURL=_u64.js.map
File diff suppressed because one or more lines are too long
+32
View File
@@ -0,0 +1,32 @@
import { type KDFInput } from './utils.ts';
/**
* Argon2 options.
* * t: time cost, m: mem cost in kb, p: parallelization.
* * key: optional key. personalization: arbitrary extra data.
* * dkLen: desired number of output bytes.
*/
export type ArgonOpts = {
t: number;
m: number;
p: number;
version?: number;
key?: KDFInput;
personalization?: KDFInput;
dkLen?: number;
asyncTick?: number;
maxmem?: number;
onProgress?: (progress: number) => void;
};
/** argon2d GPU-resistant version. */
export declare const argon2d: (password: KDFInput, salt: KDFInput, opts: ArgonOpts) => Uint8Array;
/** argon2i side-channel-resistant version. */
export declare const argon2i: (password: KDFInput, salt: KDFInput, opts: ArgonOpts) => Uint8Array;
/** argon2id, combining i+d, the most popular version from RFC 9106 */
export declare const argon2id: (password: KDFInput, salt: KDFInput, opts: ArgonOpts) => Uint8Array;
/** argon2d async GPU-resistant version. */
export declare const argon2dAsync: (password: KDFInput, salt: KDFInput, opts: ArgonOpts) => Promise<Uint8Array>;
/** argon2i async side-channel-resistant version. */
export declare const argon2iAsync: (password: KDFInput, salt: KDFInput, opts: ArgonOpts) => Promise<Uint8Array>;
/** argon2id async, combining i+d, the most popular version from RFC 9106 */
export declare const argon2idAsync: (password: KDFInput, salt: KDFInput, opts: ArgonOpts) => Promise<Uint8Array>;
//# sourceMappingURL=argon2.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"argon2.d.ts","sourceRoot":"","sources":["src/argon2.ts"],"names":[],"mappings":"AAYA,OAAO,EAAqD,KAAK,QAAQ,EAAE,MAAM,YAAY,CAAC;AAkK9F;;;;;GAKG;AACH,MAAM,MAAM,SAAS,GAAG;IACtB,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;IACV,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,GAAG,CAAC,EAAE,QAAQ,CAAC;IACf,eAAe,CAAC,EAAE,QAAQ,CAAC;IAC3B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,UAAU,CAAC,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,IAAI,CAAC;CACzC,CAAC;AAuNF,qCAAqC;AACrC,eAAO,MAAM,OAAO,GAAI,UAAU,QAAQ,EAAE,MAAM,QAAQ,EAAE,MAAM,SAAS,KAAG,UACnC,CAAC;AAC5C,8CAA8C;AAC9C,eAAO,MAAM,OAAO,GAAI,UAAU,QAAQ,EAAE,MAAM,QAAQ,EAAE,MAAM,SAAS,KAAG,UACpC,CAAC;AAC3C,sEAAsE;AACtE,eAAO,MAAM,QAAQ,GAAI,UAAU,QAAQ,EAAE,MAAM,QAAQ,EAAE,MAAM,SAAS,KAAG,UACpC,CAAC;AAiE5C,2CAA2C;AAC3C,eAAO,MAAM,YAAY,GACvB,UAAU,QAAQ,EAClB,MAAM,QAAQ,EACd,MAAM,SAAS,KACd,OAAO,CAAC,UAAU,CAAmD,CAAC;AACzE,oDAAoD;AACpD,eAAO,MAAM,YAAY,GACvB,UAAU,QAAQ,EAClB,MAAM,QAAQ,EACd,MAAM,SAAS,KACd,OAAO,CAAC,UAAU,CAAkD,CAAC;AACxE,4EAA4E;AAC5E,eAAO,MAAM,aAAa,GACxB,UAAU,QAAQ,EAClB,MAAM,QAAQ,EACd,MAAM,SAAS,KACd,OAAO,CAAC,UAAU,CAAmD,CAAC"}
+401
View File
@@ -0,0 +1,401 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.argon2idAsync = exports.argon2iAsync = exports.argon2dAsync = exports.argon2id = exports.argon2i = exports.argon2d = void 0;
/**
* Argon2 KDF from RFC 9106. Can be used to create a key from password and salt.
* We suggest to use Scrypt. JS Argon is 2-10x slower than native code because of 64-bitness:
* * argon uses uint64, but JS doesn't have fast uint64array
* * uint64 multiplication is 1/3 of time
* * `P` function would be very nice with u64, because most of value will be in registers,
* hovewer with u32 it will require 32 registers, which is too much.
* * JS arrays do slow bound checks, so reading from `A2_BUF` slows it down
* @module
*/
const _u64_ts_1 = require("./_u64.js");
const blake2_ts_1 = require("./blake2.js");
const utils_ts_1 = require("./utils.js");
const AT = { Argond2d: 0, Argon2i: 1, Argon2id: 2 };
const ARGON2_SYNC_POINTS = 4;
const abytesOrZero = (buf) => {
if (buf === undefined)
return Uint8Array.of();
return (0, utils_ts_1.kdfInputToBytes)(buf);
};
// u32 * u32 = u64
function mul(a, b) {
const aL = a & 0xffff;
const aH = a >>> 16;
const bL = b & 0xffff;
const bH = b >>> 16;
const ll = Math.imul(aL, bL);
const hl = Math.imul(aH, bL);
const lh = Math.imul(aL, bH);
const hh = Math.imul(aH, bH);
const carry = (ll >>> 16) + (hl & 0xffff) + lh;
const high = (hh + (hl >>> 16) + (carry >>> 16)) | 0;
const low = (carry << 16) | (ll & 0xffff);
return { h: high, l: low };
}
function mul2(a, b) {
// 2 * a * b (via shifts)
const { h, l } = mul(a, b);
return { h: ((h << 1) | (l >>> 31)) & 4294967295, l: (l << 1) & 4294967295 };
}
// BlaMka permutation for Argon2
// A + B + (2 * u32(A) * u32(B))
function blamka(Ah, Al, Bh, Bl) {
const { h: Ch, l: Cl } = mul2(Al, Bl);
// A + B + (2 * A * B)
const Rll = (0, _u64_ts_1.add3L)(Al, Bl, Cl);
return { h: (0, _u64_ts_1.add3H)(Rll, Ah, Bh, Ch), l: Rll | 0 };
}
// Temporary block buffer
const A2_BUF = new Uint32Array(256); // 1024 bytes (matrix 16x16)
function G(a, b, c, d) {
let Al = A2_BUF[2 * a], Ah = A2_BUF[2 * a + 1]; // prettier-ignore
let Bl = A2_BUF[2 * b], Bh = A2_BUF[2 * b + 1]; // prettier-ignore
let Cl = A2_BUF[2 * c], Ch = A2_BUF[2 * c + 1]; // prettier-ignore
let Dl = A2_BUF[2 * d], Dh = A2_BUF[2 * d + 1]; // prettier-ignore
({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl));
({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al });
({ Dh, Dl } = { Dh: (0, _u64_ts_1.rotr32H)(Dh, Dl), Dl: (0, _u64_ts_1.rotr32L)(Dh, Dl) });
({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl));
({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl });
({ Bh, Bl } = { Bh: (0, _u64_ts_1.rotrSH)(Bh, Bl, 24), Bl: (0, _u64_ts_1.rotrSL)(Bh, Bl, 24) });
({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl));
({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al });
({ Dh, Dl } = { Dh: (0, _u64_ts_1.rotrSH)(Dh, Dl, 16), Dl: (0, _u64_ts_1.rotrSL)(Dh, Dl, 16) });
({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl));
({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl });
({ Bh, Bl } = { Bh: (0, _u64_ts_1.rotrBH)(Bh, Bl, 63), Bl: (0, _u64_ts_1.rotrBL)(Bh, Bl, 63) });
(A2_BUF[2 * a] = Al), (A2_BUF[2 * a + 1] = Ah);
(A2_BUF[2 * b] = Bl), (A2_BUF[2 * b + 1] = Bh);
(A2_BUF[2 * c] = Cl), (A2_BUF[2 * c + 1] = Ch);
(A2_BUF[2 * d] = Dl), (A2_BUF[2 * d + 1] = Dh);
}
// prettier-ignore
function P(v00, v01, v02, v03, v04, v05, v06, v07, v08, v09, v10, v11, v12, v13, v14, v15) {
G(v00, v04, v08, v12);
G(v01, v05, v09, v13);
G(v02, v06, v10, v14);
G(v03, v07, v11, v15);
G(v00, v05, v10, v15);
G(v01, v06, v11, v12);
G(v02, v07, v08, v13);
G(v03, v04, v09, v14);
}
function block(x, xPos, yPos, outPos, needXor) {
for (let i = 0; i < 256; i++)
A2_BUF[i] = x[xPos + i] ^ x[yPos + i];
// columns (8)
for (let i = 0; i < 128; i += 16) {
// prettier-ignore
P(i, i + 1, i + 2, i + 3, i + 4, i + 5, i + 6, i + 7, i + 8, i + 9, i + 10, i + 11, i + 12, i + 13, i + 14, i + 15);
}
// rows (8)
for (let i = 0; i < 16; i += 2) {
// prettier-ignore
P(i, i + 1, i + 16, i + 17, i + 32, i + 33, i + 48, i + 49, i + 64, i + 65, i + 80, i + 81, i + 96, i + 97, i + 112, i + 113);
}
if (needXor)
for (let i = 0; i < 256; i++)
x[outPos + i] ^= A2_BUF[i] ^ x[xPos + i] ^ x[yPos + i];
else
for (let i = 0; i < 256; i++)
x[outPos + i] = A2_BUF[i] ^ x[xPos + i] ^ x[yPos + i];
(0, utils_ts_1.clean)(A2_BUF);
}
// Variable-Length Hash Function H'
function Hp(A, dkLen) {
const A8 = (0, utils_ts_1.u8)(A);
const T = new Uint32Array(1);
const T8 = (0, utils_ts_1.u8)(T);
T[0] = dkLen;
// Fast path
if (dkLen <= 64)
return blake2_ts_1.blake2b.create({ dkLen }).update(T8).update(A8).digest();
const out = new Uint8Array(dkLen);
let V = blake2_ts_1.blake2b.create({}).update(T8).update(A8).digest();
let pos = 0;
// First block
out.set(V.subarray(0, 32));
pos += 32;
// Rest blocks
for (; dkLen - pos > 64; pos += 32) {
const Vh = blake2_ts_1.blake2b.create({}).update(V);
Vh.digestInto(V);
Vh.destroy();
out.set(V.subarray(0, 32), pos);
}
// Last block
out.set((0, blake2_ts_1.blake2b)(V, { dkLen: dkLen - pos }), pos);
(0, utils_ts_1.clean)(V, T);
return (0, utils_ts_1.u32)(out);
}
// Used only inside process block!
function indexAlpha(r, s, laneLen, segmentLen, index, randL, sameLane = false) {
// This is ugly, but close enough to reference implementation.
let area;
if (r === 0) {
if (s === 0)
area = index - 1;
else if (sameLane)
area = s * segmentLen + index - 1;
else
area = s * segmentLen + (index == 0 ? -1 : 0);
}
else if (sameLane)
area = laneLen - segmentLen + index - 1;
else
area = laneLen - segmentLen + (index == 0 ? -1 : 0);
const startPos = r !== 0 && s !== ARGON2_SYNC_POINTS - 1 ? (s + 1) * segmentLen : 0;
const rel = area - 1 - mul(area, mul(randL, randL).h).h;
return (startPos + rel) % laneLen;
}
const maxUint32 = Math.pow(2, 32);
function isU32(num) {
return Number.isSafeInteger(num) && num >= 0 && num < maxUint32;
}
function argon2Opts(opts) {
const merged = {
version: 0x13,
dkLen: 32,
maxmem: maxUint32 - 1,
asyncTick: 10,
};
for (let [k, v] of Object.entries(opts))
if (v != null)
merged[k] = v;
const { dkLen, p, m, t, version, onProgress } = merged;
if (!isU32(dkLen) || dkLen < 4)
throw new Error('dkLen should be at least 4 bytes');
if (!isU32(p) || p < 1 || p >= Math.pow(2, 24))
throw new Error('p should be 1 <= p < 2^24');
if (!isU32(m))
throw new Error('m should be 0 <= m < 2^32');
if (!isU32(t) || t < 1)
throw new Error('t (iterations) should be 1 <= t < 2^32');
if (onProgress !== undefined && typeof onProgress !== 'function')
throw new Error('progressCb should be function');
/*
Memory size m MUST be an integer number of kibibytes from 8*p to 2^(32)-1. The actual number of blocks is m', which is m rounded down to the nearest multiple of 4*p.
*/
if (!isU32(m) || m < 8 * p)
throw new Error('memory should be at least 8*p bytes');
if (version !== 0x10 && version !== 0x13)
throw new Error('unknown version=' + version);
return merged;
}
function argon2Init(password, salt, type, opts) {
password = (0, utils_ts_1.kdfInputToBytes)(password);
salt = (0, utils_ts_1.kdfInputToBytes)(salt);
(0, utils_ts_1.abytes)(password);
(0, utils_ts_1.abytes)(salt);
if (!isU32(password.length))
throw new Error('password should be less than 4 GB');
if (!isU32(salt.length) || salt.length < 8)
throw new Error('salt should be at least 8 bytes and less than 4 GB');
if (!Object.values(AT).includes(type))
throw new Error('invalid type');
let { p, dkLen, m, t, version, key, personalization, maxmem, onProgress, asyncTick } = argon2Opts(opts);
// Validation
key = abytesOrZero(key);
personalization = abytesOrZero(personalization);
// H_0 = H^(64)(LE32(p) || LE32(T) || LE32(m) || LE32(t) ||
// LE32(v) || LE32(y) || LE32(length(P)) || P ||
// LE32(length(S)) || S || LE32(length(K)) || K ||
// LE32(length(X)) || X)
const h = blake2_ts_1.blake2b.create({});
const BUF = new Uint32Array(1);
const BUF8 = (0, utils_ts_1.u8)(BUF);
for (let item of [p, dkLen, m, t, version, type]) {
BUF[0] = item;
h.update(BUF8);
}
for (let i of [password, salt, key, personalization]) {
BUF[0] = i.length; // BUF is u32 array, this is valid
h.update(BUF8).update(i);
}
const H0 = new Uint32Array(18);
const H0_8 = (0, utils_ts_1.u8)(H0);
h.digestInto(H0_8);
// 256 u32 = 1024 (BLOCK_SIZE), fills A2_BUF on processing
// Params
const lanes = p;
// m' = 4 * p * floor (m / 4p)
const mP = 4 * p * Math.floor(m / (ARGON2_SYNC_POINTS * p));
//q = m' / p columns
const laneLen = Math.floor(mP / p);
const segmentLen = Math.floor(laneLen / ARGON2_SYNC_POINTS);
const memUsed = mP * 256;
if (!isU32(maxmem) || memUsed > maxmem)
throw new Error('mem should be less than 2**32, got: maxmem=' + maxmem + ', memused=' + memUsed);
const B = new Uint32Array(memUsed);
// Fill first blocks
for (let l = 0; l < p; l++) {
const i = 256 * laneLen * l;
// B[i][0] = H'^(1024)(H_0 || LE32(0) || LE32(i))
H0[17] = l;
H0[16] = 0;
B.set(Hp(H0, 1024), i);
// B[i][1] = H'^(1024)(H_0 || LE32(1) || LE32(i))
H0[16] = 1;
B.set(Hp(H0, 1024), i + 256);
}
let perBlock = () => { };
if (onProgress) {
const totalBlock = t * ARGON2_SYNC_POINTS * p * segmentLen;
// Invoke callback if progress changes from 10.01 to 10.02
// Allows to draw smooth progress bar on up to 8K screen
const callbackPer = Math.max(Math.floor(totalBlock / 10000), 1);
let blockCnt = 0;
perBlock = () => {
blockCnt++;
if (onProgress && (!(blockCnt % callbackPer) || blockCnt === totalBlock))
onProgress(blockCnt / totalBlock);
};
}
(0, utils_ts_1.clean)(BUF, H0);
return { type, mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock, asyncTick };
}
function argon2Output(B, p, laneLen, dkLen) {
const B_final = new Uint32Array(256);
for (let l = 0; l < p; l++)
for (let j = 0; j < 256; j++)
B_final[j] ^= B[256 * (laneLen * l + laneLen - 1) + j];
const res = (0, utils_ts_1.u8)(Hp(B_final, dkLen));
(0, utils_ts_1.clean)(B_final);
return res;
}
function processBlock(B, address, l, r, s, index, laneLen, segmentLen, lanes, offset, prev, dataIndependent, needXor) {
if (offset % laneLen)
prev = offset - 1;
let randL, randH;
if (dataIndependent) {
let i128 = index % 128;
if (i128 === 0) {
address[256 + 12]++;
block(address, 256, 2 * 256, 0, false);
block(address, 0, 2 * 256, 0, false);
}
randL = address[2 * i128];
randH = address[2 * i128 + 1];
}
else {
const T = 256 * prev;
randL = B[T];
randH = B[T + 1];
}
// address block
const refLane = r === 0 && s === 0 ? l : randH % lanes;
const refPos = indexAlpha(r, s, laneLen, segmentLen, index, randL, refLane == l);
const refBlock = laneLen * refLane + refPos;
// B[i][j] = G(B[i][j-1], B[l][z])
block(B, 256 * prev, 256 * refBlock, offset * 256, needXor);
}
function argon2(type, password, salt, opts) {
const { mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock } = argon2Init(password, salt, type, opts);
// Pre-loop setup
// [address, input, zero_block] format so we can pass single U32 to block function
const address = new Uint32Array(3 * 256);
address[256 + 6] = mP;
address[256 + 8] = t;
address[256 + 10] = type;
for (let r = 0; r < t; r++) {
const needXor = r !== 0 && version === 0x13;
address[256 + 0] = r;
for (let s = 0; s < ARGON2_SYNC_POINTS; s++) {
address[256 + 4] = s;
const dataIndependent = type == AT.Argon2i || (type == AT.Argon2id && r === 0 && s < 2);
for (let l = 0; l < p; l++) {
address[256 + 2] = l;
address[256 + 12] = 0;
let startPos = 0;
if (r === 0 && s === 0) {
startPos = 2;
if (dataIndependent) {
address[256 + 12]++;
block(address, 256, 2 * 256, 0, false);
block(address, 0, 2 * 256, 0, false);
}
}
// current block postion
let offset = l * laneLen + s * segmentLen + startPos;
// previous block position
let prev = offset % laneLen ? offset - 1 : offset + laneLen - 1;
for (let index = startPos; index < segmentLen; index++, offset++, prev++) {
perBlock();
processBlock(B, address, l, r, s, index, laneLen, segmentLen, lanes, offset, prev, dataIndependent, needXor);
}
}
}
}
(0, utils_ts_1.clean)(address);
return argon2Output(B, p, laneLen, dkLen);
}
/** argon2d GPU-resistant version. */
const argon2d = (password, salt, opts) => argon2(AT.Argond2d, password, salt, opts);
exports.argon2d = argon2d;
/** argon2i side-channel-resistant version. */
const argon2i = (password, salt, opts) => argon2(AT.Argon2i, password, salt, opts);
exports.argon2i = argon2i;
/** argon2id, combining i+d, the most popular version from RFC 9106 */
const argon2id = (password, salt, opts) => argon2(AT.Argon2id, password, salt, opts);
exports.argon2id = argon2id;
async function argon2Async(type, password, salt, opts) {
const { mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock, asyncTick } = argon2Init(password, salt, type, opts);
// Pre-loop setup
// [address, input, zero_block] format so we can pass single U32 to block function
const address = new Uint32Array(3 * 256);
address[256 + 6] = mP;
address[256 + 8] = t;
address[256 + 10] = type;
let ts = Date.now();
for (let r = 0; r < t; r++) {
const needXor = r !== 0 && version === 0x13;
address[256 + 0] = r;
for (let s = 0; s < ARGON2_SYNC_POINTS; s++) {
address[256 + 4] = s;
const dataIndependent = type == AT.Argon2i || (type == AT.Argon2id && r === 0 && s < 2);
for (let l = 0; l < p; l++) {
address[256 + 2] = l;
address[256 + 12] = 0;
let startPos = 0;
if (r === 0 && s === 0) {
startPos = 2;
if (dataIndependent) {
address[256 + 12]++;
block(address, 256, 2 * 256, 0, false);
block(address, 0, 2 * 256, 0, false);
}
}
// current block postion
let offset = l * laneLen + s * segmentLen + startPos;
// previous block position
let prev = offset % laneLen ? offset - 1 : offset + laneLen - 1;
for (let index = startPos; index < segmentLen; index++, offset++, prev++) {
perBlock();
processBlock(B, address, l, r, s, index, laneLen, segmentLen, lanes, offset, prev, dataIndependent, needXor);
// Date.now() is not monotonic, so in case if clock goes backwards we return return control too
const diff = Date.now() - ts;
if (!(diff >= 0 && diff < asyncTick)) {
await (0, utils_ts_1.nextTick)();
ts += diff;
}
}
}
}
}
(0, utils_ts_1.clean)(address);
return argon2Output(B, p, laneLen, dkLen);
}
/** argon2d async GPU-resistant version. */
const argon2dAsync = (password, salt, opts) => argon2Async(AT.Argond2d, password, salt, opts);
exports.argon2dAsync = argon2dAsync;
/** argon2i async side-channel-resistant version. */
const argon2iAsync = (password, salt, opts) => argon2Async(AT.Argon2i, password, salt, opts);
exports.argon2iAsync = argon2iAsync;
/** argon2id async, combining i+d, the most popular version from RFC 9106 */
const argon2idAsync = (password, salt, opts) => argon2Async(AT.Argon2id, password, salt, opts);
exports.argon2idAsync = argon2idAsync;
//# sourceMappingURL=argon2.js.map
File diff suppressed because one or more lines are too long
+106
View File
@@ -0,0 +1,106 @@
import { Hash, type CHashO, type Input } from './utils.ts';
/** Blake1 options. Basically just "salt" */
export type BlakeOpts = {
salt?: Uint8Array;
};
declare abstract class BLAKE1<T extends BLAKE1<T>> extends Hash<T> {
protected finished: boolean;
protected length: number;
protected pos: number;
protected destroyed: boolean;
protected buffer: Uint8Array;
protected view: DataView;
protected salt: Uint32Array;
abstract compress(view: DataView, offset: number, withLength?: boolean): void;
protected abstract get(): number[];
protected abstract set(...args: number[]): void;
readonly blockLen: number;
readonly outputLen: number;
private lengthFlag;
private counterLen;
protected constants: Uint32Array;
constructor(blockLen: number, outputLen: number, lengthFlag: number, counterLen: number, saltLen: number, constants: Uint32Array, opts?: BlakeOpts);
update(data: Input): this;
destroy(): void;
_cloneInto(to?: T): T;
clone(): T;
digestInto(out: Uint8Array): void;
digest(): Uint8Array;
}
declare class Blake1_32 extends BLAKE1<Blake1_32> {
private v0;
private v1;
private v2;
private v3;
private v4;
private v5;
private v6;
private v7;
constructor(outputLen: number, IV: Uint32Array, lengthFlag: number, opts?: BlakeOpts);
protected get(): [number, number, number, number, number, number, number, number];
protected set(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number): void;
destroy(): void;
compress(view: DataView, offset: number, withLength?: boolean): void;
}
declare class Blake1_64 extends BLAKE1<Blake1_64> {
private v0l;
private v0h;
private v1l;
private v1h;
private v2l;
private v2h;
private v3l;
private v3h;
private v4l;
private v4h;
private v5l;
private v5h;
private v6l;
private v6h;
private v7l;
private v7h;
constructor(outputLen: number, IV: Uint32Array, lengthFlag: number, opts?: BlakeOpts);
protected get(): [
number,
number,
number,
number,
number,
number,
number,
number,
number,
number,
number,
number,
number,
number,
number,
number
];
protected set(v0l: number, v0h: number, v1l: number, v1h: number, v2l: number, v2h: number, v3l: number, v3h: number, v4l: number, v4h: number, v5l: number, v5h: number, v6l: number, v6h: number, v7l: number, v7h: number): void;
destroy(): void;
compress(view: DataView, offset: number, withLength?: boolean): void;
}
export declare class BLAKE224 extends Blake1_32 {
constructor(opts?: BlakeOpts);
}
export declare class BLAKE256 extends Blake1_32 {
constructor(opts?: BlakeOpts);
}
export declare class BLAKE384 extends Blake1_64 {
constructor(opts?: BlakeOpts);
}
export declare class BLAKE512 extends Blake1_64 {
constructor(opts?: BlakeOpts);
}
/** blake1-224 hash function */
export declare const blake224: CHashO;
/** blake1-256 hash function */
export declare const blake256: CHashO;
/** blake1-384 hash function */
export declare const blake384: CHashO;
/** blake1-512 hash function */
export declare const blake512: CHashO;
export {};
//# sourceMappingURL=blake1.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"blake1.d.ts","sourceRoot":"","sources":["src/blake1.ts"],"names":[],"mappings":"AA4BA,OAAO,EAGO,IAAI,EAChB,KAAK,MAAM,EAAE,KAAK,KAAK,EACxB,MAAM,YAAY,CAAC;AAEpB,4CAA4C;AAC5C,MAAM,MAAM,SAAS,GAAG;IACtB,IAAI,CAAC,EAAE,UAAU,CAAC;CACnB,CAAC;AAKF,uBAAe,MAAM,CAAC,CAAC,SAAS,MAAM,CAAC,CAAC,CAAC,CAAE,SAAQ,IAAI,CAAC,CAAC,CAAC;IACxD,SAAS,CAAC,QAAQ,UAAS;IAC3B,SAAS,CAAC,MAAM,SAAK;IACrB,SAAS,CAAC,GAAG,SAAK;IAClB,SAAS,CAAC,SAAS,UAAS;IAE5B,SAAS,CAAC,MAAM,EAAE,UAAU,CAAC;IAC7B,SAAS,CAAC,IAAI,EAAE,QAAQ,CAAC;IACzB,SAAS,CAAC,IAAI,EAAE,WAAW,CAAC;IAC5B,QAAQ,CAAC,QAAQ,CAAC,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,OAAO,GAAG,IAAI;IAC7E,SAAS,CAAC,QAAQ,CAAC,GAAG,IAAI,MAAM,EAAE;IAClC,SAAS,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,IAAI,EAAE,MAAM,EAAE,GAAG,IAAI;IAE/C,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,OAAO,CAAC,UAAU,CAAS;IAC3B,OAAO,CAAC,UAAU,CAAS;IAC3B,SAAS,CAAC,SAAS,EAAE,WAAW,CAAC;gBAG/B,QAAQ,EAAE,MAAM,EAChB,SAAS,EAAE,MAAM,EACjB,UAAU,EAAE,MAAM,EAClB,UAAU,EAAE,MAAM,EAClB,OAAO,EAAE,MAAM,EACf,SAAS,EAAE,WAAW,EACtB,IAAI,GAAE,SAAc;IA2BtB,MAAM,CAAC,IAAI,EAAE,KAAK,GAAG,IAAI;IA8BzB,OAAO,IAAI,IAAI;IAMf,UAAU,CAAC,EAAE,CAAC,EAAE,CAAC,GAAG,CAAC;IAarB,KAAK,IAAI,CAAC;IAGV,UAAU,CAAC,GAAG,EAAE,UAAU,GAAG,IAAI;IA4BjC,MAAM,IAAI,UAAU;CAOrB;AAgCD,cAAM,SAAU,SAAQ,MAAM,CAAC,SAAS,CAAC;IACvC,OAAO,CAAC,EAAE,CAAS;IACnB,OAAO,CAAC,EAAE,CAAS;IACnB,OAAO,CAAC,EAAE,CAAS;IACnB,OAAO,CAAC,EAAE,CAAS;IACnB,OAAO,CAAC,EAAE,CAAS;IACnB,OAAO,CAAC,EAAE,CAAS;IACnB,OAAO,CAAC,EAAE,CAAS;IACnB,OAAO,CAAC,EAAE,CAAS;gBACP,SAAS,EAAE,MAAM,EAAE,EAAE,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,EAAE,IAAI,GAAE,SAAc;IAWxF,SAAS,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC;IAKjF,SAAS,CAAC,GAAG,CACX,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAC7F,IAAI;IAUP,OAAO,IAAI,IAAI;IAIf,QAAQ,CAAC,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,UAAO,GAAG,IAAI;CAiDlE;AAsED,cAAM,SAAU,SAAQ,MAAM,CAAC,SAAS,CAAC;IACvC,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,GAAG,CAAS;gBACR,SAAS,EAAE,MAAM,EAAE,EAAE,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,EAAE,IAAI,GAAE,SAAc;IAoBxF,SAAS,CAAC,GAAG,IAAI;QACf,MAAM;QAAE,MAAM;QAAE,MAAM;QAAE,MAAM;QAAE,MAAM;QAAE,MAAM;QAAE,MAAM;QAAE,MAAM;QAC9D,MAAM;QAAE,MAAM;QAAE,MAAM;QAAE,MAAM;QAAE,MAAM;QAAE,MAAM;QAAE,MAAM;QAAE,MAAM;KAC/D;IAKD,SAAS,CAAC,GAAG,CACX,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAClD,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAClD,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAClD,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GACjD,IAAI;IAkBP,OAAO,IAAI,IAAI;IAIf,QAAQ,CAAC,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,UAAO,GAAG,IAAI;CAiDlE;AAED,qBAAa,QAAS,SAAQ,SAAS;gBACzB,IAAI,GAAE,SAAc;CAGjC;AACD,qBAAa,QAAS,SAAQ,SAAS;gBACzB,IAAI,GAAE,SAAc;CAGjC;AACD,qBAAa,QAAS,SAAQ,SAAS;gBACzB,IAAI,GAAE,SAAc;CAGjC;AACD,qBAAa,QAAS,SAAQ,SAAS;gBACzB,IAAI,GAAE,SAAc;CAGjC;AACD,+BAA+B;AAC/B,eAAO,MAAM,QAAQ,EAAE,MAEtB,CAAC;AACF,+BAA+B;AAC/B,eAAO,MAAM,QAAQ,EAAE,MAEtB,CAAC;AACF,+BAA+B;AAC/B,eAAO,MAAM,QAAQ,EAAE,MAEtB,CAAC;AACF,+BAA+B;AAC/B,eAAO,MAAM,QAAQ,EAAE,MAEtB,CAAC"}
+459
View File
@@ -0,0 +1,459 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.blake512 = exports.blake384 = exports.blake256 = exports.blake224 = exports.BLAKE512 = exports.BLAKE384 = exports.BLAKE256 = exports.BLAKE224 = void 0;
/**
* Blake1 legacy hash function, one of SHA3 proposals.
* Rarely used. Check out blake2 or blake3 instead.
* https://www.aumasson.jp/blake/blake.pdf
*
* In the best case, there are 0 allocations.
*
* Differences from blake2:
*
* - BE instead of LE
* - Paddings, similar to MD5, RIPEMD, SHA1, SHA2, but:
* - length flag is located before actual length
* - padding block is compressed differently (no lengths)
* Instead of msg[sigma[k]], we have `msg[sigma[k]] ^ constants[sigma[k-1]]`
* (-1 for g1, g2 without -1)
* - Salt is XOR-ed into constants instead of state
* - Salt is XOR-ed with output in `compress`
* - Additional rows (+64 bytes) in SIGMA for new rounds
* - Different round count:
* - 14 / 10 rounds in blake256 / blake2s
* - 16 / 12 rounds in blake512 / blake2b
* - blake512: G1b: rotr 24 -> 25, G2b: rotr 63 -> 11
* @module
*/
const _blake_ts_1 = require("./_blake.js");
const _md_ts_1 = require("./_md.js");
const u64 = require("./_u64.js");
// prettier-ignore
const utils_ts_1 = require("./utils.js");
// Empty zero-filled salt
const EMPTY_SALT = /* @__PURE__ */ new Uint32Array(8);
class BLAKE1 extends utils_ts_1.Hash {
constructor(blockLen, outputLen, lengthFlag, counterLen, saltLen, constants, opts = {}) {
super();
this.finished = false;
this.length = 0;
this.pos = 0;
this.destroyed = false;
const { salt } = opts;
this.blockLen = blockLen;
this.outputLen = outputLen;
this.lengthFlag = lengthFlag;
this.counterLen = counterLen;
this.buffer = new Uint8Array(blockLen);
this.view = (0, utils_ts_1.createView)(this.buffer);
if (salt) {
let slt = salt;
slt = (0, utils_ts_1.toBytes)(slt);
(0, utils_ts_1.abytes)(slt);
if (slt.length !== 4 * saltLen)
throw new Error('wrong salt length');
const salt32 = (this.salt = new Uint32Array(saltLen));
const sv = (0, utils_ts_1.createView)(slt);
this.constants = constants.slice();
for (let i = 0, offset = 0; i < salt32.length; i++, offset += 4) {
salt32[i] = sv.getUint32(offset, false);
this.constants[i] ^= salt32[i];
}
}
else {
this.salt = EMPTY_SALT;
this.constants = constants;
}
}
update(data) {
(0, utils_ts_1.aexists)(this);
data = (0, utils_ts_1.toBytes)(data);
(0, utils_ts_1.abytes)(data);
// From _md, but update length before each compress
const { view, buffer, blockLen } = this;
const len = data.length;
let dataView;
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, cast it to view and process
if (take === blockLen) {
if (!dataView)
dataView = (0, utils_ts_1.createView)(data);
for (; blockLen <= len - pos; pos += blockLen) {
this.length += blockLen;
this.compress(dataView, pos);
}
continue;
}
buffer.set(data.subarray(pos, pos + take), this.pos);
this.pos += take;
pos += take;
if (this.pos === blockLen) {
this.length += blockLen;
this.compress(view, 0, true);
this.pos = 0;
}
}
return this;
}
destroy() {
this.destroyed = true;
if (this.salt !== EMPTY_SALT) {
(0, utils_ts_1.clean)(this.salt, this.constants);
}
}
_cloneInto(to) {
to || (to = new this.constructor());
to.set(...this.get());
const { buffer, length, finished, destroyed, constants, salt, pos } = this;
to.buffer.set(buffer);
to.constants = constants.slice();
to.destroyed = destroyed;
to.finished = finished;
to.length = length;
to.pos = pos;
to.salt = salt.slice();
return to;
}
clone() {
return this._cloneInto();
}
digestInto(out) {
(0, utils_ts_1.aexists)(this);
(0, utils_ts_1.aoutput)(out, this);
this.finished = true;
// Padding
const { buffer, blockLen, counterLen, lengthFlag, view } = this;
(0, utils_ts_1.clean)(buffer.subarray(this.pos)); // clean buf
const counter = BigInt((this.length + this.pos) * 8);
const counterPos = blockLen - counterLen - 1;
buffer[this.pos] |= 128; // End block flag
this.length += this.pos; // add unwritten length
// Not enough in buffer for length: write what we have.
if (this.pos > counterPos) {
this.compress(view, 0);
(0, utils_ts_1.clean)(buffer);
this.pos = 0;
}
// Difference with md: here we have lengthFlag!
buffer[counterPos] |= lengthFlag; // Length flag
// We always set 8 byte length flag. Because length will overflow significantly sooner.
(0, _md_ts_1.setBigUint64)(view, blockLen - 8, counter, false);
this.compress(view, 0, this.pos !== 0); // don't add length if length is not empty block?
// Write output
(0, utils_ts_1.clean)(buffer);
const v = (0, utils_ts_1.createView)(out);
const state = this.get();
for (let i = 0; i < this.outputLen / 4; ++i)
v.setUint32(i * 4, state[i]);
}
digest() {
const { buffer, outputLen } = this;
this.digestInto(buffer);
const res = buffer.slice(0, outputLen);
this.destroy();
return res;
}
}
// Constants
const B64C = /* @__PURE__ */ Uint32Array.from([
0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
0x9216d5d9, 0x8979fb1b, 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96,
0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69,
]);
// first half of C512
const B32C = B64C.slice(0, 16);
const B256_IV = _md_ts_1.SHA256_IV.slice();
const B224_IV = _md_ts_1.SHA224_IV.slice();
const B384_IV = _md_ts_1.SHA384_IV.slice();
const B512_IV = _md_ts_1.SHA512_IV.slice();
function generateTBL256() {
const TBL = [];
for (let i = 0, j = 0; i < 14; i++, j += 16) {
for (let offset = 1; offset < 16; offset += 2) {
TBL.push(B32C[_blake_ts_1.BSIGMA[j + offset]]);
TBL.push(B32C[_blake_ts_1.BSIGMA[j + offset - 1]]);
}
}
return new Uint32Array(TBL);
}
const TBL256 = /* @__PURE__ */ generateTBL256(); // C256[SIGMA[X]] precompute
// Reusable temporary buffer
const BLAKE256_W = /* @__PURE__ */ new Uint32Array(16);
class Blake1_32 extends BLAKE1 {
constructor(outputLen, IV, lengthFlag, opts = {}) {
super(64, outputLen, lengthFlag, 8, 4, B32C, opts);
this.v0 = IV[0] | 0;
this.v1 = IV[1] | 0;
this.v2 = IV[2] | 0;
this.v3 = IV[3] | 0;
this.v4 = IV[4] | 0;
this.v5 = IV[5] | 0;
this.v6 = IV[6] | 0;
this.v7 = IV[7] | 0;
}
get() {
const { v0, v1, v2, v3, v4, v5, v6, v7 } = this;
return [v0, v1, v2, v3, v4, v5, v6, v7];
}
// prettier-ignore
set(v0, v1, v2, v3, v4, v5, v6, v7) {
this.v0 = v0 | 0;
this.v1 = v1 | 0;
this.v2 = v2 | 0;
this.v3 = v3 | 0;
this.v4 = v4 | 0;
this.v5 = v5 | 0;
this.v6 = v6 | 0;
this.v7 = v7 | 0;
}
destroy() {
super.destroy();
this.set(0, 0, 0, 0, 0, 0, 0, 0);
}
compress(view, offset, withLength = true) {
for (let i = 0; i < 16; i++, offset += 4)
BLAKE256_W[i] = view.getUint32(offset, false);
// NOTE: we cannot re-use compress from blake2s, since there is additional xor over u256[SIGMA[e]]
let v00 = this.v0 | 0;
let v01 = this.v1 | 0;
let v02 = this.v2 | 0;
let v03 = this.v3 | 0;
let v04 = this.v4 | 0;
let v05 = this.v5 | 0;
let v06 = this.v6 | 0;
let v07 = this.v7 | 0;
let v08 = this.constants[0] | 0;
let v09 = this.constants[1] | 0;
let v10 = this.constants[2] | 0;
let v11 = this.constants[3] | 0;
const { h, l } = u64.fromBig(BigInt(withLength ? this.length * 8 : 0));
let v12 = (this.constants[4] ^ l) >>> 0;
let v13 = (this.constants[5] ^ l) >>> 0;
let v14 = (this.constants[6] ^ h) >>> 0;
let v15 = (this.constants[7] ^ h) >>> 0;
// prettier-ignore
for (let i = 0, k = 0, j = 0; i < 14; i++) {
({ a: v00, b: v04, c: v08, d: v12 } = (0, _blake_ts_1.G1s)(v00, v04, v08, v12, BLAKE256_W[_blake_ts_1.BSIGMA[k++]] ^ TBL256[j++]));
({ a: v00, b: v04, c: v08, d: v12 } = (0, _blake_ts_1.G2s)(v00, v04, v08, v12, BLAKE256_W[_blake_ts_1.BSIGMA[k++]] ^ TBL256[j++]));
({ a: v01, b: v05, c: v09, d: v13 } = (0, _blake_ts_1.G1s)(v01, v05, v09, v13, BLAKE256_W[_blake_ts_1.BSIGMA[k++]] ^ TBL256[j++]));
({ a: v01, b: v05, c: v09, d: v13 } = (0, _blake_ts_1.G2s)(v01, v05, v09, v13, BLAKE256_W[_blake_ts_1.BSIGMA[k++]] ^ TBL256[j++]));
({ a: v02, b: v06, c: v10, d: v14 } = (0, _blake_ts_1.G1s)(v02, v06, v10, v14, BLAKE256_W[_blake_ts_1.BSIGMA[k++]] ^ TBL256[j++]));
({ a: v02, b: v06, c: v10, d: v14 } = (0, _blake_ts_1.G2s)(v02, v06, v10, v14, BLAKE256_W[_blake_ts_1.BSIGMA[k++]] ^ TBL256[j++]));
({ a: v03, b: v07, c: v11, d: v15 } = (0, _blake_ts_1.G1s)(v03, v07, v11, v15, BLAKE256_W[_blake_ts_1.BSIGMA[k++]] ^ TBL256[j++]));
({ a: v03, b: v07, c: v11, d: v15 } = (0, _blake_ts_1.G2s)(v03, v07, v11, v15, BLAKE256_W[_blake_ts_1.BSIGMA[k++]] ^ TBL256[j++]));
({ a: v00, b: v05, c: v10, d: v15 } = (0, _blake_ts_1.G1s)(v00, v05, v10, v15, BLAKE256_W[_blake_ts_1.BSIGMA[k++]] ^ TBL256[j++]));
({ a: v00, b: v05, c: v10, d: v15 } = (0, _blake_ts_1.G2s)(v00, v05, v10, v15, BLAKE256_W[_blake_ts_1.BSIGMA[k++]] ^ TBL256[j++]));
({ a: v01, b: v06, c: v11, d: v12 } = (0, _blake_ts_1.G1s)(v01, v06, v11, v12, BLAKE256_W[_blake_ts_1.BSIGMA[k++]] ^ TBL256[j++]));
({ a: v01, b: v06, c: v11, d: v12 } = (0, _blake_ts_1.G2s)(v01, v06, v11, v12, BLAKE256_W[_blake_ts_1.BSIGMA[k++]] ^ TBL256[j++]));
({ a: v02, b: v07, c: v08, d: v13 } = (0, _blake_ts_1.G1s)(v02, v07, v08, v13, BLAKE256_W[_blake_ts_1.BSIGMA[k++]] ^ TBL256[j++]));
({ a: v02, b: v07, c: v08, d: v13 } = (0, _blake_ts_1.G2s)(v02, v07, v08, v13, BLAKE256_W[_blake_ts_1.BSIGMA[k++]] ^ TBL256[j++]));
({ a: v03, b: v04, c: v09, d: v14 } = (0, _blake_ts_1.G1s)(v03, v04, v09, v14, BLAKE256_W[_blake_ts_1.BSIGMA[k++]] ^ TBL256[j++]));
({ a: v03, b: v04, c: v09, d: v14 } = (0, _blake_ts_1.G2s)(v03, v04, v09, v14, BLAKE256_W[_blake_ts_1.BSIGMA[k++]] ^ TBL256[j++]));
}
this.v0 = (this.v0 ^ v00 ^ v08 ^ this.salt[0]) >>> 0;
this.v1 = (this.v1 ^ v01 ^ v09 ^ this.salt[1]) >>> 0;
this.v2 = (this.v2 ^ v02 ^ v10 ^ this.salt[2]) >>> 0;
this.v3 = (this.v3 ^ v03 ^ v11 ^ this.salt[3]) >>> 0;
this.v4 = (this.v4 ^ v04 ^ v12 ^ this.salt[0]) >>> 0;
this.v5 = (this.v5 ^ v05 ^ v13 ^ this.salt[1]) >>> 0;
this.v6 = (this.v6 ^ v06 ^ v14 ^ this.salt[2]) >>> 0;
this.v7 = (this.v7 ^ v07 ^ v15 ^ this.salt[3]) >>> 0;
(0, utils_ts_1.clean)(BLAKE256_W);
}
}
const BBUF = /* @__PURE__ */ new Uint32Array(32);
const BLAKE512_W = /* @__PURE__ */ new Uint32Array(32);
function generateTBL512() {
const TBL = [];
for (let r = 0, k = 0; r < 16; r++, k += 16) {
for (let offset = 1; offset < 16; offset += 2) {
TBL.push(B64C[_blake_ts_1.BSIGMA[k + offset] * 2 + 0]);
TBL.push(B64C[_blake_ts_1.BSIGMA[k + offset] * 2 + 1]);
TBL.push(B64C[_blake_ts_1.BSIGMA[k + offset - 1] * 2 + 0]);
TBL.push(B64C[_blake_ts_1.BSIGMA[k + offset - 1] * 2 + 1]);
}
}
return new Uint32Array(TBL);
}
const TBL512 = /* @__PURE__ */ generateTBL512(); // C512[SIGMA[X]] precompute
// Mixing function G splitted in two halfs
function G1b(a, b, c, d, msg, k) {
const Xpos = 2 * _blake_ts_1.BSIGMA[k];
const Xl = msg[Xpos + 1] ^ TBL512[k * 2 + 1], Xh = msg[Xpos] ^ TBL512[k * 2]; // prettier-ignore
let Al = BBUF[2 * a + 1], Ah = BBUF[2 * a]; // prettier-ignore
let Bl = BBUF[2 * b + 1], Bh = BBUF[2 * b]; // prettier-ignore
let Cl = BBUF[2 * c + 1], Ch = BBUF[2 * c]; // prettier-ignore
let Dl = BBUF[2 * d + 1], Dh = BBUF[2 * d]; // prettier-ignore
// v[a] = (v[a] + v[b] + x) | 0;
let ll = u64.add3L(Al, Bl, Xl);
Ah = u64.add3H(ll, Ah, Bh, Xh) >>> 0;
Al = (ll | 0) >>> 0;
// v[d] = rotr(v[d] ^ v[a], 32)
({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al });
({ Dh, Dl } = { Dh: u64.rotr32H(Dh, Dl), Dl: u64.rotr32L(Dh, Dl) });
// v[c] = (v[c] + v[d]) | 0;
({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl));
// v[b] = rotr(v[b] ^ v[c], 25)
({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl });
({ Bh, Bl } = { Bh: u64.rotrSH(Bh, Bl, 25), Bl: u64.rotrSL(Bh, Bl, 25) });
(BBUF[2 * a + 1] = Al), (BBUF[2 * a] = Ah);
(BBUF[2 * b + 1] = Bl), (BBUF[2 * b] = Bh);
(BBUF[2 * c + 1] = Cl), (BBUF[2 * c] = Ch);
(BBUF[2 * d + 1] = Dl), (BBUF[2 * d] = Dh);
}
function G2b(a, b, c, d, msg, k) {
const Xpos = 2 * _blake_ts_1.BSIGMA[k];
const Xl = msg[Xpos + 1] ^ TBL512[k * 2 + 1], Xh = msg[Xpos] ^ TBL512[k * 2]; // prettier-ignore
let Al = BBUF[2 * a + 1], Ah = BBUF[2 * a]; // prettier-ignore
let Bl = BBUF[2 * b + 1], Bh = BBUF[2 * b]; // prettier-ignore
let Cl = BBUF[2 * c + 1], Ch = BBUF[2 * c]; // prettier-ignore
let Dl = BBUF[2 * d + 1], Dh = BBUF[2 * d]; // prettier-ignore
// v[a] = (v[a] + v[b] + x) | 0;
let ll = u64.add3L(Al, Bl, Xl);
Ah = u64.add3H(ll, Ah, Bh, Xh);
Al = ll | 0;
// v[d] = rotr(v[d] ^ v[a], 16)
({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al });
({ Dh, Dl } = { Dh: u64.rotrSH(Dh, Dl, 16), Dl: u64.rotrSL(Dh, Dl, 16) });
// v[c] = (v[c] + v[d]) | 0;
({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl));
// v[b] = rotr(v[b] ^ v[c], 11)
({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl });
({ Bh, Bl } = { Bh: u64.rotrSH(Bh, Bl, 11), Bl: u64.rotrSL(Bh, Bl, 11) });
(BBUF[2 * a + 1] = Al), (BBUF[2 * a] = Ah);
(BBUF[2 * b + 1] = Bl), (BBUF[2 * b] = Bh);
(BBUF[2 * c + 1] = Cl), (BBUF[2 * c] = Ch);
(BBUF[2 * d + 1] = Dl), (BBUF[2 * d] = Dh);
}
class Blake1_64 extends BLAKE1 {
constructor(outputLen, IV, lengthFlag, opts = {}) {
super(128, outputLen, lengthFlag, 16, 8, B64C, opts);
this.v0l = IV[0] | 0;
this.v0h = IV[1] | 0;
this.v1l = IV[2] | 0;
this.v1h = IV[3] | 0;
this.v2l = IV[4] | 0;
this.v2h = IV[5] | 0;
this.v3l = IV[6] | 0;
this.v3h = IV[7] | 0;
this.v4l = IV[8] | 0;
this.v4h = IV[9] | 0;
this.v5l = IV[10] | 0;
this.v5h = IV[11] | 0;
this.v6l = IV[12] | 0;
this.v6h = IV[13] | 0;
this.v7l = IV[14] | 0;
this.v7h = IV[15] | 0;
}
// prettier-ignore
get() {
let { v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h } = this;
return [v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h];
}
// prettier-ignore
set(v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h) {
this.v0l = v0l | 0;
this.v0h = v0h | 0;
this.v1l = v1l | 0;
this.v1h = v1h | 0;
this.v2l = v2l | 0;
this.v2h = v2h | 0;
this.v3l = v3l | 0;
this.v3h = v3h | 0;
this.v4l = v4l | 0;
this.v4h = v4h | 0;
this.v5l = v5l | 0;
this.v5h = v5h | 0;
this.v6l = v6l | 0;
this.v6h = v6h | 0;
this.v7l = v7l | 0;
this.v7h = v7h | 0;
}
destroy() {
super.destroy();
this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
compress(view, offset, withLength = true) {
for (let i = 0; i < 32; i++, offset += 4)
BLAKE512_W[i] = view.getUint32(offset, false);
this.get().forEach((v, i) => (BBUF[i] = v)); // First half from state.
BBUF.set(this.constants.subarray(0, 16), 16);
if (withLength) {
const { h, l } = u64.fromBig(BigInt(this.length * 8));
BBUF[24] = (BBUF[24] ^ h) >>> 0;
BBUF[25] = (BBUF[25] ^ l) >>> 0;
BBUF[26] = (BBUF[26] ^ h) >>> 0;
BBUF[27] = (BBUF[27] ^ l) >>> 0;
}
for (let i = 0, k = 0; i < 16; i++) {
G1b(0, 4, 8, 12, BLAKE512_W, k++);
G2b(0, 4, 8, 12, BLAKE512_W, k++);
G1b(1, 5, 9, 13, BLAKE512_W, k++);
G2b(1, 5, 9, 13, BLAKE512_W, k++);
G1b(2, 6, 10, 14, BLAKE512_W, k++);
G2b(2, 6, 10, 14, BLAKE512_W, k++);
G1b(3, 7, 11, 15, BLAKE512_W, k++);
G2b(3, 7, 11, 15, BLAKE512_W, k++);
G1b(0, 5, 10, 15, BLAKE512_W, k++);
G2b(0, 5, 10, 15, BLAKE512_W, k++);
G1b(1, 6, 11, 12, BLAKE512_W, k++);
G2b(1, 6, 11, 12, BLAKE512_W, k++);
G1b(2, 7, 8, 13, BLAKE512_W, k++);
G2b(2, 7, 8, 13, BLAKE512_W, k++);
G1b(3, 4, 9, 14, BLAKE512_W, k++);
G2b(3, 4, 9, 14, BLAKE512_W, k++);
}
this.v0l ^= BBUF[0] ^ BBUF[16] ^ this.salt[0];
this.v0h ^= BBUF[1] ^ BBUF[17] ^ this.salt[1];
this.v1l ^= BBUF[2] ^ BBUF[18] ^ this.salt[2];
this.v1h ^= BBUF[3] ^ BBUF[19] ^ this.salt[3];
this.v2l ^= BBUF[4] ^ BBUF[20] ^ this.salt[4];
this.v2h ^= BBUF[5] ^ BBUF[21] ^ this.salt[5];
this.v3l ^= BBUF[6] ^ BBUF[22] ^ this.salt[6];
this.v3h ^= BBUF[7] ^ BBUF[23] ^ this.salt[7];
this.v4l ^= BBUF[8] ^ BBUF[24] ^ this.salt[0];
this.v4h ^= BBUF[9] ^ BBUF[25] ^ this.salt[1];
this.v5l ^= BBUF[10] ^ BBUF[26] ^ this.salt[2];
this.v5h ^= BBUF[11] ^ BBUF[27] ^ this.salt[3];
this.v6l ^= BBUF[12] ^ BBUF[28] ^ this.salt[4];
this.v6h ^= BBUF[13] ^ BBUF[29] ^ this.salt[5];
this.v7l ^= BBUF[14] ^ BBUF[30] ^ this.salt[6];
this.v7h ^= BBUF[15] ^ BBUF[31] ^ this.salt[7];
(0, utils_ts_1.clean)(BBUF, BLAKE512_W);
}
}
class BLAKE224 extends Blake1_32 {
constructor(opts = {}) {
super(28, B224_IV, 0, opts);
}
}
exports.BLAKE224 = BLAKE224;
class BLAKE256 extends Blake1_32 {
constructor(opts = {}) {
super(32, B256_IV, 1, opts);
}
}
exports.BLAKE256 = BLAKE256;
class BLAKE384 extends Blake1_64 {
constructor(opts = {}) {
super(48, B384_IV, 0, opts);
}
}
exports.BLAKE384 = BLAKE384;
class BLAKE512 extends Blake1_64 {
constructor(opts = {}) {
super(64, B512_IV, 1, opts);
}
}
exports.BLAKE512 = BLAKE512;
/** blake1-224 hash function */
exports.blake224 = (0, utils_ts_1.createOptHasher)((opts) => new BLAKE224(opts));
/** blake1-256 hash function */
exports.blake256 = (0, utils_ts_1.createOptHasher)((opts) => new BLAKE256(opts));
/** blake1-384 hash function */
exports.blake384 = (0, utils_ts_1.createOptHasher)((opts) => new BLAKE384(opts));
/** blake1-512 hash function */
exports.blake512 = (0, utils_ts_1.createOptHasher)((opts) => new BLAKE512(opts));
//# sourceMappingURL=blake1.js.map
File diff suppressed because one or more lines are too long
+116
View File
@@ -0,0 +1,116 @@
import { Hash, type CHashO, type Input } from './utils.ts';
/** Blake hash options. dkLen is output length. key is used in MAC mode. salt is used in KDF mode. */
export type Blake2Opts = {
dkLen?: number;
key?: Input;
salt?: Input;
personalization?: Input;
};
/** Class, from which others are subclassed. */
export declare abstract class BLAKE2<T extends BLAKE2<T>> extends Hash<T> {
protected abstract compress(msg: Uint32Array, offset: number, isLast: boolean): void;
protected abstract get(): number[];
protected abstract set(...args: number[]): void;
abstract destroy(): void;
protected buffer: Uint8Array;
protected buffer32: Uint32Array;
protected finished: boolean;
protected destroyed: boolean;
protected length: number;
protected pos: number;
readonly blockLen: number;
readonly outputLen: number;
constructor(blockLen: number, outputLen: number);
update(data: Input): this;
digestInto(out: Uint8Array): void;
digest(): Uint8Array;
_cloneInto(to?: T): T;
clone(): T;
}
export declare class BLAKE2b extends BLAKE2<BLAKE2b> {
private v0l;
private v0h;
private v1l;
private v1h;
private v2l;
private v2h;
private v3l;
private v3h;
private v4l;
private v4h;
private v5l;
private v5h;
private v6l;
private v6h;
private v7l;
private v7h;
constructor(opts?: Blake2Opts);
protected get(): [
number,
number,
number,
number,
number,
number,
number,
number,
number,
number,
number,
number,
number,
number,
number,
number
];
protected set(v0l: number, v0h: number, v1l: number, v1h: number, v2l: number, v2h: number, v3l: number, v3h: number, v4l: number, v4h: number, v5l: number, v5h: number, v6l: number, v6h: number, v7l: number, v7h: number): void;
protected compress(msg: Uint32Array, offset: number, isLast: boolean): void;
destroy(): void;
}
/**
* Blake2b hash function. 64-bit. 1.5x slower than blake2s in JS.
* @param msg - message that would be hashed
* @param opts - dkLen output length, key for MAC mode, salt, personalization
*/
export declare const blake2b: CHashO;
export type Num16 = {
v0: number;
v1: number;
v2: number;
v3: number;
v4: number;
v5: number;
v6: number;
v7: number;
v8: number;
v9: number;
v10: number;
v11: number;
v12: number;
v13: number;
v14: number;
v15: number;
};
export declare function compress(s: Uint8Array, offset: number, msg: Uint32Array, rounds: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number, v9: number, v10: number, v11: number, v12: number, v13: number, v14: number, v15: number): Num16;
export declare class BLAKE2s extends BLAKE2<BLAKE2s> {
private v0;
private v1;
private v2;
private v3;
private v4;
private v5;
private v6;
private v7;
constructor(opts?: Blake2Opts);
protected get(): [number, number, number, number, number, number, number, number];
protected set(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number): void;
protected compress(msg: Uint32Array, offset: number, isLast: boolean): void;
destroy(): void;
}
/**
* Blake2s hash function. Focuses on 8-bit to 32-bit platforms. 1.5x faster than blake2b in JS.
* @param msg - message that would be hashed
* @param opts - dkLen output length, key for MAC mode, salt, personalization
*/
export declare const blake2s: CHashO;
//# sourceMappingURL=blake2.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"blake2.d.ts","sourceRoot":"","sources":["src/blake2.ts"],"names":[],"mappings":"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"}
+420
View File
@@ -0,0 +1,420 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.blake2s = exports.BLAKE2s = exports.blake2b = exports.BLAKE2b = exports.BLAKE2 = void 0;
exports.compress = compress;
/**
* blake2b (64-bit) & blake2s (8 to 32-bit) hash functions.
* b could have been faster, but there is no fast u64 in js, so s is 1.5x faster.
* @module
*/
const _blake_ts_1 = require("./_blake.js");
const _md_ts_1 = require("./_md.js");
const u64 = require("./_u64.js");
// prettier-ignore
const utils_ts_1 = require("./utils.js");
// Same as SHA512_IV, but swapped endianness: LE instead of BE. iv[1] is iv[0], etc.
const B2B_IV = /* @__PURE__ */ Uint32Array.from([
0xf3bcc908, 0x6a09e667, 0x84caa73b, 0xbb67ae85, 0xfe94f82b, 0x3c6ef372, 0x5f1d36f1, 0xa54ff53a,
0xade682d1, 0x510e527f, 0x2b3e6c1f, 0x9b05688c, 0xfb41bd6b, 0x1f83d9ab, 0x137e2179, 0x5be0cd19,
]);
// Temporary buffer
const BBUF = /* @__PURE__ */ new Uint32Array(32);
// Mixing function G splitted in two halfs
function G1b(a, b, c, d, msg, x) {
// NOTE: V is LE here
const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore
let Al = BBUF[2 * a], Ah = BBUF[2 * a + 1]; // prettier-ignore
let Bl = BBUF[2 * b], Bh = BBUF[2 * b + 1]; // prettier-ignore
let Cl = BBUF[2 * c], Ch = BBUF[2 * c + 1]; // prettier-ignore
let Dl = BBUF[2 * d], Dh = BBUF[2 * d + 1]; // prettier-ignore
// v[a] = (v[a] + v[b] + x) | 0;
let ll = u64.add3L(Al, Bl, Xl);
Ah = u64.add3H(ll, Ah, Bh, Xh);
Al = ll | 0;
// v[d] = rotr(v[d] ^ v[a], 32)
({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al });
({ Dh, Dl } = { Dh: u64.rotr32H(Dh, Dl), Dl: u64.rotr32L(Dh, Dl) });
// v[c] = (v[c] + v[d]) | 0;
({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl));
// v[b] = rotr(v[b] ^ v[c], 24)
({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl });
({ Bh, Bl } = { Bh: u64.rotrSH(Bh, Bl, 24), Bl: u64.rotrSL(Bh, Bl, 24) });
(BBUF[2 * a] = Al), (BBUF[2 * a + 1] = Ah);
(BBUF[2 * b] = Bl), (BBUF[2 * b + 1] = Bh);
(BBUF[2 * c] = Cl), (BBUF[2 * c + 1] = Ch);
(BBUF[2 * d] = Dl), (BBUF[2 * d + 1] = Dh);
}
function G2b(a, b, c, d, msg, x) {
// NOTE: V is LE here
const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore
let Al = BBUF[2 * a], Ah = BBUF[2 * a + 1]; // prettier-ignore
let Bl = BBUF[2 * b], Bh = BBUF[2 * b + 1]; // prettier-ignore
let Cl = BBUF[2 * c], Ch = BBUF[2 * c + 1]; // prettier-ignore
let Dl = BBUF[2 * d], Dh = BBUF[2 * d + 1]; // prettier-ignore
// v[a] = (v[a] + v[b] + x) | 0;
let ll = u64.add3L(Al, Bl, Xl);
Ah = u64.add3H(ll, Ah, Bh, Xh);
Al = ll | 0;
// v[d] = rotr(v[d] ^ v[a], 16)
({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al });
({ Dh, Dl } = { Dh: u64.rotrSH(Dh, Dl, 16), Dl: u64.rotrSL(Dh, Dl, 16) });
// v[c] = (v[c] + v[d]) | 0;
({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl));
// v[b] = rotr(v[b] ^ v[c], 63)
({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl });
({ Bh, Bl } = { Bh: u64.rotrBH(Bh, Bl, 63), Bl: u64.rotrBL(Bh, Bl, 63) });
(BBUF[2 * a] = Al), (BBUF[2 * a + 1] = Ah);
(BBUF[2 * b] = Bl), (BBUF[2 * b + 1] = Bh);
(BBUF[2 * c] = Cl), (BBUF[2 * c + 1] = Ch);
(BBUF[2 * d] = Dl), (BBUF[2 * d + 1] = Dh);
}
function checkBlake2Opts(outputLen, opts = {}, keyLen, saltLen, persLen) {
(0, utils_ts_1.anumber)(keyLen);
if (outputLen < 0 || outputLen > keyLen)
throw new Error('outputLen bigger than keyLen');
const { key, salt, personalization } = opts;
if (key !== undefined && (key.length < 1 || key.length > keyLen))
throw new Error('key length must be undefined or 1..' + keyLen);
if (salt !== undefined && salt.length !== saltLen)
throw new Error('salt must be undefined or ' + saltLen);
if (personalization !== undefined && personalization.length !== persLen)
throw new Error('personalization must be undefined or ' + persLen);
}
/** Class, from which others are subclassed. */
class BLAKE2 extends utils_ts_1.Hash {
constructor(blockLen, outputLen) {
super();
this.finished = false;
this.destroyed = false;
this.length = 0;
this.pos = 0;
(0, utils_ts_1.anumber)(blockLen);
(0, utils_ts_1.anumber)(outputLen);
this.blockLen = blockLen;
this.outputLen = outputLen;
this.buffer = new Uint8Array(blockLen);
this.buffer32 = (0, utils_ts_1.u32)(this.buffer);
}
update(data) {
(0, utils_ts_1.aexists)(this);
data = (0, utils_ts_1.toBytes)(data);
(0, utils_ts_1.abytes)(data);
// Main difference with other hashes: there is flag for last block,
// so we cannot process current block before we know that there
// is the next one. This significantly complicates logic and reduces ability
// to do zero-copy processing
const { blockLen, buffer, buffer32 } = this;
const len = data.length;
const offset = data.byteOffset;
const buf = data.buffer;
for (let pos = 0; pos < len;) {
// If buffer is full and we still have input (don't process last block, same as blake2s)
if (this.pos === blockLen) {
(0, utils_ts_1.swap32IfBE)(buffer32);
this.compress(buffer32, 0, false);
(0, utils_ts_1.swap32IfBE)(buffer32);
this.pos = 0;
}
const take = Math.min(blockLen - this.pos, len - pos);
const dataOffset = offset + pos;
// full block && aligned to 4 bytes && not last in input
if (take === blockLen && !(dataOffset % 4) && pos + take < len) {
const data32 = new Uint32Array(buf, dataOffset, Math.floor((len - pos) / 4));
(0, utils_ts_1.swap32IfBE)(data32);
for (let pos32 = 0; pos + blockLen < len; pos32 += buffer32.length, pos += blockLen) {
this.length += blockLen;
this.compress(data32, pos32, false);
}
(0, utils_ts_1.swap32IfBE)(data32);
continue;
}
buffer.set(data.subarray(pos, pos + take), this.pos);
this.pos += take;
this.length += take;
pos += take;
}
return this;
}
digestInto(out) {
(0, utils_ts_1.aexists)(this);
(0, utils_ts_1.aoutput)(out, this);
const { pos, buffer32 } = this;
this.finished = true;
// Padding
(0, utils_ts_1.clean)(this.buffer.subarray(pos));
(0, utils_ts_1.swap32IfBE)(buffer32);
this.compress(buffer32, 0, true);
(0, utils_ts_1.swap32IfBE)(buffer32);
const out32 = (0, utils_ts_1.u32)(out);
this.get().forEach((v, i) => (out32[i] = (0, utils_ts_1.swap8IfBE)(v)));
}
digest() {
const { buffer, outputLen } = this;
this.digestInto(buffer);
const res = buffer.slice(0, outputLen);
this.destroy();
return res;
}
_cloneInto(to) {
const { buffer, length, finished, destroyed, outputLen, pos } = this;
to || (to = new this.constructor({ dkLen: outputLen }));
to.set(...this.get());
to.buffer.set(buffer);
to.destroyed = destroyed;
to.finished = finished;
to.length = length;
to.pos = pos;
// @ts-ignore
to.outputLen = outputLen;
return to;
}
clone() {
return this._cloneInto();
}
}
exports.BLAKE2 = BLAKE2;
class BLAKE2b extends BLAKE2 {
constructor(opts = {}) {
const olen = opts.dkLen === undefined ? 64 : opts.dkLen;
super(128, olen);
// Same as SHA-512, but LE
this.v0l = B2B_IV[0] | 0;
this.v0h = B2B_IV[1] | 0;
this.v1l = B2B_IV[2] | 0;
this.v1h = B2B_IV[3] | 0;
this.v2l = B2B_IV[4] | 0;
this.v2h = B2B_IV[5] | 0;
this.v3l = B2B_IV[6] | 0;
this.v3h = B2B_IV[7] | 0;
this.v4l = B2B_IV[8] | 0;
this.v4h = B2B_IV[9] | 0;
this.v5l = B2B_IV[10] | 0;
this.v5h = B2B_IV[11] | 0;
this.v6l = B2B_IV[12] | 0;
this.v6h = B2B_IV[13] | 0;
this.v7l = B2B_IV[14] | 0;
this.v7h = B2B_IV[15] | 0;
checkBlake2Opts(olen, opts, 64, 16, 16);
let { key, personalization, salt } = opts;
let keyLength = 0;
if (key !== undefined) {
key = (0, utils_ts_1.toBytes)(key);
keyLength = key.length;
}
this.v0l ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24);
if (salt !== undefined) {
salt = (0, utils_ts_1.toBytes)(salt);
const slt = (0, utils_ts_1.u32)(salt);
this.v4l ^= (0, utils_ts_1.swap8IfBE)(slt[0]);
this.v4h ^= (0, utils_ts_1.swap8IfBE)(slt[1]);
this.v5l ^= (0, utils_ts_1.swap8IfBE)(slt[2]);
this.v5h ^= (0, utils_ts_1.swap8IfBE)(slt[3]);
}
if (personalization !== undefined) {
personalization = (0, utils_ts_1.toBytes)(personalization);
const pers = (0, utils_ts_1.u32)(personalization);
this.v6l ^= (0, utils_ts_1.swap8IfBE)(pers[0]);
this.v6h ^= (0, utils_ts_1.swap8IfBE)(pers[1]);
this.v7l ^= (0, utils_ts_1.swap8IfBE)(pers[2]);
this.v7h ^= (0, utils_ts_1.swap8IfBE)(pers[3]);
}
if (key !== undefined) {
// Pad to blockLen and update
const tmp = new Uint8Array(this.blockLen);
tmp.set(key);
this.update(tmp);
}
}
// prettier-ignore
get() {
let { v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h } = this;
return [v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h];
}
// prettier-ignore
set(v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h) {
this.v0l = v0l | 0;
this.v0h = v0h | 0;
this.v1l = v1l | 0;
this.v1h = v1h | 0;
this.v2l = v2l | 0;
this.v2h = v2h | 0;
this.v3l = v3l | 0;
this.v3h = v3h | 0;
this.v4l = v4l | 0;
this.v4h = v4h | 0;
this.v5l = v5l | 0;
this.v5h = v5h | 0;
this.v6l = v6l | 0;
this.v6h = v6h | 0;
this.v7l = v7l | 0;
this.v7h = v7h | 0;
}
compress(msg, offset, isLast) {
this.get().forEach((v, i) => (BBUF[i] = v)); // First half from state.
BBUF.set(B2B_IV, 16); // Second half from IV.
let { h, l } = u64.fromBig(BigInt(this.length));
BBUF[24] = B2B_IV[8] ^ l; // Low word of the offset.
BBUF[25] = B2B_IV[9] ^ h; // High word.
// Invert all bits for last block
if (isLast) {
BBUF[28] = ~BBUF[28];
BBUF[29] = ~BBUF[29];
}
let j = 0;
const s = _blake_ts_1.BSIGMA;
for (let i = 0; i < 12; i++) {
G1b(0, 4, 8, 12, msg, offset + 2 * s[j++]);
G2b(0, 4, 8, 12, msg, offset + 2 * s[j++]);
G1b(1, 5, 9, 13, msg, offset + 2 * s[j++]);
G2b(1, 5, 9, 13, msg, offset + 2 * s[j++]);
G1b(2, 6, 10, 14, msg, offset + 2 * s[j++]);
G2b(2, 6, 10, 14, msg, offset + 2 * s[j++]);
G1b(3, 7, 11, 15, msg, offset + 2 * s[j++]);
G2b(3, 7, 11, 15, msg, offset + 2 * s[j++]);
G1b(0, 5, 10, 15, msg, offset + 2 * s[j++]);
G2b(0, 5, 10, 15, msg, offset + 2 * s[j++]);
G1b(1, 6, 11, 12, msg, offset + 2 * s[j++]);
G2b(1, 6, 11, 12, msg, offset + 2 * s[j++]);
G1b(2, 7, 8, 13, msg, offset + 2 * s[j++]);
G2b(2, 7, 8, 13, msg, offset + 2 * s[j++]);
G1b(3, 4, 9, 14, msg, offset + 2 * s[j++]);
G2b(3, 4, 9, 14, msg, offset + 2 * s[j++]);
}
this.v0l ^= BBUF[0] ^ BBUF[16];
this.v0h ^= BBUF[1] ^ BBUF[17];
this.v1l ^= BBUF[2] ^ BBUF[18];
this.v1h ^= BBUF[3] ^ BBUF[19];
this.v2l ^= BBUF[4] ^ BBUF[20];
this.v2h ^= BBUF[5] ^ BBUF[21];
this.v3l ^= BBUF[6] ^ BBUF[22];
this.v3h ^= BBUF[7] ^ BBUF[23];
this.v4l ^= BBUF[8] ^ BBUF[24];
this.v4h ^= BBUF[9] ^ BBUF[25];
this.v5l ^= BBUF[10] ^ BBUF[26];
this.v5h ^= BBUF[11] ^ BBUF[27];
this.v6l ^= BBUF[12] ^ BBUF[28];
this.v6h ^= BBUF[13] ^ BBUF[29];
this.v7l ^= BBUF[14] ^ BBUF[30];
this.v7h ^= BBUF[15] ^ BBUF[31];
(0, utils_ts_1.clean)(BBUF);
}
destroy() {
this.destroyed = true;
(0, utils_ts_1.clean)(this.buffer32);
this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
}
exports.BLAKE2b = BLAKE2b;
/**
* Blake2b hash function. 64-bit. 1.5x slower than blake2s in JS.
* @param msg - message that would be hashed
* @param opts - dkLen output length, key for MAC mode, salt, personalization
*/
exports.blake2b = (0, utils_ts_1.createOptHasher)((opts) => new BLAKE2b(opts));
// prettier-ignore
function compress(s, offset, msg, rounds, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) {
let j = 0;
for (let i = 0; i < rounds; i++) {
({ a: v0, b: v4, c: v8, d: v12 } = (0, _blake_ts_1.G1s)(v0, v4, v8, v12, msg[offset + s[j++]]));
({ a: v0, b: v4, c: v8, d: v12 } = (0, _blake_ts_1.G2s)(v0, v4, v8, v12, msg[offset + s[j++]]));
({ a: v1, b: v5, c: v9, d: v13 } = (0, _blake_ts_1.G1s)(v1, v5, v9, v13, msg[offset + s[j++]]));
({ a: v1, b: v5, c: v9, d: v13 } = (0, _blake_ts_1.G2s)(v1, v5, v9, v13, msg[offset + s[j++]]));
({ a: v2, b: v6, c: v10, d: v14 } = (0, _blake_ts_1.G1s)(v2, v6, v10, v14, msg[offset + s[j++]]));
({ a: v2, b: v6, c: v10, d: v14 } = (0, _blake_ts_1.G2s)(v2, v6, v10, v14, msg[offset + s[j++]]));
({ a: v3, b: v7, c: v11, d: v15 } = (0, _blake_ts_1.G1s)(v3, v7, v11, v15, msg[offset + s[j++]]));
({ a: v3, b: v7, c: v11, d: v15 } = (0, _blake_ts_1.G2s)(v3, v7, v11, v15, msg[offset + s[j++]]));
({ a: v0, b: v5, c: v10, d: v15 } = (0, _blake_ts_1.G1s)(v0, v5, v10, v15, msg[offset + s[j++]]));
({ a: v0, b: v5, c: v10, d: v15 } = (0, _blake_ts_1.G2s)(v0, v5, v10, v15, msg[offset + s[j++]]));
({ a: v1, b: v6, c: v11, d: v12 } = (0, _blake_ts_1.G1s)(v1, v6, v11, v12, msg[offset + s[j++]]));
({ a: v1, b: v6, c: v11, d: v12 } = (0, _blake_ts_1.G2s)(v1, v6, v11, v12, msg[offset + s[j++]]));
({ a: v2, b: v7, c: v8, d: v13 } = (0, _blake_ts_1.G1s)(v2, v7, v8, v13, msg[offset + s[j++]]));
({ a: v2, b: v7, c: v8, d: v13 } = (0, _blake_ts_1.G2s)(v2, v7, v8, v13, msg[offset + s[j++]]));
({ a: v3, b: v4, c: v9, d: v14 } = (0, _blake_ts_1.G1s)(v3, v4, v9, v14, msg[offset + s[j++]]));
({ a: v3, b: v4, c: v9, d: v14 } = (0, _blake_ts_1.G2s)(v3, v4, v9, v14, msg[offset + s[j++]]));
}
return { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 };
}
const B2S_IV = _md_ts_1.SHA256_IV;
class BLAKE2s extends BLAKE2 {
constructor(opts = {}) {
const olen = opts.dkLen === undefined ? 32 : opts.dkLen;
super(64, olen);
// Internal state, same as SHA-256
this.v0 = B2S_IV[0] | 0;
this.v1 = B2S_IV[1] | 0;
this.v2 = B2S_IV[2] | 0;
this.v3 = B2S_IV[3] | 0;
this.v4 = B2S_IV[4] | 0;
this.v5 = B2S_IV[5] | 0;
this.v6 = B2S_IV[6] | 0;
this.v7 = B2S_IV[7] | 0;
checkBlake2Opts(olen, opts, 32, 8, 8);
let { key, personalization, salt } = opts;
let keyLength = 0;
if (key !== undefined) {
key = (0, utils_ts_1.toBytes)(key);
keyLength = key.length;
}
this.v0 ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24);
if (salt !== undefined) {
salt = (0, utils_ts_1.toBytes)(salt);
const slt = (0, utils_ts_1.u32)(salt);
this.v4 ^= (0, utils_ts_1.swap8IfBE)(slt[0]);
this.v5 ^= (0, utils_ts_1.swap8IfBE)(slt[1]);
}
if (personalization !== undefined) {
personalization = (0, utils_ts_1.toBytes)(personalization);
const pers = (0, utils_ts_1.u32)(personalization);
this.v6 ^= (0, utils_ts_1.swap8IfBE)(pers[0]);
this.v7 ^= (0, utils_ts_1.swap8IfBE)(pers[1]);
}
if (key !== undefined) {
// Pad to blockLen and update
(0, utils_ts_1.abytes)(key);
const tmp = new Uint8Array(this.blockLen);
tmp.set(key);
this.update(tmp);
}
}
get() {
const { v0, v1, v2, v3, v4, v5, v6, v7 } = this;
return [v0, v1, v2, v3, v4, v5, v6, v7];
}
// prettier-ignore
set(v0, v1, v2, v3, v4, v5, v6, v7) {
this.v0 = v0 | 0;
this.v1 = v1 | 0;
this.v2 = v2 | 0;
this.v3 = v3 | 0;
this.v4 = v4 | 0;
this.v5 = v5 | 0;
this.v6 = v6 | 0;
this.v7 = v7 | 0;
}
compress(msg, offset, isLast) {
const { h, l } = u64.fromBig(BigInt(this.length));
// prettier-ignore
const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(_blake_ts_1.BSIGMA, offset, msg, 10, this.v0, this.v1, this.v2, this.v3, this.v4, this.v5, this.v6, this.v7, B2S_IV[0], B2S_IV[1], B2S_IV[2], B2S_IV[3], l ^ B2S_IV[4], h ^ B2S_IV[5], isLast ? ~B2S_IV[6] : B2S_IV[6], B2S_IV[7]);
this.v0 ^= v0 ^ v8;
this.v1 ^= v1 ^ v9;
this.v2 ^= v2 ^ v10;
this.v3 ^= v3 ^ v11;
this.v4 ^= v4 ^ v12;
this.v5 ^= v5 ^ v13;
this.v6 ^= v6 ^ v14;
this.v7 ^= v7 ^ v15;
}
destroy() {
this.destroyed = true;
(0, utils_ts_1.clean)(this.buffer32);
this.set(0, 0, 0, 0, 0, 0, 0, 0);
}
}
exports.BLAKE2s = BLAKE2s;
/**
* Blake2s hash function. Focuses on 8-bit to 32-bit platforms. 1.5x faster than blake2b in JS.
* @param msg - message that would be hashed
* @param opts - dkLen output length, key for MAC mode, salt, personalization
*/
exports.blake2s = (0, utils_ts_1.createOptHasher)((opts) => new BLAKE2s(opts));
//# sourceMappingURL=blake2.js.map
File diff suppressed because one or more lines are too long
+11
View File
@@ -0,0 +1,11 @@
/**
* Blake2b hash function. Focuses on 64-bit platforms, but in JS speed different from Blake2s is negligible.
* @module
* @deprecated
*/
import { BLAKE2b as B2B, blake2b as b2b } from './blake2.ts';
/** @deprecated Use import from `noble/hashes/blake2` module */
export declare const BLAKE2b: typeof B2B;
/** @deprecated Use import from `noble/hashes/blake2` module */
export declare const blake2b: typeof b2b;
//# sourceMappingURL=blake2b.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"blake2b.d.ts","sourceRoot":"","sources":["src/blake2b.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,OAAO,IAAI,GAAG,EAAE,OAAO,IAAI,GAAG,EAAE,MAAM,aAAa,CAAC;AAC7D,+DAA+D;AAC/D,eAAO,MAAM,OAAO,EAAE,OAAO,GAAS,CAAC;AACvC,+DAA+D;AAC/D,eAAO,MAAM,OAAO,EAAE,OAAO,GAAS,CAAC"}
+14
View File
@@ -0,0 +1,14 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.blake2b = exports.BLAKE2b = void 0;
/**
* Blake2b hash function. Focuses on 64-bit platforms, but in JS speed different from Blake2s is negligible.
* @module
* @deprecated
*/
const blake2_ts_1 = require("./blake2.js");
/** @deprecated Use import from `noble/hashes/blake2` module */
exports.BLAKE2b = blake2_ts_1.BLAKE2b;
/** @deprecated Use import from `noble/hashes/blake2` module */
exports.blake2b = blake2_ts_1.blake2b;
//# sourceMappingURL=blake2b.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"blake2b.js","sourceRoot":"","sources":["src/blake2b.ts"],"names":[],"mappings":";;;AAAA;;;;GAIG;AACH,2CAA6D;AAC7D,+DAA+D;AAClD,QAAA,OAAO,GAAe,mBAAG,CAAC;AACvC,+DAA+D;AAClD,QAAA,OAAO,GAAe,mBAAG,CAAC"}
+20
View File
@@ -0,0 +1,20 @@
/**
* Blake2s hash function. Focuses on 8-bit to 32-bit platforms. blake2b for 64-bit, but in JS it is slower.
* @module
* @deprecated
*/
import { G1s as G1s_n, G2s as G2s_n } from './_blake.ts';
import { BLAKE2s as B2S, blake2s as b2s, compress as compress_n } from './blake2.ts';
/** @deprecated Use import from `noble/hashes/blake2` module */
export declare const B2S_IV: Uint32Array;
/** @deprecated Use import from `noble/hashes/blake2` module */
export declare const G1s: typeof G1s_n;
/** @deprecated Use import from `noble/hashes/blake2` module */
export declare const G2s: typeof G2s_n;
/** @deprecated Use import from `noble/hashes/blake2` module */
export declare const compress: typeof compress_n;
/** @deprecated Use import from `noble/hashes/blake2` module */
export declare const BLAKE2s: typeof B2S;
/** @deprecated Use import from `noble/hashes/blake2` module */
export declare const blake2s: typeof b2s;
//# sourceMappingURL=blake2s.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"blake2s.d.ts","sourceRoot":"","sources":["src/blake2s.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,GAAG,IAAI,KAAK,EAAE,GAAG,IAAI,KAAK,EAAE,MAAM,aAAa,CAAC;AAEzD,OAAO,EAAE,OAAO,IAAI,GAAG,EAAE,OAAO,IAAI,GAAG,EAAE,QAAQ,IAAI,UAAU,EAAE,MAAM,aAAa,CAAC;AACrF,+DAA+D;AAC/D,eAAO,MAAM,MAAM,EAAE,WAAuB,CAAC;AAC7C,+DAA+D;AAC/D,eAAO,MAAM,GAAG,EAAE,OAAO,KAAa,CAAC;AACvC,+DAA+D;AAC/D,eAAO,MAAM,GAAG,EAAE,OAAO,KAAa,CAAC;AACvC,+DAA+D;AAC/D,eAAO,MAAM,QAAQ,EAAE,OAAO,UAAuB,CAAC;AACtD,+DAA+D;AAC/D,eAAO,MAAM,OAAO,EAAE,OAAO,GAAS,CAAC;AACvC,+DAA+D;AAC/D,eAAO,MAAM,OAAO,EAAE,OAAO,GAAS,CAAC"}
+24
View File
@@ -0,0 +1,24 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.blake2s = exports.BLAKE2s = exports.compress = exports.G2s = exports.G1s = exports.B2S_IV = void 0;
/**
* Blake2s hash function. Focuses on 8-bit to 32-bit platforms. blake2b for 64-bit, but in JS it is slower.
* @module
* @deprecated
*/
const _blake_ts_1 = require("./_blake.js");
const _md_ts_1 = require("./_md.js");
const blake2_ts_1 = require("./blake2.js");
/** @deprecated Use import from `noble/hashes/blake2` module */
exports.B2S_IV = _md_ts_1.SHA256_IV;
/** @deprecated Use import from `noble/hashes/blake2` module */
exports.G1s = _blake_ts_1.G1s;
/** @deprecated Use import from `noble/hashes/blake2` module */
exports.G2s = _blake_ts_1.G2s;
/** @deprecated Use import from `noble/hashes/blake2` module */
exports.compress = blake2_ts_1.compress;
/** @deprecated Use import from `noble/hashes/blake2` module */
exports.BLAKE2s = blake2_ts_1.BLAKE2s;
/** @deprecated Use import from `noble/hashes/blake2` module */
exports.blake2s = blake2_ts_1.blake2s;
//# sourceMappingURL=blake2s.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"blake2s.js","sourceRoot":"","sources":["src/blake2s.ts"],"names":[],"mappings":";;;AAAA;;;;GAIG;AACH,2CAAyD;AACzD,qCAAqC;AACrC,2CAAqF;AACrF,+DAA+D;AAClD,QAAA,MAAM,GAAgB,kBAAS,CAAC;AAC7C,+DAA+D;AAClD,QAAA,GAAG,GAAiB,eAAK,CAAC;AACvC,+DAA+D;AAClD,QAAA,GAAG,GAAiB,eAAK,CAAC;AACvC,+DAA+D;AAClD,QAAA,QAAQ,GAAsB,oBAAU,CAAC;AACtD,+DAA+D;AAClD,QAAA,OAAO,GAAe,mBAAG,CAAC;AACvC,+DAA+D;AAClD,QAAA,OAAO,GAAe,mBAAG,CAAC"}
+54
View File
@@ -0,0 +1,54 @@
import { BLAKE2 } from './blake2.ts';
import { type CHashXO, type HashXOF, type Input } from './utils.ts';
/**
* Ensure to use EITHER `key` OR `context`, not both.
*
* * `key`: 32-byte MAC key.
* * `context`: string for KDF. Should be hardcoded, globally unique, and application - specific.
* A good default format for the context string is "[application] [commit timestamp] [purpose]".
*/
export type Blake3Opts = {
dkLen?: number;
key?: Input;
context?: Input;
};
/** Blake3 hash. Can be used as MAC and KDF. */
export declare class BLAKE3 extends BLAKE2<BLAKE3> implements HashXOF<BLAKE3> {
private chunkPos;
private chunksDone;
private flags;
private IV;
private state;
private stack;
private posOut;
private bufferOut32;
private bufferOut;
private chunkOut;
private enableXOF;
constructor(opts?: Blake3Opts, flags?: number);
protected get(): [];
protected set(): void;
private b2Compress;
protected compress(buf: Uint32Array, bufPos?: number, isLast?: boolean): void;
_cloneInto(to?: BLAKE3): BLAKE3;
destroy(): void;
private b2CompressOut;
protected finish(): void;
private writeInto;
xofInto(out: Uint8Array): Uint8Array;
xof(bytes: number): Uint8Array;
digestInto(out: Uint8Array): Uint8Array;
digest(): Uint8Array;
}
/**
* BLAKE3 hash function. Can be used as MAC and KDF.
* @param msg - message that would be hashed
* @param opts - `dkLen` for output length, `key` for MAC mode, `context` for KDF mode
* @example
* const data = new Uint8Array(32);
* const hash = blake3(data);
* const mac = blake3(data, { key: new Uint8Array(32) });
* const kdf = blake3(data, { context: 'application name' });
*/
export declare const blake3: CHashXO;
//# sourceMappingURL=blake3.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"blake3.d.ts","sourceRoot":"","sources":["src/blake3.ts"],"names":[],"mappings":"AAeA,OAAO,EAAE,MAAM,EAAY,MAAM,aAAa,CAAC;AAE/C,OAAO,EAGL,KAAK,OAAO,EAAE,KAAK,OAAO,EAAE,KAAK,KAAK,EACvC,MAAM,YAAY,CAAC;AAwBpB;;;;;;GAMG;AACH,MAAM,MAAM,UAAU,GAAG;IAAE,KAAK,CAAC,EAAE,MAAM,CAAC;IAAC,GAAG,CAAC,EAAE,KAAK,CAAC;IAAC,OAAO,CAAC,EAAE,KAAK,CAAA;CAAE,CAAC;AAE1E,+CAA+C;AAC/C,qBAAa,MAAO,SAAQ,MAAM,CAAC,MAAM,CAAE,YAAW,OAAO,CAAC,MAAM,CAAC;IACnE,OAAO,CAAC,QAAQ,CAAK;IACrB,OAAO,CAAC,UAAU,CAAK;IACvB,OAAO,CAAC,KAAK,CAAS;IACtB,OAAO,CAAC,EAAE,CAAc;IACxB,OAAO,CAAC,KAAK,CAAc;IAC3B,OAAO,CAAC,KAAK,CAAqB;IAElC,OAAO,CAAC,MAAM,CAAK;IACnB,OAAO,CAAC,WAAW,CAAuB;IAC1C,OAAO,CAAC,SAAS,CAAa;IAC9B,OAAO,CAAC,QAAQ,CAAK;IACrB,OAAO,CAAC,SAAS,CAAQ;gBAEb,IAAI,GAAE,UAAe,EAAE,KAAK,SAAI;IA2B5C,SAAS,CAAC,GAAG,IAAI,EAAE;IAGnB,SAAS,CAAC,GAAG,IAAI,IAAI;IACrB,OAAO,CAAC,UAAU;IAmBlB,SAAS,CAAC,QAAQ,CAAC,GAAG,EAAE,WAAW,EAAE,MAAM,GAAE,MAAU,EAAE,MAAM,GAAE,OAAe,GAAG,IAAI;IAiCvF,UAAU,CAAC,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM;IAe/B,OAAO,IAAI,IAAI;IAMf,OAAO,CAAC,aAAa;IA+BrB,SAAS,CAAC,MAAM,IAAI,IAAI;IAoBxB,OAAO,CAAC,SAAS;IAcjB,OAAO,CAAC,GAAG,EAAE,UAAU,GAAG,UAAU;IAIpC,GAAG,CAAC,KAAK,EAAE,MAAM,GAAG,UAAU;IAI9B,UAAU,CAAC,GAAG,EAAE,UAAU,GAAG,UAAU;IAQvC,MAAM,IAAI,UAAU;CAGrB;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,MAAM,EAAE,OAEpB,CAAC"}
+255
View File
@@ -0,0 +1,255 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.blake3 = exports.BLAKE3 = void 0;
/**
* Blake3 fast hash is Blake2 with reduced security (round count). Can also be used as MAC & KDF.
*
* It is advertised as "the fastest cryptographic hash". However, it isn't true in JS.
* Why is this so slow? While it should be 6x faster than blake2b, perf diff is only 20%:
*
* * There is only 30% reduction in number of rounds from blake2s
* * Speed-up comes from tree structure, which is parallelized using SIMD & threading.
* These features are not present in JS, so we only get overhead from trees.
* * Parallelization only happens on 1024-byte chunks: there is no benefit for small inputs.
* * It is still possible to make it faster using: a) loop unrolling b) web workers c) wasm
* @module
*/
const _md_ts_1 = require("./_md.js");
const _u64_ts_1 = require("./_u64.js");
const blake2_ts_1 = require("./blake2.js");
// prettier-ignore
const utils_ts_1 = require("./utils.js");
// Flag bitset
const B3_Flags = {
CHUNK_START: 0b1,
CHUNK_END: 0b10,
PARENT: 0b100,
ROOT: 0b1000,
KEYED_HASH: 0b10000,
DERIVE_KEY_CONTEXT: 0b100000,
DERIVE_KEY_MATERIAL: 0b1000000,
};
const B3_IV = _md_ts_1.SHA256_IV.slice();
const B3_SIGMA = /* @__PURE__ */ (() => {
const Id = Array.from({ length: 16 }, (_, i) => i);
const permute = (arr) => [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8].map((i) => arr[i]);
const res = [];
for (let i = 0, v = Id; i < 7; i++, v = permute(v))
res.push(...v);
return Uint8Array.from(res);
})();
/** Blake3 hash. Can be used as MAC and KDF. */
class BLAKE3 extends blake2_ts_1.BLAKE2 {
constructor(opts = {}, flags = 0) {
super(64, opts.dkLen === undefined ? 32 : opts.dkLen);
this.chunkPos = 0; // Position of current block in chunk
this.chunksDone = 0; // How many chunks we already have
this.flags = 0 | 0;
this.stack = [];
// Output
this.posOut = 0;
this.bufferOut32 = new Uint32Array(16);
this.chunkOut = 0; // index of output chunk
this.enableXOF = true;
const { key, context } = opts;
const hasContext = context !== undefined;
if (key !== undefined) {
if (hasContext)
throw new Error('Only "key" or "context" can be specified at same time');
const k = (0, utils_ts_1.toBytes)(key).slice();
(0, utils_ts_1.abytes)(k, 32);
this.IV = (0, utils_ts_1.u32)(k);
(0, utils_ts_1.swap32IfBE)(this.IV);
this.flags = flags | B3_Flags.KEYED_HASH;
}
else if (hasContext) {
const ctx = (0, utils_ts_1.toBytes)(context);
const contextKey = new BLAKE3({ dkLen: 32 }, B3_Flags.DERIVE_KEY_CONTEXT)
.update(ctx)
.digest();
this.IV = (0, utils_ts_1.u32)(contextKey);
(0, utils_ts_1.swap32IfBE)(this.IV);
this.flags = flags | B3_Flags.DERIVE_KEY_MATERIAL;
}
else {
this.IV = B3_IV.slice();
this.flags = flags;
}
this.state = this.IV.slice();
this.bufferOut = (0, utils_ts_1.u8)(this.bufferOut32);
}
// Unused
get() {
return [];
}
set() { }
b2Compress(counter, flags, buf, bufPos = 0) {
const { state: s, pos } = this;
const { h, l } = (0, _u64_ts_1.fromBig)(BigInt(counter), true);
// prettier-ignore
const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = (0, blake2_ts_1.compress)(B3_SIGMA, bufPos, buf, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], B3_IV[0], B3_IV[1], B3_IV[2], B3_IV[3], h, l, pos, flags);
s[0] = v0 ^ v8;
s[1] = v1 ^ v9;
s[2] = v2 ^ v10;
s[3] = v3 ^ v11;
s[4] = v4 ^ v12;
s[5] = v5 ^ v13;
s[6] = v6 ^ v14;
s[7] = v7 ^ v15;
}
compress(buf, bufPos = 0, isLast = false) {
// Compress last block
let flags = this.flags;
if (!this.chunkPos)
flags |= B3_Flags.CHUNK_START;
if (this.chunkPos === 15 || isLast)
flags |= B3_Flags.CHUNK_END;
if (!isLast)
this.pos = this.blockLen;
this.b2Compress(this.chunksDone, flags, buf, bufPos);
this.chunkPos += 1;
// If current block is last in chunk (16 blocks), then compress chunks
if (this.chunkPos === 16 || isLast) {
let chunk = this.state;
this.state = this.IV.slice();
// If not the last one, compress only when there are trailing zeros in chunk counter
// chunks used as binary tree where current stack is path. Zero means current leaf is finished and can be compressed.
// 1 (001) - leaf not finished (just push current chunk to stack)
// 2 (010) - leaf finished at depth=1 (merge with last elm on stack and push back)
// 3 (011) - last leaf not finished
// 4 (100) - leafs finished at depth=1 and depth=2
for (let last, chunks = this.chunksDone + 1; isLast || !(chunks & 1); chunks >>= 1) {
if (!(last = this.stack.pop()))
break;
this.buffer32.set(last, 0);
this.buffer32.set(chunk, 8);
this.pos = this.blockLen;
this.b2Compress(0, this.flags | B3_Flags.PARENT, this.buffer32, 0);
chunk = this.state;
this.state = this.IV.slice();
}
this.chunksDone++;
this.chunkPos = 0;
this.stack.push(chunk);
}
this.pos = 0;
}
_cloneInto(to) {
to = super._cloneInto(to);
const { IV, flags, state, chunkPos, posOut, chunkOut, stack, chunksDone } = this;
to.state.set(state.slice());
to.stack = stack.map((i) => Uint32Array.from(i));
to.IV.set(IV);
to.flags = flags;
to.chunkPos = chunkPos;
to.chunksDone = chunksDone;
to.posOut = posOut;
to.chunkOut = chunkOut;
to.enableXOF = this.enableXOF;
to.bufferOut32.set(this.bufferOut32);
return to;
}
destroy() {
this.destroyed = true;
(0, utils_ts_1.clean)(this.state, this.buffer32, this.IV, this.bufferOut32);
(0, utils_ts_1.clean)(...this.stack);
}
// Same as b2Compress, but doesn't modify state and returns 16 u32 array (instead of 8)
b2CompressOut() {
const { state: s, pos, flags, buffer32, bufferOut32: out32 } = this;
const { h, l } = (0, _u64_ts_1.fromBig)(BigInt(this.chunkOut++));
(0, utils_ts_1.swap32IfBE)(buffer32);
// prettier-ignore
const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = (0, blake2_ts_1.compress)(B3_SIGMA, 0, buffer32, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], B3_IV[0], B3_IV[1], B3_IV[2], B3_IV[3], l, h, pos, flags);
out32[0] = v0 ^ v8;
out32[1] = v1 ^ v9;
out32[2] = v2 ^ v10;
out32[3] = v3 ^ v11;
out32[4] = v4 ^ v12;
out32[5] = v5 ^ v13;
out32[6] = v6 ^ v14;
out32[7] = v7 ^ v15;
out32[8] = s[0] ^ v8;
out32[9] = s[1] ^ v9;
out32[10] = s[2] ^ v10;
out32[11] = s[3] ^ v11;
out32[12] = s[4] ^ v12;
out32[13] = s[5] ^ v13;
out32[14] = s[6] ^ v14;
out32[15] = s[7] ^ v15;
(0, utils_ts_1.swap32IfBE)(buffer32);
(0, utils_ts_1.swap32IfBE)(out32);
this.posOut = 0;
}
finish() {
if (this.finished)
return;
this.finished = true;
// Padding
(0, utils_ts_1.clean)(this.buffer.subarray(this.pos));
// Process last chunk
let flags = this.flags | B3_Flags.ROOT;
if (this.stack.length) {
flags |= B3_Flags.PARENT;
(0, utils_ts_1.swap32IfBE)(this.buffer32);
this.compress(this.buffer32, 0, true);
(0, utils_ts_1.swap32IfBE)(this.buffer32);
this.chunksDone = 0;
this.pos = this.blockLen;
}
else {
flags |= (!this.chunkPos ? B3_Flags.CHUNK_START : 0) | B3_Flags.CHUNK_END;
}
this.flags = flags;
this.b2CompressOut();
}
writeInto(out) {
(0, utils_ts_1.aexists)(this, false);
(0, utils_ts_1.abytes)(out);
this.finish();
const { blockLen, bufferOut } = this;
for (let pos = 0, len = out.length; pos < len;) {
if (this.posOut >= blockLen)
this.b2CompressOut();
const take = Math.min(blockLen - this.posOut, len - pos);
out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
this.posOut += take;
pos += take;
}
return out;
}
xofInto(out) {
if (!this.enableXOF)
throw new Error('XOF is not possible after digest call');
return this.writeInto(out);
}
xof(bytes) {
(0, utils_ts_1.anumber)(bytes);
return this.xofInto(new Uint8Array(bytes));
}
digestInto(out) {
(0, utils_ts_1.aoutput)(out, this);
if (this.finished)
throw new Error('digest() was already called');
this.enableXOF = false;
this.writeInto(out);
this.destroy();
return out;
}
digest() {
return this.digestInto(new Uint8Array(this.outputLen));
}
}
exports.BLAKE3 = BLAKE3;
/**
* BLAKE3 hash function. Can be used as MAC and KDF.
* @param msg - message that would be hashed
* @param opts - `dkLen` for output length, `key` for MAC mode, `context` for KDF mode
* @example
* const data = new Uint8Array(32);
* const hash = blake3(data);
* const mac = blake3(data, { key: new Uint8Array(32) });
* const kdf = blake3(data, { context: 'application name' });
*/
exports.blake3 = (0, utils_ts_1.createXOFer)((opts) => new BLAKE3(opts));
//# sourceMappingURL=blake3.js.map
File diff suppressed because one or more lines are too long
+2
View File
@@ -0,0 +1,2 @@
export declare const crypto: any;
//# sourceMappingURL=crypto.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"crypto.d.ts","sourceRoot":"","sources":["src/crypto.ts"],"names":[],"mappings":"AAOA,eAAO,MAAM,MAAM,EAAE,GACqE,CAAC"}
+5
View File
@@ -0,0 +1,5 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.crypto = void 0;
exports.crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
//# sourceMappingURL=crypto.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"crypto.js","sourceRoot":"","sources":["src/crypto.ts"],"names":[],"mappings":";;;AAOa,QAAA,MAAM,GACjB,OAAO,UAAU,KAAK,QAAQ,IAAI,QAAQ,IAAI,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC"}
+2
View File
@@ -0,0 +1,2 @@
export declare const crypto: any;
//# sourceMappingURL=cryptoNode.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"cryptoNode.d.ts","sourceRoot":"","sources":["src/cryptoNode.ts"],"names":[],"mappings":"AASA,eAAO,MAAM,MAAM,EAAE,GAKJ,CAAC"}
+18
View File
@@ -0,0 +1,18 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.crypto = void 0;
/**
* Internal webcrypto alias.
* We prefer WebCrypto aka globalThis.crypto, which exists in node.js 16+.
* Falls back to Node.js built-in crypto for Node.js <=v14.
* See utils.ts for details.
* @module
*/
// @ts-ignore
const nc = require("node:crypto");
exports.crypto = nc && typeof nc === 'object' && 'webcrypto' in nc
? nc.webcrypto
: nc && typeof nc === 'object' && 'randomBytes' in nc
? nc
: undefined;
//# sourceMappingURL=cryptoNode.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"cryptoNode.js","sourceRoot":"","sources":["src/cryptoNode.ts"],"names":[],"mappings":";;;AAAA;;;;;;GAMG;AACH,aAAa;AACb,kCAAkC;AACrB,QAAA,MAAM,GACjB,EAAE,IAAI,OAAO,EAAE,KAAK,QAAQ,IAAI,WAAW,IAAI,EAAE;IAC/C,CAAC,CAAE,EAAE,CAAC,SAAiB;IACvB,CAAC,CAAC,EAAE,IAAI,OAAO,EAAE,KAAK,QAAQ,IAAI,aAAa,IAAI,EAAE;QACnD,CAAC,CAAC,EAAE;QACJ,CAAC,CAAC,SAAS,CAAC"}
+47
View File
@@ -0,0 +1,47 @@
export declare function scrypt(password: string, salt: string): Uint8Array;
export declare function pbkdf2(password: string, salt: string): Uint8Array;
/**
* Derives main seed. Takes a lot of time. Prefer `eskdf` method instead.
*/
export declare function deriveMainSeed(username: string, password: string): Uint8Array;
type AccountID = number | string;
type OptsLength = {
keyLength: number;
};
type OptsMod = {
modulus: bigint;
};
type KeyOpts = undefined | OptsLength | OptsMod;
export interface ESKDF {
/**
* Derives a child key. Child key will not be associated with any
* other child key because of properties of underlying KDF.
*
* @param protocol - 3-15 character protocol name
* @param accountId - numeric identifier of account
* @param options - `keyLength: 64` or `modulus: 41920438n`
* @example deriveChildKey('aes', 0)
*/
deriveChildKey: (protocol: string, accountId: AccountID, options?: KeyOpts) => Uint8Array;
/**
* Deletes the main seed from eskdf instance
*/
expire: () => void;
/**
* Account fingerprint
*/
fingerprint: string;
}
/**
* ESKDF
* @param username - username, email, or identifier, min: 8 characters, should have enough entropy
* @param password - password, min: 8 characters, should have enough entropy
* @example
* const kdf = await eskdf('example-university', 'beginning-new-example');
* const key = kdf.deriveChildKey('aes', 0);
* console.log(kdf.fingerprint);
* kdf.expire();
*/
export declare function eskdf(username: string, password: string): Promise<ESKDF>;
export {};
//# sourceMappingURL=eskdf.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"eskdf.d.ts","sourceRoot":"","sources":["src/eskdf.ts"],"names":[],"mappings":"AAiBA,wBAAgB,MAAM,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,UAAU,CAEjE;AAGD,wBAAgB,MAAM,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,UAAU,CAEjE;AAiBD;;GAEG;AACH,wBAAgB,cAAc,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,UAAU,CAY7E;AAED,KAAK,SAAS,GAAG,MAAM,GAAG,MAAM,CAAC;AAgCjC,KAAK,UAAU,GAAG;IAAE,SAAS,EAAE,MAAM,CAAA;CAAE,CAAC;AACxC,KAAK,OAAO,GAAG;IAAE,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC;AACnC,KAAK,OAAO,GAAG,SAAS,GAAG,UAAU,GAAG,OAAO,CAAC;AAwChD,MAAM,WAAW,KAAK;IACpB;;;;;;;;OAQG;IACH,cAAc,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,SAAS,EAAE,OAAO,CAAC,EAAE,OAAO,KAAK,UAAU,CAAC;IAC1F;;OAEG;IACH,MAAM,EAAE,MAAM,IAAI,CAAC;IACnB;;OAEG;IACH,WAAW,EAAE,MAAM,CAAC;CACrB;AAED;;;;;;;;;GASG;AACH,wBAAsB,KAAK,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,KAAK,CAAC,CAuB9E"}

Some files were not shown because too many files have changed in this diff Show More