From: Chris Duncan Date: Fri, 29 Nov 2024 10:35:49 +0000 (-0800) Subject: We're only going to work in browser environments from here on out, so lose the node... X-Git-Url: https://zoso.dev/?a=commitdiff_plain;h=f0f33cec96465d6f04135e0a35b77187eeffa765;p=libnemo.git We're only going to work in browser environments from here on out, so lose the node crypto implementation. We're also not opening the module up to plugin RNG, so place the relevant code directly in the one place it is used. --- diff --git a/src/lib/workers/nano-nacl.ts b/src/lib/workers/nano-nacl.ts index 296b3ec..4ef0df1 100644 --- a/src/lib/workers/nano-nacl.ts +++ b/src/lib/workers/nano-nacl.ts @@ -34,9 +34,6 @@ async function NanoNaCl (Blake2b: Blake2b) { return r } - // Pluggable, initialized in high-level API below. - var randombytes = function (x, n) { throw new Error('no PRNG') } - var gf0 = gf(), gf1 = gf([1]), D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]), @@ -606,12 +603,21 @@ async function NanoNaCl (Blake2b: Blake2b) { scalarmult(p, q, s) } - function crypto_sign_keypair (pk, sk, seeded?: boolean) { + function crypto_sign_keypair (pk: Uint8Array, sk: Uint8Array, seeded?: boolean) { var d = new Uint8Array(64) var p = [gf(), gf(), gf(), gf()] var i - if (!seeded) randombytes(sk, 32) + if (!seeded) { + var QUOTA = 65536 // https://w3c.github.io/webcrypto/#Crypto-method-getRandomValues + var i, n = 32, v = new Uint8Array(n) + for (i = 0; i < n; i += QUOTA) { + crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA))) + } + for (i = 0; i < n; i++) sk[i] = v[i] + cleanup(v) + } + crypto_hash(d, sk, 32) d[0] &= 248 d[31] &= 127 @@ -856,41 +862,6 @@ async function NanoNaCl (Blake2b: Blake2b) { const seedLength = crypto_sign_SEEDBYTES const signatureLength = crypto_sign_BYTES - const setPRNG = function (fn) { - randombytes = fn - }; - - (function () { - // Initialize PRNG if environment provides CSPRNG. - // If not, methods calling randombytes will throw. - var crypto = self?.crypto ?? null - if (crypto && crypto.getRandomValues) { - // Browsers. - var QUOTA = 65536 - setPRNG(function (x, n) { - var i, v = new Uint8Array(n) - for (i = 0; i < n; i += QUOTA) { - crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA))) - } - for (i = 0; i < n; i++) x[i] = v[i] - cleanup(v) - }) - } else if (typeof require !== 'undefined') { - // Node.js. - try { - crypto = require('node:crypto') - if (crypto && crypto.randomBytes) { - setPRNG(function (x, n) { - var i, v = crypto.randomBytes(n) - for (i = 0; i < n; i++) x[i] = v[i] - cleanup(v) - }) - } - } catch (err) { - throw new Error('failed to load node:crypto') - } - } - })() } export const nacl = {