@amritk/nish-aarch64-linux 0.49.0 → 0.50.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/INSTALL.md +1 -1
  2. package/bin/nish +0 -0
  3. package/docs/AI.md +233 -159
  4. package/package.json +1 -1
  5. package/runtime/gfx/nish-gfx.h +373 -61
  6. package/runtime/nish.d.ts +12 -9
  7. package/std/README.md +8 -5
  8. package/std/base64.ts +74 -1
  9. package/std/bytes.ts +201 -93
  10. package/std/compress/deflate.ts +20 -15
  11. package/std/crypto/base64url.ts +93 -66
  12. package/std/crypto/bcrypt.ts +25 -21
  13. package/std/crypto/hmac.ts +1 -1
  14. package/std/crypto/jwt.ts +32 -19
  15. package/std/crypto/p256.ts +9 -12
  16. package/std/crypto/pki-roots.ts +7 -4
  17. package/std/crypto/pki.ts +43 -55
  18. package/std/crypto/rsa-sign.ts +1632 -0
  19. package/std/crypto/rsa.ts +26 -4
  20. package/std/crypto/sha256.ts +135 -68
  21. package/std/crypto/x25519.ts +12 -11
  22. package/std/crypto/x509.ts +164 -40
  23. package/std/gpu/sys.ts +490 -0
  24. package/std/json-equal.ts +33 -18
  25. package/std/json-format.ts +39 -8
  26. package/std/json-number.ts +15 -3
  27. package/std/json-tokenizer.ts +4 -3
  28. package/std/json-typed.ts +29 -12
  29. package/std/json-value.ts +222 -104
  30. package/std/json.ts +81 -46
  31. package/std/net/dns-config.ts +18 -5
  32. package/std/net/dns-message.ts +60 -27
  33. package/std/net/dns-resolver.ts +35 -16
  34. package/std/net/dns.ts +3 -2
  35. package/std/net/fetch.ts +120 -38
  36. package/std/net/handler.ts +178 -66
  37. package/std/net/hpack.ts +192 -98
  38. package/std/net/http-compress.ts +83 -30
  39. package/std/net/http-fields.ts +327 -31
  40. package/std/net/http-server.ts +317 -20
  41. package/std/net/http1-client-codec.ts +137 -40
  42. package/std/net/http1-codec.ts +391 -202
  43. package/std/net/http1-server.ts +220 -38
  44. package/std/net/http2-cleartext.ts +10 -4
  45. package/std/net/http2-frame.ts +2 -2
  46. package/std/net/http2-tls.ts +3 -3
  47. package/std/net/http2.ts +69 -15
  48. package/std/net/http3-frame.ts +11 -14
  49. package/std/net/http3-server.ts +12 -15
  50. package/std/net/http3.ts +41 -29
  51. package/std/net/multipart.ts +592 -0
  52. package/std/net/outbound.ts +24 -8
  53. package/std/net/postgres-async.ts +92 -54
  54. package/std/net/postgres-carrier.ts +28 -4
  55. package/std/net/postgres.ts +166 -65
  56. package/std/net/prefork.ts +86 -5
  57. package/std/net/protobuf.ts +6 -2
  58. package/std/net/qpack.ts +66 -25
  59. package/std/net/quic-conn-ack.ts +27 -7
  60. package/std/net/quic-conn-cid.ts +13 -7
  61. package/std/net/quic-datagram.ts +6 -5
  62. package/std/net/quic-frame.ts +67 -23
  63. package/std/net/quic-listener.ts +19 -12
  64. package/std/net/quic-recovery.ts +11 -9
  65. package/std/net/quic-stream.ts +7 -5
  66. package/std/net/quic.ts +36 -31
  67. package/std/net/router.ts +136 -24
  68. package/std/net/serve.ts +59 -5
  69. package/std/net/static.ts +81 -33
  70. package/std/net/tls/record.ts +26 -13
  71. package/std/net/tls/ticket.ts +6 -5
  72. package/std/net/tls-tcp.ts +69 -30
  73. package/std/net/tls.ts +152 -38
  74. package/std/net/upstream.ts +65 -19
  75. package/std/net/url.ts +97 -78
  76. package/std/net/websocket.ts +33 -15
  77. package/std/net/webtransport.ts +28 -12
  78. package/std/regex.ts +600 -388
  79. package/std/sqlite.ts +37 -19
  80. package/std/sync/ring.ts +232 -115
  81. package/std/sync/shm.ts +11 -4
  82. package/std/temporal.ts +232 -133
  83. package/std/term-io.ts +12 -6
  84. package/std/term-pixels.ts +158 -22
  85. package/std/term-rate.ts +8 -3
  86. package/std/term.ts +4 -4
  87. package/std/text.ts +33 -11
  88. package/std/threads.ts +52 -8
  89. package/std/yaml-json.ts +238 -106
  90. package/std/yaml-lines.ts +47 -27
  91. package/std/yaml-write.ts +58 -24
  92. package/std/yaml.ts +808 -395
@@ -0,0 +1,1632 @@
1
+ /**
2
+ * `nish/crypto/rsa-sign` — an RSA private key of 2048 to 4096 bits held as a
3
+ * `Secret`, and RSASSA-PSS signing with SHA-256 under it (RFC 8017 §8.1.1,
4
+ * the TLS 1.3 scheme `rsa_pss_rsae_sha256`), in constant-time arithmetic.
5
+ *
6
+ * import { rsaParsePrivateKey, rsaSignPssSha256 } from "nish/crypto/rsa-sign";
7
+ * import { Secret, wipe } from "nish:secret";
8
+ *
9
+ * // der: a PKCS#1 RSAPrivateKey, which the caller wipes
10
+ * const signOnce = (der: u8[], message: u8[]): u8[] | null => {
11
+ * const key: Secret<u8[]> | null = rsaParsePrivateKey(der, 0, toI32(der.length));
12
+ * if (key === null) {
13
+ * return null;
14
+ * }
15
+ * const signature: u8[] | null = rsaSignPssSha256(key, message);
16
+ * wipe(key);
17
+ * return signature;
18
+ * };
19
+ *
20
+ * `nish/crypto/x509` reads PEM keys, PKCS#1 and PKCS#8, through
21
+ * `rsaParsePrivateKey` (`x509ParseRsaPrivateKey`).
22
+ *
23
+ * **The key** is PKCS#1's `RSAPrivateKey` (RFC 8017 §A.1.2), version 0 (two
24
+ * primes), read strictly: definite lengths in their shortest form, every
25
+ * INTEGER positive and minimal, nothing after the last. The modulus is odd and
26
+ * `RSA_SIGN_MIN_BITS` to `RSA_SIGN_MAX_BITS` bits, the public exponent odd, at
27
+ * least 3 and below 2^32, and the private exponent nonzero and below the
28
+ * modulus. The CRT values must hold together (RFC 8017 §3.2): `p` and `q`
29
+ * odd, `dP` below `p`, `dQ` below `q` and `qInv` below `p`, `p q` equal to the
30
+ * modulus and `q qInv` 1 modulo `p`. Then one value is signed twice: 2 by the
31
+ * CRT, opened again under the public exponent, and 2 raised to the private
32
+ * exponent and then to the public one, each of which must give 2 back, so a
33
+ * key whose exponents do not undo each other is refused at load, not at the
34
+ * first handshake. The key's bytes lie in the first 4096 of the array it is read from: the
35
+ * reader bounds absolute indexes, not the key's length, so a key past index
36
+ * 4096 of a larger buffer is refused (a 4096-bit PKCS#1 key is about 2350
37
+ * bytes, and `nish/crypto/x509` hands it the PEM block's own DER, where a
38
+ * PKCS#8 wrapper puts the key a few dozen bytes in). The `Secret` holds the
39
+ * modulus, the private exponent and the public exponent, each as many
40
+ * big-endian bytes as the modulus has (`k`); then `p`, `q`, `dP`, `dQ` and
41
+ * `qInv`, then R^2 and R^3 modulo `p` and modulo `q`, each in `w` bytes, for
42
+ * `w` four times half the modulus's 32-bit limbs, rounded up; then R^2 modulo
43
+ * the modulus in `k` bytes: `4 k + 9 w` bytes, the constants computed once at
44
+ * load. A `Secret` of the first `3 k` bytes alone, `n`, `d` and `e` (RFC 8017
45
+ * §3.2's first form), is a key here too: it signs by `m^d mod n`, the same
46
+ * fixed window over every nibble of `d` and the same check against `e`, about
47
+ * four times the CRT's work, and nothing checks it before its first
48
+ * signature, since no parse made it. Known-answer tests build one directly
49
+ * (`test/spec/rfc8017-rsa-pss-sha256.ts`).
50
+ *
51
+ * **The salt is derived, not drawn.** `rsaSignPssSha256` and
52
+ * `rsaSignPssSha256Into` take as the salt the SHA-256 of a fixed label, the
53
+ * private exponent's `k` bytes and the message's hash:
54
+ * `RSA_PSS_SHA256_SALT_SIZE` bytes that no one without the key can predict,
55
+ * the same for the same message and different for every other, as RFC 6979
56
+ * derives an ECDSA nonce (`nish/crypto/p256` signs that way). PSS's security
57
+ * does not rest on the salt being random (RFC 8017 §8.1, note 4: even an
58
+ * empty salt keeps a reduction), and a verifier cannot tell a derived salt
59
+ * from a drawn one. So nothing here reaches `crypto.getRandomValues` or any
60
+ * other source, and the module compiles for wasm32. `rsaSignPssSha256Salted`
61
+ * signs with a salt the caller gives, for known-answer tests.
62
+ *
63
+ * **Constant time.** Each half exponent is applied in a fixed 4-bit window
64
+ * over every nibble of its limbs, leading zeros included: four Montgomery
65
+ * squarings, a read of the whole 16-entry table that keeps one entry under an
66
+ * `ctEq` mask, and one Montgomery multiplication, for every nibble. The
67
+ * Montgomery multiplication (CIOS, as in `nish/crypto/rsa`) ends in a
68
+ * subtraction whose result is kept or dropped by `ctSelect`, never a branch.
69
+ * Recombining the halves (Garner's `h = (s1 - s2) qInv mod p`, then
70
+ * `s = s2 + q h`) is masked arithmetic of the same fixed shape. So the
71
+ * sequence of operations and the addresses read depend on the modulus's
72
+ * length alone. The modulus, the message and the public exponent are public,
73
+ * and the code that touches only them (the check after signing) may branch on
74
+ * them. The salt's hash reads the private exponent through SHA-256, whose
75
+ * work depends on the length alone.
76
+ *
77
+ * **CRT, checked; no blinding.** Signing works modulo `p` and `q`, about a
78
+ * quarter of the work of one exponentiation by `d` modulo `n`. A fault in one
79
+ * half gives a value right modulo one prime and wrong modulo the other, which
80
+ * factors `n` (Bellcore), so every signature is raised to `e` and compared
81
+ * with the encoded message, and its limbs checked below `n`, before any byte
82
+ * of it is returned; one that does not match answers `null`. The exponents
83
+ * are not blinded; the fixed window is the defence against timing (RSA-S2 in
84
+ * docs/security/crypto-rsa.md).
85
+ *
86
+ * **Wiping.** Every limb array that held a prime, an exponent, a constant
87
+ * made from a prime or a power of the message, the window table and the
88
+ * product among them, is wiped before the exposing function returns, and
89
+ * so is the hasher that derives the salt. The parse builds the `Secret`
90
+ * straight from the DER without a copy that outlives it. The DER itself is
91
+ * the caller's to wipe.
92
+ *
93
+ * Private names carry the `rsaSign` prefix because a `std/` module's private
94
+ * functions share the importing program's flat symbol namespace
95
+ * (`docs/wp26-stdlib.md` §3e).
96
+ */
97
+
98
+ import { Secret, expose, exposeWith, secret, wipe } from "nish:secret"
99
+ import { hmacCopySha256 } from "nish/crypto/hmac"
100
+ import { Sha256 } from "nish/crypto/sha256"
101
+
102
+ /** The fewest modulus bits a signing key may have. */
103
+ export const RSA_SIGN_MIN_BITS: i32 = 2048
104
+
105
+ /** The most modulus bits a signing key may have. */
106
+ export const RSA_SIGN_MAX_BITS: i32 = 4096
107
+
108
+ /** The salt length, in bytes, that `rsa_pss_rsae_sha256` requires: SHA-256's output. */
109
+ export const RSA_PSS_SHA256_SALT_SIZE: i32 = 32
110
+
111
+ /** The bytes of a DER element's contents: `der[start .. end)`. */
112
+ class RsaSignSpan {
113
+ /** The first byte of the contents. */
114
+ start: i32
115
+ /** One past the last byte of the contents. */
116
+ end: i32
117
+
118
+ constructor(start: i32, end: i32) {
119
+ this.start = start
120
+ this.end = end
121
+ }
122
+ }
123
+
124
+ /**
125
+ * The contents of the element at `der[at]`, when it has the identifier `tag`
126
+ * and a definite length in its shortest form that fits before `end`; `null`
127
+ * otherwise. Lengths of more than two octets are refused: a 4096-bit key's
128
+ * DER is under 2.5 kilobytes.
129
+ */
130
+ const rsaSignDer = (der: u8[], at: i32, end: i32, tag: i32): RsaSignSpan | null => {
131
+ const total: i32 = toI32(der.length)
132
+ if (end < 2 || end > total || at < 0 || at > end - 2 || at > total - 2 || toI32(der[at]) !== tag) {
133
+ return null
134
+ }
135
+ const first: i32 = toI32(der[at + 1])
136
+ let start: i32 = at + 2
137
+ let length: i32 = first
138
+ if (first === 0x81) {
139
+ if (at > end - 3 || at > total - 3) {
140
+ return null
141
+ }
142
+ length = toI32(der[at + 2])
143
+ if (length < 0x80) {
144
+ return null
145
+ }
146
+ start = at + 3
147
+ } else if (first === 0x82) {
148
+ if (at > end - 4 || at > total - 4) {
149
+ return null
150
+ }
151
+ length = (toI32(der[at + 2]) << 8) | toI32(der[at + 3])
152
+ if (length < 0x100) {
153
+ return null
154
+ }
155
+ start = at + 4
156
+ } else if (first >= 0x80) {
157
+ return null
158
+ }
159
+ if (length > end - start) {
160
+ return null
161
+ }
162
+ return new RsaSignSpan(start, toI32(toI64(start) + toI64(length)))
163
+ }
164
+
165
+ /**
166
+ * The magnitude of the INTEGER at `der[at]` before `end`, as the span of its
167
+ * bytes with the sign octet dropped; `null` for another tag, an empty,
168
+ * negative or non-minimal INTEGER, and one past `4096`.
169
+ */
170
+ const rsaSignInteger = (der: u8[], at: i32, end: i32): RsaSignSpan | null => {
171
+ const e: RsaSignSpan | null = rsaSignDer(der, at, end, 0x02)
172
+ if (e === null) {
173
+ return null
174
+ }
175
+ const start: i32 = e.start
176
+ const stop: i32 = e.end
177
+ if (start < 0 || start >= stop || stop > 4096 || start >= toI32(der.length) || toI32(der[start]) >= 0x80) {
178
+ return null
179
+ }
180
+ if (toI32(der[start]) !== 0) {
181
+ return e
182
+ }
183
+ const from: i32 = start + 1
184
+ if (from >= stop || from >= toI32(der.length) || toI32(der[from]) < 0x80) {
185
+ return null
186
+ }
187
+ return new RsaSignSpan(from, stop)
188
+ }
189
+
190
+ /**
191
+ * The significant bits of the big-endian magnitude `der[start .. end)`, whose
192
+ * first byte is nonzero; 0 for an empty span or one past `4096`.
193
+ */
194
+ const rsaSignBits = (der: u8[], start: i32, end: i32): i32 => {
195
+ if (start < 0 || start >= end || end > 4096 || start >= toI32(der.length)) {
196
+ return 0
197
+ }
198
+ const top: i32 = toI32(der[start])
199
+ let topBits: i32 = 0
200
+ for (let b: i32 = 0; b < 8; b++) {
201
+ if (top >> b !== 0) {
202
+ topBits = b + 1
203
+ }
204
+ }
205
+ const bytes: i32 = end - start
206
+ if (topBits < 1 || topBits > 8 || bytes < 1 || bytes > 4096) {
207
+ return 0
208
+ }
209
+ return (bytes - 1) * 8 + topBits
210
+ }
211
+
212
+ /** Whether the byte before `der[end]` is odd: the last byte of a magnitude ending there. */
213
+ const rsaSignOdd = (der: u8[], end: i32): boolean => {
214
+ if (end < 1 || end > 4096) {
215
+ return false
216
+ }
217
+ const last: i32 = end - 1
218
+ return last < toI32(der.length) && (toI32(der[last]) & 1) === 1
219
+ }
220
+
221
+ /**
222
+ * The bytes each CRT value of a key with a `k`-byte modulus takes: `4 c`, for
223
+ * the `c = ⌈⌈k / 4⌉ / 2⌉` limbs of half the modulus; 0 for a `k` out of range.
224
+ */
225
+ const rsaSignHalfWidth = (k: i32): i32 => {
226
+ if (k < 256 || k > 512) {
227
+ return 0
228
+ }
229
+ const count: i32 = toI32((k + 3) / 4)
230
+ return toI32((count + 1) / 2) * 4
231
+ }
232
+
233
+ /**
234
+ * The key bytes for a `k`-byte modulus, `4 k + 9 w` of them with `w` from
235
+ * `rsaSignHalfWidth`: `n`, `d` and `e` in `k` bytes each, then `p`, `q`,
236
+ * `dP`, `dQ` and `qInv` in `w` bytes each, each right-aligned, out of the spans
237
+ * the parse found, which fit; the four Montgomery constants after them and
238
+ * R^2 mod n in the last `k` bytes stay zero for `rsaSignPrecompute`. Empty for
239
+ * a `k` out of range.
240
+ */
241
+ const rsaSignKeyBytes = (der: u8[], k: i32, spans: RsaSignSpan[]): u8[] => {
242
+ const w: i32 = rsaSignHalfWidth(k)
243
+ // The bounds restate rsaSignHalfWidth's, so the prover sees the sizes fit.
244
+ if (k < 256 || k > 512 || w < 1 || w > 256 || toI32(spans.length) !== 8) {
245
+ return []
246
+ }
247
+ const size: i32 = 4 * k + 9 * w
248
+ const out: u8[] = new Array<u8>(size)
249
+ for (let i: i32 = 0; i < 8; i++) {
250
+ const at: i32 = i < 3 ? i * k : 3 * k + (i - 3) * w
251
+ rsaSignPlace(out, at, i < 3 ? k : w, der, spans[i])
252
+ }
253
+ return out
254
+ }
255
+
256
+ /**
257
+ * Copies the bytes of `span` into the last of the `width` bytes of `out` at
258
+ * `at`; a span wider than `width` copies nothing.
259
+ */
260
+ const rsaSignPlace = (out: u8[], at: i32, width: i32, der: u8[], span: RsaSignSpan): void => {
261
+ const start: i32 = span.start
262
+ const stop: i32 = span.end
263
+ if (
264
+ start < 0 ||
265
+ start > 4096 ||
266
+ stop < 0 ||
267
+ stop < start ||
268
+ stop > 4096 ||
269
+ at < 0 ||
270
+ at > 4096 ||
271
+ width < 0 ||
272
+ width > 512
273
+ ) {
274
+ return
275
+ }
276
+ const length: i32 = stop - start
277
+ if (length < 0 || length > width) {
278
+ return
279
+ }
280
+ const pad: i32 = width - length
281
+ const to: i32 = at + pad
282
+ for (let i: i32 = 0; i < length; i++) {
283
+ const o: i32 = to + i
284
+ const s: i32 = start + i
285
+ if (o >= 0 && o < toI32(out.length) && s >= 0 && s < toI32(der.length)) {
286
+ out[o] = der[s]
287
+ }
288
+ }
289
+ }
290
+
291
+ /**
292
+ * Reads the DER of a PKCS#1 `RSAPrivateKey` (RFC 8017 §A.1.2) filling
293
+ * `der[start .. end)`, and tries it once. Answers `null` for anything but
294
+ * version 0 and its nine positive, minimal INTEGERs with definite, minimal
295
+ * lengths and nothing after them; for a modulus that is even or outside
296
+ * `RSA_SIGN_MIN_BITS` to `RSA_SIGN_MAX_BITS` bits; for a public exponent that is
297
+ * even, below 3 or not below 2^32; for a private exponent of zero or not below
298
+ * the modulus; for CRT values that do not hold together (`p` or `q` even,
299
+ * `dP`, `dQ` or `qInv` out of range, `p q` not the modulus, `q qInv` not 1
300
+ * modulo `p`); and for exponents that do not undo each other (2 signed by the
301
+ * CRT, or raised to the private exponent, and opened again is not 2). `der`
302
+ * is not changed and not kept: the
303
+ * caller wipes it. A key whose `end` is past 4096 is refused, whatever its
304
+ * length: the limit is on the index, not on `end - start`.
305
+ *
306
+ * @param der The array holding the key's DER.
307
+ * @param start The index of the key's SEQUENCE tag.
308
+ * @param end One past the key's last byte.
309
+ * @returns The key as a fresh `Secret` the caller wipes, or `null`.
310
+ */
311
+ export const rsaParsePrivateKey = (der: u8[], start: i32, end: i32): Secret<u8[]> | null => {
312
+ const seq: RsaSignSpan | null = rsaSignDer(der, start, end, 0x30)
313
+ if (seq === null || seq.end !== end || end > 4096) {
314
+ return null
315
+ }
316
+ const version: RsaSignSpan | null = rsaSignDer(der, seq.start, seq.end, 0x02)
317
+ if (version === null) {
318
+ return null
319
+ }
320
+ const vs: i32 = version.start
321
+ if (vs < 0 || vs >= toI32(der.length) || version.end !== vs + 1 || toI32(der[vs]) !== 0) {
322
+ return null
323
+ }
324
+ const n: RsaSignSpan | null = rsaSignInteger(der, version.end, seq.end)
325
+ if (n === null) {
326
+ return null
327
+ }
328
+ const e: RsaSignSpan | null = rsaSignInteger(der, n.end, seq.end)
329
+ if (e === null) {
330
+ return null
331
+ }
332
+ const d: RsaSignSpan | null = rsaSignInteger(der, e.end, seq.end)
333
+ if (d === null) {
334
+ return null
335
+ }
336
+ // p, q, dP, dQ and qInv, each no wider than half the modulus's limbs.
337
+ const spans: RsaSignSpan[] = [n, d, e]
338
+ let at: i32 = d.end
339
+ for (let i: i32 = 0; i < 5; i++) {
340
+ const v: RsaSignSpan | null = rsaSignInteger(der, at, seq.end)
341
+ if (v === null) {
342
+ return null
343
+ }
344
+ spans.push(v)
345
+ at = v.end
346
+ }
347
+ if (at !== seq.end) {
348
+ return null
349
+ }
350
+ const total: i32 = toI32(der.length)
351
+ const ns: i32 = n.start
352
+ const ne: i32 = n.end
353
+ const es: i32 = e.start
354
+ const ee: i32 = e.end
355
+ const ds: i32 = d.start
356
+ const de: i32 = d.end
357
+ if (
358
+ ns < 0 ||
359
+ ne <= ns ||
360
+ ne > total ||
361
+ es < 0 ||
362
+ ee <= es ||
363
+ ee > total ||
364
+ ds < 0 ||
365
+ de < ds ||
366
+ de > total
367
+ ) {
368
+ return null
369
+ }
370
+ const bits: i32 = rsaSignBits(der, ns, ne)
371
+ const eBits: i32 = rsaSignBits(der, es, ee)
372
+ if (
373
+ bits < 2048 ||
374
+ bits > 4096 ||
375
+ !rsaSignOdd(der, ne) ||
376
+ eBits < 2 ||
377
+ eBits > 32 ||
378
+ !rsaSignOdd(der, ee) ||
379
+ de - ds > ne - ns
380
+ ) {
381
+ return null
382
+ }
383
+ const w: i32 = rsaSignHalfWidth(ne - ns)
384
+ for (let i: i32 = 3; i < toI32(spans.length); i++) {
385
+ const from: i32 = spans[i].start
386
+ const to: i32 = spans[i].end
387
+ if (from < 0 || to < 0 || to - from > w) {
388
+ return null
389
+ }
390
+ }
391
+ const bytes: u8[] = rsaSignKeyBytes(der, ne - ns, spans)
392
+ rsaSignPrecompute(bytes)
393
+ const key: Secret<u8[]> = secret(bytes)
394
+ if (!expose(key, rsaSignKeySound)) {
395
+ wipe(key)
396
+ return null
397
+ }
398
+ return key
399
+ }
400
+
401
+ /**
402
+ * The modulus bits of a key from `rsaParsePrivateKey`, or 0 for a `Secret`
403
+ * that is not one (its length is not `4 k + 9 w` for a `k` of 256 to 512).
404
+ *
405
+ * @param priv The key.
406
+ * @returns The modulus's bit length, which is public.
407
+ */
408
+ export const rsaPrivateKeyBits = (priv: Secret<u8[]>): i32 => expose(priv, rsaSignKeyBits)
409
+
410
+ /**
411
+ * The modulus of a key from `rsaParsePrivateKey`, as `k` big-endian bytes, to
412
+ * hold against a certificate's public key; empty for a `Secret` that is not
413
+ * one.
414
+ *
415
+ * @param priv The key.
416
+ * @returns A fresh copy of the modulus, which is public.
417
+ */
418
+ export const rsaPrivateKeyModulus = (priv: Secret<u8[]>): u8[] => expose(priv, rsaSignKeyModulus)
419
+
420
+ /**
421
+ * The public exponent of a key from `rsaParsePrivateKey`, as `k` big-endian
422
+ * bytes with leading zeros; empty for a `Secret` that is not one.
423
+ *
424
+ * @param priv The key.
425
+ * @returns A fresh copy of the public exponent.
426
+ */
427
+ export const rsaPrivateKeyExponent = (priv: Secret<u8[]>): u8[] => expose(priv, rsaSignKeyExponent)
428
+
429
+ /**
430
+ * RSASP1 (RFC 8017 §5.2.1) alone: `m^d mod n` for the `k`-byte big-endian
431
+ * `m`, as `k` bytes, with no padding scheme around it. It is a primitive for
432
+ * known-answer tests and for a caller that encodes its own message; signing a
433
+ * value an attacker chose with it is a decryption oracle. `null` for an `m`
434
+ * that is not exactly `k` bytes or not below `n`, a `Secret` that is neither a
435
+ * key from `rsaParsePrivateKey` nor the first form `n`, `d` and `e` (the
436
+ * module's comment), and a result that fails the check against `e`.
437
+ *
438
+ * @param priv The key, borrowed.
439
+ * @param m The message representative, `k` bytes.
440
+ * @returns The signature representative, `k` bytes, or `null`.
441
+ */
442
+ export const rsaSignRaw = (priv: Secret<u8[]>, m: u8[]): u8[] | null => exposeWith(priv, m, rsaSignPrivateOp)
443
+
444
+ /**
445
+ * The hashers `rsaSignPssSha256SaltedInto` hashes with, made once and reused, so a
446
+ * signature allocates nothing that outlives it: a `Sha256` keeps arrays in its
447
+ * fields, and one made per hash inside the signer's arena would be stored
448
+ * there. A carrier keeps one scratch, not one per connection: signing is
449
+ * synchronous.
450
+ */
451
+ export class RsaSignScratch {
452
+ /** A hasher nothing is fed, which `work` is reset from. */
453
+ private fresh: Sha256
454
+ /** The hasher every digest is computed in. */
455
+ private work: Sha256
456
+
457
+ /** Makes the two hashers. */
458
+ constructor() {
459
+ this.fresh = new Sha256()
460
+ this.work = new Sha256()
461
+ }
462
+
463
+ /**
464
+ * The SHA-256 digest of `data[off .. off + len)`, then of the four bytes of
465
+ * `counter` when `counter` is not negative (MGF1's `C`), written at
466
+ * `out[at]`.
467
+ *
468
+ * @param data The array holding the input.
469
+ * @param off The input's first index.
470
+ * @param len The input's length.
471
+ * @param counter MGF1's block counter, or -1 for none.
472
+ * @param out The array the digest is written into.
473
+ * @param at The index of the digest's first byte.
474
+ * @returns Whether `out` had room for the digest.
475
+ */
476
+ hashInto(data: u8[], off: i32, len: i32, counter: i32, out: u8[], at: i32): boolean {
477
+ hmacCopySha256(this.fresh, this.work)
478
+ this.work.update(data, off, len)
479
+ if (counter >= 0) {
480
+ const c: u8[] = [toU8(counter >> 24), toU8(counter >> 16), toU8(counter >> 8), toU8(counter)]
481
+ this.work.update(c, toI32(0), toI32(4))
482
+ }
483
+ return this.work.digestInto(out, at)
484
+ }
485
+
486
+ /**
487
+ * The derived salt for the message hash `mHash` (32 bytes), written into
488
+ * `salt` (32 bytes): the SHA-256 of "nish rsa-pss-sha256 salt", the private
489
+ * exponent `d` and `mHash`. The hasher's state, block and schedule, which
490
+ * held `d`'s blocks, are wiped before it returns.
491
+ *
492
+ * @param d A copy of the private exponent, which the caller wipes.
493
+ * @param mHash The message's SHA-256.
494
+ * @param salt The array the salt is written into.
495
+ * @returns Whether the salt was written.
496
+ */
497
+ saltInto(d: u8[], mHash: u8[], salt: u8[]): boolean {
498
+ if (toI32(mHash.length) !== 32 || toI32(salt.length) !== 32) {
499
+ return false
500
+ }
501
+ const label: u8[] = [
502
+ 110, 105, 115, 104, 32, 114, 115, 97, 45, 112, 115, 115, 45, 115, 104, 97, 50, 53, 54, 32, 115, 97, 108,
503
+ 116,
504
+ ]
505
+ hmacCopySha256(this.fresh, this.work)
506
+ this.work.update(label, toI32(0), toI32(24))
507
+ this.work.update(d, toI32(0), toI32(d.length))
508
+ this.work.update(mHash, toI32(0), toI32(32))
509
+ const ok: boolean = this.work.digestInto(salt, toI32(0))
510
+ wipe(this.work.state)
511
+ wipe(this.work.block)
512
+ wipe(this.work.schedule)
513
+ this.work.fill = 0
514
+ this.work.total = 0
515
+ return ok
516
+ }
517
+ }
518
+
519
+ /**
520
+ * RSASSA-PSS-SIGN (RFC 8017 §8.1.1) with SHA-256, MGF1-SHA-256 and the salt
521
+ * given: for known-answer tests. A salt of any length up to `emLen - 34`
522
+ * bytes is taken; TLS's `rsa_pss_rsae_sha256` wants
523
+ * `RSA_PSS_SHA256_SALT_SIZE` bytes, which `rsaSignPssSha256` derives. `null`
524
+ * for a salt too long for the key, a
525
+ * `Secret` that is not a key (the module's comment), and a signature that
526
+ * fails the check against `e`.
527
+ *
528
+ * @param priv The key, borrowed.
529
+ * @param msg The message, hashed here.
530
+ * @param salt The salt.
531
+ * @returns The `k`-byte signature, or `null`.
532
+ */
533
+ export const rsaSignPssSha256Salted = (priv: Secret<u8[]>, msg: u8[], salt: u8[]): u8[] | null => {
534
+ const em: u8[] | null = rsaSignPssEncode(
535
+ new RsaSignScratch(),
536
+ msg,
537
+ 0,
538
+ toI32(msg.length),
539
+ salt,
540
+ rsaPrivateKeyBits(priv)
541
+ )
542
+ if (em === null) {
543
+ return null
544
+ }
545
+ return exposeWith(priv, em, rsaSignPrivateOp)
546
+ }
547
+
548
+ /**
549
+ * `rsaSignPssSha256Salted` over `msg[off .. off + len)`, writing the `k`-byte
550
+ * signature at `out[at]` and hashing in `sc`, for a server whose memory may not
551
+ * grow per handshake; `rsaSignPssSha256Into` derives the salt. Its arena scope
552
+ * frees what it allocates. Answers `false`, leaving `out` as it was, when either
553
+ * window is outside its array (`k` is `rsaPrivateKeyBits(priv)` rounded up to
554
+ * bytes), for a salt too long for the key, a `Secret` that is not a key and a
555
+ * signature that fails the check against `e`.
556
+ *
557
+ * @param sc The hashers, made once by the caller.
558
+ * @param priv The key, borrowed.
559
+ * @param msg The array holding the message.
560
+ * @param off The message's first index.
561
+ * @param len The message's length.
562
+ * @param salt The salt.
563
+ * @param out The array the signature is written into.
564
+ * @param at The index of the signature's first byte.
565
+ * @returns Whether a signature was written.
566
+ */
567
+ export const rsaSignPssSha256SaltedInto = (
568
+ sc: RsaSignScratch,
569
+ priv: Secret<u8[]>,
570
+ msg: u8[],
571
+ off: i32,
572
+ len: i32,
573
+ salt: u8[],
574
+ out: u8[],
575
+ at: i32
576
+ ): boolean => {
577
+ const bits: i32 = rsaPrivateKeyBits(priv)
578
+ if (bits < 2048 || bits > 4096) {
579
+ return false
580
+ }
581
+ const k: i32 = toI32((bits + 7) / 8)
582
+ if (off < 0 || len < 0 || off > toI32(msg.length) - len || at < 0 || at > toI32(out.length) - k) {
583
+ return false
584
+ }
585
+ using _scope = arena()
586
+ const em: u8[] | null = rsaSignPssEncode(sc, msg, off, len, salt, bits)
587
+ if (em === null) {
588
+ return false
589
+ }
590
+ const signature: u8[] | null = exposeWith(priv, em, rsaSignPrivateOp)
591
+ if (signature === null || toI32(signature.length) !== k) {
592
+ return false
593
+ }
594
+ const sig: u8[] = signature
595
+ for (let i: i32 = 0; i < toI32(sig.length); i++) {
596
+ const o: i32 = toI32(toI64(at) + toI64(i))
597
+ if (o >= 0 && o < toI32(out.length)) {
598
+ out[o] = sig[i]
599
+ }
600
+ }
601
+ return true
602
+ }
603
+
604
+ /**
605
+ * RSASSA-PSS-SIGN (RFC 8017 §8.1.1) with SHA-256, MGF1-SHA-256 and the
606
+ * `RSA_PSS_SHA256_SALT_SIZE`-byte salt derived from the key and the message
607
+ * (see the module's comment): TLS 1.3's `rsa_pss_rsae_sha256`. `null` for a
608
+ * `Secret` that is not a key (the module's comment) and a signature that
609
+ * fails the check against `e`.
610
+ *
611
+ * @param priv The key, borrowed.
612
+ * @param msg The message, hashed here.
613
+ * @returns The `k`-byte signature, or `null`.
614
+ */
615
+ export const rsaSignPssSha256 = (priv: Secret<u8[]>, msg: u8[]): u8[] | null => {
616
+ const sc: RsaSignScratch = new RsaSignScratch()
617
+ const mHash: u8[] = new Array<u8>(32)
618
+ if (!sc.hashInto(msg, toI32(0), toI32(msg.length), toI32(-1), mHash, toI32(0))) {
619
+ return null
620
+ }
621
+ const salt: u8[] = new Array<u8>(32)
622
+ if (!rsaSignSaltInto(sc, priv, mHash, salt)) {
623
+ return null
624
+ }
625
+ return rsaSignPssSha256Salted(priv, msg, salt)
626
+ }
627
+
628
+ /**
629
+ * `rsaSignPssSha256` over `msg[off .. off + len)`, writing the `k`-byte
630
+ * signature at `out[at]` and hashing in `sc`: `rsaSignPssSha256SaltedInto`
631
+ * with the derived salt. The hash and the salt it allocates are released when
632
+ * its `arena()` scope closes on return; that release covers only what is
633
+ * allocated inside the scope, so it holds while no caller keeps a reference
634
+ * to them, and `sc` and `out` are the caller's. Answers `false`, leaving `out`
635
+ * as it was, when either window is outside its array, for a `Secret` that is
636
+ * not a key, and for a signature that fails the check against `e`.
637
+ *
638
+ * @param sc The hashers, made once by the caller.
639
+ * @param priv The key, borrowed.
640
+ * @param msg The array holding the message.
641
+ * @param off The message's first index.
642
+ * @param len The message's length.
643
+ * @param out The array the signature is written into.
644
+ * @param at The index of the signature's first byte.
645
+ * @returns Whether a signature was written.
646
+ */
647
+ export const rsaSignPssSha256Into = (
648
+ sc: RsaSignScratch,
649
+ priv: Secret<u8[]>,
650
+ msg: u8[],
651
+ off: i32,
652
+ len: i32,
653
+ out: u8[],
654
+ at: i32
655
+ ): boolean => {
656
+ if (off < 0 || len < 0 || off > toI32(msg.length) - len) {
657
+ return false
658
+ }
659
+ using _scope = arena()
660
+ const mHash: u8[] = new Array<u8>(32)
661
+ if (!sc.hashInto(msg, off, len, toI32(-1), mHash, toI32(0))) {
662
+ return false
663
+ }
664
+ const salt: u8[] = new Array<u8>(32)
665
+ if (!rsaSignSaltInto(sc, priv, mHash, salt)) {
666
+ return false
667
+ }
668
+ return rsaSignPssSha256SaltedInto(sc, priv, msg, off, len, salt, out, at)
669
+ }
670
+
671
+ /**
672
+ * The derived salt for `mHash`, hashed in `sc`, written into `salt`: a copy
673
+ * of the private exponent is taken with `expose`, hashed and wiped, the shape
674
+ * `p256SignSha256Into` has, since a function `exposeWith` runs may not write
675
+ * through its argument and a hasher made inside it would store arrays no
676
+ * arena block may release around. Whether it was written; `false` for a key
677
+ * value of the wrong shape.
678
+ */
679
+ const rsaSignSaltInto = (sc: RsaSignScratch, priv: Secret<u8[]>, mHash: u8[], salt: u8[]): boolean => {
680
+ const d: u8[] = expose(priv, rsaSignExponentCopy)
681
+ if (toI32(d.length) === 0) {
682
+ return false
683
+ }
684
+ const ok: boolean = sc.saltInto(d, mHash, salt)
685
+ wipe(d)
686
+ return ok
687
+ }
688
+
689
+ /** A copy of the private exponent's `k` bytes, for `rsaSignSaltInto`; empty for a key value of the wrong shape. */
690
+ const rsaSignExponentCopy = (key: u8[]): u8[] => {
691
+ const k: i32 = rsaSignKeySize(key)
692
+ if (k < 256 || k > 512) {
693
+ return []
694
+ }
695
+ const d: u8[] = new Array<u8>(k)
696
+ for (let i: i32 = 0; i < toI32(d.length) && i < 512; i++) {
697
+ const j: i32 = k + i
698
+ if (j < toI32(key.length)) {
699
+ d[i] = key[j]
700
+ }
701
+ }
702
+ return d
703
+ }
704
+
705
+ // ---------------------------------------------------------------------------
706
+ // EMSA-PSS (RFC 8017 §9.1.1) and MGF1 (§B.2.1)
707
+ // ---------------------------------------------------------------------------
708
+
709
+ /**
710
+ * EMSA-PSS-ENCODE of `msg[off .. off + len)` with `salt`, for a modulus of
711
+ * `bits` bits (emBits = bits - 1), hashing in `sc`, returned as `k` bytes:
712
+ * the `emLen`-byte EM, behind a zero byte when `emLen` is `k - 1`. `null`
713
+ * for `bits` out of range, a salt that does not fit (emLen < 32 + sLen + 2)
714
+ * and a message window outside `msg`.
715
+ */
716
+ const rsaSignPssEncode = (
717
+ sc: RsaSignScratch,
718
+ msg: u8[],
719
+ off: i32,
720
+ len: i32,
721
+ salt: u8[],
722
+ bits: i32
723
+ ): u8[] | null => {
724
+ if (bits < 2048 || bits > 4096) {
725
+ return null
726
+ }
727
+ const k: i32 = toI32((bits + 7) / 8)
728
+ const emBits: i32 = bits - 1
729
+ const emLen: i32 = toI32((emBits + 7) / 8)
730
+ const sLen: i32 = toI32(salt.length)
731
+ if (sLen < 0 || sLen > 478 || sLen > emLen - 34) {
732
+ return null
733
+ }
734
+ // M' = 00 x 8 || mHash || salt, and H = Hash(M').
735
+ const prime: u8[] = new Array<u8>(40 + sLen)
736
+ if (!sc.hashInto(msg, off, len, toI32(-1), prime, toI32(8))) {
737
+ return null
738
+ }
739
+ for (let i: i32 = 0; i < sLen; i++) {
740
+ const p: i32 = 40 + i
741
+ if (p < toI32(prime.length)) {
742
+ prime[p] = salt[i]
743
+ }
744
+ }
745
+ const out: u8[] = new Array<u8>(k)
746
+ const from: i32 = k - emLen
747
+ const dbLen: i32 = emLen - 33
748
+ const hAt: i32 = from + dbLen
749
+ if (from < 0 || from > 1 || !sc.hashInto(prime, toI32(0), toI32(prime.length), toI32(-1), out, hAt)) {
750
+ return null
751
+ }
752
+ // DB = PS || 01 || salt, masked by MGF1(H): the mask is written into `out`
753
+ // first, a block at a time, and DB XORed in after it.
754
+ const block: u8[] = new Array<u8>(32)
755
+ for (let done: i32 = 0; done < dbLen; done = done + 32) {
756
+ if (!sc.hashInto(out, hAt, toI32(32), toI32(done / 32), block, toI32(0))) {
757
+ return null
758
+ }
759
+ for (let i: i32 = 0; i < 32; i++) {
760
+ const o: i32 = from + done + i
761
+ if (done + i < dbLen && o < toI32(out.length) && i < toI32(block.length)) {
762
+ out[o] = block[i]
763
+ }
764
+ }
765
+ }
766
+ const one: i32 = toI32(toI64(hAt) - toI64(sLen) - 1)
767
+ if (one >= 0 && one < toI32(out.length)) {
768
+ out[one] = out[one] ^ 1
769
+ }
770
+ for (let i: i32 = 0; i < sLen; i++) {
771
+ const o: i32 = toI32(toI64(one) + 1 + toI64(i))
772
+ if (o >= 0 && o < toI32(out.length)) {
773
+ out[o] = out[o] ^ salt[i]
774
+ }
775
+ }
776
+ // Clear the leftmost 8 emLen - emBits bits.
777
+ if (from < toI32(out.length) && k >= 1 && k <= toI32(out.length)) {
778
+ out[from] = toU8(toI32(out[from]) & (toI32(0xff) >> (8 * emLen - emBits)))
779
+ out[k - 1] = 0xbc
780
+ }
781
+ return out
782
+ }
783
+
784
+ // ---------------------------------------------------------------------------
785
+ // The key's shape
786
+ // ---------------------------------------------------------------------------
787
+
788
+ /**
789
+ * `k` for a key value of `4 k + 9 w` bytes (`rsaSignKeyBytes`), or of the
790
+ * first form's `3 k` (`n`, `d` and `e`, RFC 8017 §3.2), with `k` 256 to 512,
791
+ * else 0. Each length grows with `k`, and every `3 k` is below every
792
+ * `4 k + 9 w`, so one `k` at most has it.
793
+ */
794
+ const rsaSignKeySize = (key: u8[]): i32 => {
795
+ const total: i32 = toI32(key.length)
796
+ for (let k: i32 = 256; k <= 512; k++) {
797
+ if (3 * k === total || 4 * k + 9 * rsaSignHalfWidth(k) === total) {
798
+ return k
799
+ }
800
+ }
801
+ return 0
802
+ }
803
+
804
+ /** The modulus bits of the key value, or 0 for one of the wrong shape or a leading zero byte. */
805
+ const rsaSignKeyBits = (key: u8[]): i32 => {
806
+ const k: i32 = rsaSignKeySize(key)
807
+ // biome-ignore lint/style/useExplicitLengthCheck: the panic prover reads `length < 1` as a bound for the key[0] after it and does not read `=== 0`
808
+ if (k === 0 || key.length < 1) {
809
+ return 0
810
+ }
811
+ if (key[0] === 0) {
812
+ return 0
813
+ }
814
+ const bits: i32 = rsaSignBits(key, 0, k)
815
+ if (bits < 2048 || bits > 4096) {
816
+ return 0
817
+ }
818
+ return bits
819
+ }
820
+
821
+ /** A copy of the `k` bytes of the key value from `from`; empty for one of the wrong shape. */
822
+ const rsaSignKeyPart = (key: u8[], part: i32): u8[] => {
823
+ const k: i32 = rsaSignKeySize(key)
824
+ if (k < 256 || k > 512 || part < 0 || part > 2) {
825
+ return []
826
+ }
827
+ const out: u8[] = new Array<u8>(k)
828
+ for (let i: i32 = 0; i < k; i++) {
829
+ const s: i32 = part * k + i
830
+ if (s >= 0 && s < toI32(key.length) && i < toI32(out.length)) {
831
+ out[i] = key[s]
832
+ }
833
+ }
834
+ return out
835
+ }
836
+
837
+ /** A copy of the key's first `k` bytes, `n`. */
838
+ const rsaSignKeyModulus = (key: u8[]): u8[] => rsaSignKeyPart(key, 0)
839
+
840
+ /** A copy of the key's last `k` bytes, `e`. */
841
+ const rsaSignKeyExponent = (key: u8[]): u8[] => rsaSignKeyPart(key, 2)
842
+
843
+ /**
844
+ * Whether the parsed key value holds together, without a branch on a secret
845
+ * until the answer: `d` below `n`; `p` and `q` odd; `dP` below `p`, `dQ` below
846
+ * `q` and `qInv` below `p` (RFC 8017 §3.2); `p q = n`; `q qInv = 1 mod p`,
847
+ * which also refuses `p = q`; then RSASP1 of 2 by the CRT, opened again under
848
+ * `e` by `rsaSignPrivateOp`'s own check, and 2 raised to `d` and then to `e`
849
+ * giving 2, since `d` itself still derives the salt.
850
+ */
851
+ const rsaSignKeySound = (key: u8[]): boolean => {
852
+ const k: i32 = rsaSignKeySize(key)
853
+ if (k < 256 || k > 512 || rsaSignKeyBits(key) === 0) {
854
+ return false
855
+ }
856
+ // d - n, borrow out of the top: set when d < n.
857
+ let borrow: i32 = 0
858
+ for (let i: i32 = k - 1; i >= 0; i--) {
859
+ const di: i32 = k + i
860
+ if (di < toI32(key.length) && i < toI32(key.length)) {
861
+ const diff: i32 = toI32(key[di]) - toI32(key[i]) - borrow
862
+ borrow = (diff >> 8) & 1
863
+ }
864
+ }
865
+ const crt: u32 = rsaSignCrtSound(key, k)
866
+ const two: u8[] = new Array<u8>(k)
867
+ const last: i32 = k - 1
868
+ if (last >= 0 && last < toI32(two.length)) {
869
+ two[last] = 2
870
+ }
871
+ const s: u8[] | null = rsaSignPrivateOp(key, two)
872
+ const full: boolean = rsaSignFullOpens(key, two)
873
+ return borrow === 1 && crt === 0 && s !== null && full
874
+ }
875
+
876
+ // ---------------------------------------------------------------------------
877
+ // Constant-time Montgomery arithmetic
878
+ // ---------------------------------------------------------------------------
879
+ //
880
+ // Every limb array is `128` long and `t` two more, the most a
881
+ // 4096-bit modulus takes; `count`, the modulus's own limbs, is 64 to 128, and
882
+ // the limbs past it stay zero. Each helper checks those lengths on entry and
883
+ // does nothing when they do not hold, which no caller here lets happen.
884
+
885
+ /**
886
+ * The `len` big-endian bytes of `src` at `off` as `count` little-endian `u32`
887
+ * limbs in `out`.
888
+ */
889
+ const rsaSignLimbs = (out: u32[], src: u8[], off: i32, len: i32, count: i32): void => {
890
+ if (count < 0 || count > 128 || off < 0 || off > 4096 || len < 0 || len > 512) {
891
+ return
892
+ }
893
+ for (let limb: i32 = 0; limb < count; limb++) {
894
+ let v: u32 = 0
895
+ for (let b: i32 = 0; b < 4; b++) {
896
+ const j: i32 = len - 1 - (limb * 4 + b)
897
+ const s: i32 = off + j
898
+ if (j >= 0 && s >= 0 && s < toI32(src.length)) {
899
+ v = v | (toU32(src[s]) << toU32(b * 8))
900
+ }
901
+ }
902
+ if (limb < toI32(out.length)) {
903
+ out[limb] = v
904
+ }
905
+ }
906
+ }
907
+
908
+ /** The low `k` bytes of the limbs `a`, big-endian; empty for a `k` out of range. */
909
+ const rsaSignBytes = (a: u32[], k: i32): u8[] => {
910
+ if (k < 0 || k > 512 || toI32(a.length) < 128) {
911
+ return []
912
+ }
913
+ const out: u8[] = new Array<u8>(k)
914
+ for (let j: i32 = 0; j < k; j++) {
915
+ const o: i32 = k - 1 - j
916
+ if (o >= 0 && o < toI32(out.length)) {
917
+ out[o] = toU8(a[toI32(j / 4)] >> toU32((j & 3) << 3))
918
+ }
919
+ }
920
+ return out
921
+ }
922
+
923
+ /** -n^-1 mod 2^32 for the odd limb `n0`, by Newton's iteration (as in `nish/crypto/rsa`). */
924
+ const rsaSignMontInverse = (n0: u32): u32 => {
925
+ let x: u32 = n0
926
+ for (let i: i32 = 0; i < 4; i++) {
927
+ const nx: u32 = toU32(toU64(n0) * toU64(x))
928
+ x = toU32(toU64(x) * toU64(toU32(2 - toU64(nx))))
929
+ }
930
+ return toU32(0 - toU64(x))
931
+ }
932
+
933
+ /**
934
+ * `out = t - n` when the `count + 1`-limb value `t` (its top limb `top`, 0 or
935
+ * 1) is at least `n`, else `out = t`, for `t` below 2n: the subtraction is
936
+ * always done and the answer chosen by mask. `out` is not `t`.
937
+ */
938
+ const rsaSignReduce = (out: u32[], t: u32[], top: u32, n: u32[], count: i32): void => {
939
+ if (count < 1 || count > 128 || toI32(out.length) < 128 || toI32(t.length) < 128 || toI32(n.length) < 128) {
940
+ return
941
+ }
942
+ let borrow: u64 = 0
943
+ for (let i: i32 = 0; i < count; i++) {
944
+ const d: u64 = toU64(t[i]) - toU64(n[i]) - borrow
945
+ out[i] = toU32(d)
946
+ borrow = (d >> 32) & 1
947
+ }
948
+ // `t` stays when there is no top limb and the subtraction borrowed.
949
+ const keep: u32 = toU32(borrow) & (top ^ 1)
950
+ const take: u32 = ctEq(keep, 0)
951
+ for (let i: i32 = 0; i < count; i++) {
952
+ out[i] = ctSelect(take, out[i], t[i])
953
+ }
954
+ }
955
+
956
+ /**
957
+ * `out = a b R^-1 mod n`, R = 2^(32 count), for `a` and `b` below `n`: CIOS,
958
+ * with `t` as scratch and the final subtraction by mask. `out` may be `a` or
959
+ * `b`. Every sum is at most (2^32 - 1) + (2^32 - 1)^2 + (2^32 - 1) = 2^64 - 1.
960
+ */
961
+ const rsaSignMontMul = (out: u32[], a: u32[], b: u32[], n: u32[], n0inv: u32, t: u32[], count: i32): void => {
962
+ if (
963
+ toI32(out.length) < 128 ||
964
+ toI32(b.length) < 128 ||
965
+ count > 128 ||
966
+ count < 1 ||
967
+ toI32(t.length) < 130 ||
968
+ toI32(a.length) < 128 ||
969
+ toI32(n.length) < 128
970
+ ) {
971
+ return
972
+ }
973
+ for (let i: i32 = 0; i < count; i++) {
974
+ // The first row reads `t` as zero, so no loop clears it first (one that
975
+ // the compiler would make a `memset` call).
976
+ const live: u64 = i === 0 ? 0 : 0xffffffff
977
+ const bi: u64 = toU64(b[i])
978
+ let carry: u64 = 0
979
+ for (let j: i32 = 0; j < count; j++) {
980
+ const s: u64 = (toU64(t[j]) & live) + toU64(a[j]) * bi + carry
981
+ t[j] = toU32(s)
982
+ carry = s >> 32
983
+ }
984
+ const top: u64 = (toU64(t[count]) & live) + carry
985
+ t[count] = toU32(top)
986
+ t[count + 1] = toU32(top >> 32)
987
+ const m: u64 = toU64(toU32(toU64(t[0]) * toU64(n0inv)))
988
+ let c: u64 = (toU64(t[0]) + m * toU64(n[0])) >> 32
989
+ for (let j: i32 = 1; j < count; j++) {
990
+ const s: u64 = toU64(t[j]) + m * toU64(n[j]) + c
991
+ t[j - 1] = toU32(s)
992
+ c = s >> 32
993
+ }
994
+ const last: u64 = toU64(t[count]) + c
995
+ t[count - 1] = toU32(last)
996
+ t[count] = t[count + 1] + toU32(last >> 32)
997
+ }
998
+ rsaSignReduce(out, t, t[count], n, count)
999
+ }
1000
+
1001
+ /**
1002
+ * One step of the fixed window: `acc = acc^16 table[nibble] R^-1 mod n`. Four
1003
+ * squarings, then every entry of the 16-entry `table` (entry `j` at `j count`)
1004
+ * read in full and the one at `nibble` kept by a `ctEq` mask into `sel`, then
1005
+ * one multiplication: the same work and the same addresses for every nibble.
1006
+ */
1007
+ const rsaSignWindowStep = (
1008
+ acc: u32[],
1009
+ table: u32[],
1010
+ sel: u32[],
1011
+ nibble: u32,
1012
+ n: u32[],
1013
+ n0inv: u32,
1014
+ t: u32[],
1015
+ count: i32
1016
+ ): void => {
1017
+ if (count < 1 || count > 128 || toI32(table.length) < 16 * count || toI32(sel.length) < 128) {
1018
+ return
1019
+ }
1020
+ for (let s: i32 = 0; s < 4; s++) {
1021
+ rsaSignMontMul(acc, acc, acc, n, n0inv, t, count)
1022
+ }
1023
+ for (let l: i32 = 0; l < count; l++) {
1024
+ sel[l] = 0
1025
+ }
1026
+ for (let j: i32 = 0; j < 16; j++) {
1027
+ const mask: u32 = ctEq(toU32(j), nibble)
1028
+ for (let l: i32 = 0; l < count; l++) {
1029
+ // Always true after the length test above; it is here for the prover.
1030
+ const at: i32 = j * count + l
1031
+ if (at < toI32(table.length)) {
1032
+ sel[l] = sel[l] | (table[at] & mask)
1033
+ }
1034
+ }
1035
+ }
1036
+ rsaSignMontMul(acc, acc, sel, n, n0inv, t, count)
1037
+ }
1038
+
1039
+ /**
1040
+ * R^2 mod n into `r`, by doubling 1 modulo `n` 64 count times; `t` is
1041
+ * scratch. The reduction is masked, so it may run on a secret prime.
1042
+ */
1043
+ const rsaSignR2 = (r: u32[], n: u32[], t: u32[], count: i32): void => {
1044
+ if (toI32(n.length) < 128 || count > 128 || count < 1 || toI32(r.length) < 128 || toI32(t.length) < 130) {
1045
+ return
1046
+ }
1047
+ for (let i: i32 = 0; i < 128; i++) {
1048
+ r[i] = 0
1049
+ }
1050
+ r[0] = 1
1051
+ for (let k: i32 = 0; k < count * 64; k++) {
1052
+ let carry: u32 = 0
1053
+ for (let i: i32 = 0; i < count; i++) {
1054
+ const v: u32 = r[i]
1055
+ t[i] = (v << 1) | carry
1056
+ carry = v >> 31
1057
+ }
1058
+ rsaSignReduce(r, t, carry, n, count)
1059
+ }
1060
+ }
1061
+
1062
+ /**
1063
+ * `out = a + b mod n` for `a` and `b` below `n`: the sum into `t`, then the
1064
+ * masked subtraction of `rsaSignReduce`. `out` may be `a` or `b`; `t` is
1065
+ * neither.
1066
+ */
1067
+ const rsaSignModAdd = (out: u32[], a: u32[], b: u32[], n: u32[], t: u32[], count: i32): void => {
1068
+ if (count < 1 || count > 128 || toI32(a.length) < 128 || toI32(b.length) < 128 || toI32(t.length) < 128) {
1069
+ return
1070
+ }
1071
+ let carry: u64 = 0
1072
+ for (let i: i32 = 0; i < count; i++) {
1073
+ const s: u64 = toU64(a[i]) + toU64(b[i]) + carry
1074
+ t[i] = toU32(s)
1075
+ carry = s >> 32
1076
+ }
1077
+ rsaSignReduce(out, t, toU32(carry), n, count)
1078
+ }
1079
+
1080
+ /**
1081
+ * `out = a - b mod n` for `a` and `b` below `n`: the difference into `t`, then
1082
+ * `n` added back under a `ctEq` mask of the borrow, never a branch. `out` may
1083
+ * be `a` or `b`; `t` is neither.
1084
+ */
1085
+ const rsaSignModSub = (out: u32[], a: u32[], b: u32[], n: u32[], t: u32[], count: i32): void => {
1086
+ if (
1087
+ count < 1 ||
1088
+ count > 128 ||
1089
+ toI32(out.length) < 128 ||
1090
+ toI32(a.length) < 128 ||
1091
+ toI32(b.length) < 128 ||
1092
+ toI32(n.length) < 128 ||
1093
+ toI32(t.length) < 128
1094
+ ) {
1095
+ return
1096
+ }
1097
+ let borrow: u64 = 0
1098
+ for (let i: i32 = 0; i < count; i++) {
1099
+ const d: u64 = toU64(a[i]) - toU64(b[i]) - borrow
1100
+ t[i] = toU32(d)
1101
+ borrow = (d >> 32) & 1
1102
+ }
1103
+ const back: u32 = ctEq(toU32(borrow), 1)
1104
+ let carry: u64 = 0
1105
+ for (let i: i32 = 0; i < count; i++) {
1106
+ const s: u64 = toU64(t[i]) + toU64(n[i] & back) + carry
1107
+ out[i] = toU32(s)
1108
+ carry = s >> 32
1109
+ }
1110
+ }
1111
+
1112
+ /** 1 when the `count`-limb `a` is below `b`, else 0: the borrow out of `a - b`, with no early exit. */
1113
+ const rsaSignLess = (a: u32[], b: u32[], count: i32): u32 => {
1114
+ if (count < 1 || count > 128 || toI32(a.length) < 128 || toI32(b.length) < 128) {
1115
+ return 0
1116
+ }
1117
+ let borrow: u64 = 0
1118
+ for (let i: i32 = 0; i < count; i++) {
1119
+ const d: u64 = toU64(a[i]) - toU64(b[i]) - borrow
1120
+ borrow = (d >> 32) & 1
1121
+ }
1122
+ return toU32(borrow)
1123
+ }
1124
+
1125
+ /**
1126
+ * `out = a b`, `2 count` limbs from two of `count`, by schoolbook rows of a
1127
+ * fixed length: the work depends on `count` alone. Each sum is at most
1128
+ * 2^64 - 1, as in `rsaSignMontMul`. `out` is neither `a` nor `b`.
1129
+ */
1130
+ const rsaSignMul = (out: u32[], a: u32[], b: u32[], count: i32): void => {
1131
+ if (count < 1 || count > 64 || toI32(out.length) < 128 || toI32(a.length) < 128 || toI32(b.length) < 128) {
1132
+ return
1133
+ }
1134
+ for (let i: i32 = 0; i < count; i++) {
1135
+ out[i] = 0
1136
+ out[i + count] = 0
1137
+ }
1138
+ for (let i: i32 = 0; i < count; i++) {
1139
+ const ai: u64 = toU64(a[i])
1140
+ let carry: u64 = 0
1141
+ for (let j: i32 = 0; j < count; j++) {
1142
+ const s: u64 = toU64(out[i + j]) + ai * toU64(b[j]) + carry
1143
+ out[i + j] = toU32(s)
1144
+ carry = s >> 32
1145
+ }
1146
+ out[i + count] = toU32(carry)
1147
+ }
1148
+ }
1149
+
1150
+ /** The low `len` bytes of the limbs `a`, big-endian, written into `out` at `at`. */
1151
+ const rsaSignStore = (out: u8[], at: i32, len: i32, a: u32[]): void => {
1152
+ if (at < 0 || len < 0 || len > 512 || toI32(a.length) < 128) {
1153
+ return
1154
+ }
1155
+ for (let j: i32 = 0; j < len; j++) {
1156
+ const o: i32 = at + len - 1 - j
1157
+ if (o >= 0 && o < toI32(out.length)) {
1158
+ out[o] = toU8(a[toI32(j / 4)] >> toU32((j & 3) << 3))
1159
+ }
1160
+ }
1161
+ }
1162
+
1163
+ /**
1164
+ * Fills the Montgomery constants of the key bytes `key` (`rsaSignKeyBytes`)
1165
+ * from its own `n`, `p` and `q`, so that signing computes none of them: R^2
1166
+ * and R^3 mod `p` and mod `q` for R = 2^(32 c), and R^2 mod `n` for
1167
+ * R = 2^(32 ⌈k / 4⌉). R^2 is 1 doubled modulo the prime under `rsaSignReduce`'s
1168
+ * mask and R^3 one Montgomery product of R^2 with itself, so nothing branches
1169
+ * on `p` or `q`. Every limb array is wiped. A key of the wrong shape is left
1170
+ * as it is.
1171
+ */
1172
+ const rsaSignPrecompute = (key: u8[]): void => {
1173
+ const k: i32 = rsaSignKeySize(key)
1174
+ const w: i32 = rsaSignHalfWidth(k)
1175
+ if (k < 256 || k > 512 || w < 4 || w > 256) {
1176
+ return
1177
+ }
1178
+ const count: i32 = toI32((k + 3) / 4)
1179
+ const c: i32 = toI32(w / 4)
1180
+ const x: u32[] = new Array<u32>(128)
1181
+ const r2: u32[] = new Array<u32>(128)
1182
+ const r3: u32[] = new Array<u32>(128)
1183
+ const t: u32[] = new Array<u32>(130)
1184
+ for (let half: i32 = 0; half < 2; half++) {
1185
+ rsaSignLimbs(x, key, 3 * k + half * w, w, c)
1186
+ rsaSignR2(r2, x, t, c)
1187
+ rsaSignMontMul(r3, r2, r2, x, rsaSignMontInverse(x[0]), t, c)
1188
+ rsaSignStore(key, 3 * k + (2 * half + 5) * w, w, r2)
1189
+ rsaSignStore(key, 3 * k + (2 * half + 6) * w, w, r3)
1190
+ }
1191
+ rsaSignLimbs(x, key, 0, k, count)
1192
+ rsaSignR2(r2, x, t, count)
1193
+ rsaSignStore(key, 3 * k + 9 * w, k, r2)
1194
+ wipe(x)
1195
+ wipe(r2)
1196
+ wipe(r3)
1197
+ wipe(t)
1198
+ }
1199
+
1200
+ /**
1201
+ * 0 when the CRT values of the key bytes `key` hold together, nonzero
1202
+ * otherwise, with no branch on them: `p` and `q` odd, `dP` below `p`, `dQ`
1203
+ * below `q`, `qInv` below `p`, `p q = n` over every limb of the product, and
1204
+ * `q qInv = 1 mod p` (two Montgomery products: `q qInv R^-1`, then by R^2).
1205
+ * Every limb array is wiped.
1206
+ */
1207
+ const rsaSignCrtSound = (key: u8[], k: i32): u32 => {
1208
+ const w: i32 = rsaSignHalfWidth(k)
1209
+ if (k < 256 || k > 512 || w < 4 || w > 256 || toI32(key.length) !== 4 * k + 9 * w) {
1210
+ return 1
1211
+ }
1212
+ const count: i32 = toI32((k + 3) / 4)
1213
+ const c: i32 = toI32(w / 4)
1214
+ const base: i32 = 3 * k
1215
+ const n: u32[] = new Array<u32>(128)
1216
+ rsaSignLimbs(n, key, 0, k, count)
1217
+ const p: u32[] = new Array<u32>(128)
1218
+ rsaSignLimbs(p, key, base, w, c)
1219
+ const q: u32[] = new Array<u32>(128)
1220
+ rsaSignLimbs(q, key, base + w, w, c)
1221
+ const dp: u32[] = new Array<u32>(128)
1222
+ rsaSignLimbs(dp, key, base + 2 * w, w, c)
1223
+ const dq: u32[] = new Array<u32>(128)
1224
+ rsaSignLimbs(dq, key, base + 3 * w, w, c)
1225
+ const qinv: u32[] = new Array<u32>(128)
1226
+ rsaSignLimbs(qinv, key, base + 4 * w, w, c)
1227
+ const r2p: u32[] = new Array<u32>(128)
1228
+ rsaSignLimbs(r2p, key, base + 5 * w, w, c)
1229
+ let bad: u32 = ((p[0] & 1) ^ 1) | ((q[0] & 1) ^ 1)
1230
+ bad = bad | (rsaSignLess(dp, p, c) ^ 1) | (rsaSignLess(dq, q, c) ^ 1) | (rsaSignLess(qinv, p, c) ^ 1)
1231
+ const prod: u32[] = new Array<u32>(128)
1232
+ rsaSignMul(prod, p, q, c)
1233
+ for (let l: i32 = 0; l < c; l++) {
1234
+ const h: i32 = c + l
1235
+ bad = bad | (prod[l] ^ n[l]) | (prod[h] ^ (h < count ? n[h] : 0))
1236
+ }
1237
+ const t: u32[] = new Array<u32>(130)
1238
+ const p0inv: u32 = rsaSignMontInverse(p[0])
1239
+ rsaSignMontMul(prod, q, qinv, p, p0inv, t, c)
1240
+ rsaSignMontMul(prod, prod, r2p, p, p0inv, t, c)
1241
+ bad = bad | (prod[0] ^ 1)
1242
+ for (let l: i32 = 1; l < c; l++) {
1243
+ bad = bad | prod[l]
1244
+ }
1245
+ wipe(p)
1246
+ wipe(q)
1247
+ wipe(dp)
1248
+ wipe(dq)
1249
+ wipe(qinv)
1250
+ wipe(r2p)
1251
+ wipe(prod)
1252
+ wipe(t)
1253
+ return bad
1254
+ }
1255
+
1256
+ /**
1257
+ * `acc = b^x R mod n` for `mm = b R mod n`, R = 2^(32 count): the 16 powers
1258
+ * `b^j R` into `table`, then the fixed 4-bit window over every nibble of the
1259
+ * `count` limbs of `x`, leading zeros included. `one` holds 1, `r2` R^2 mod n;
1260
+ * `entry` and `sel` are scratch.
1261
+ */
1262
+ const rsaSignPow = (
1263
+ acc: u32[],
1264
+ mm: u32[],
1265
+ x: u32[],
1266
+ n: u32[],
1267
+ n0inv: u32,
1268
+ r2: u32[],
1269
+ one: u32[],
1270
+ table: u32[],
1271
+ entry: u32[],
1272
+ sel: u32[],
1273
+ t: u32[],
1274
+ count: i32
1275
+ ): void => {
1276
+ if (
1277
+ count < 1 ||
1278
+ count > 128 ||
1279
+ toI32(table.length) < 16 * count ||
1280
+ toI32(acc.length) < 128 ||
1281
+ toI32(x.length) < 128 ||
1282
+ toI32(entry.length) < 128
1283
+ ) {
1284
+ return
1285
+ }
1286
+ rsaSignMontMul(entry, one, r2, n, n0inv, t, count)
1287
+ for (let j: i32 = 0; j < 16; j++) {
1288
+ for (let l: i32 = 0; l < count; l++) {
1289
+ // Always true after the length test above; it is here for the prover.
1290
+ const at: i32 = j * count + l
1291
+ if (at < toI32(table.length)) {
1292
+ table[at] = entry[l]
1293
+ }
1294
+ }
1295
+ rsaSignMontMul(entry, entry, mm, n, n0inv, t, count)
1296
+ }
1297
+ for (let l: i32 = 0; l < count; l++) {
1298
+ acc[l] = table[l]
1299
+ }
1300
+ for (let nib: i32 = 8 * count - 1; nib >= 0; nib--) {
1301
+ const nibble: u32 = (x[toI32(nib / 8)] >> toU32((nib & 7) * 4)) & 15
1302
+ rsaSignWindowStep(acc, table, sel, nibble, n, n0inv, t, count)
1303
+ }
1304
+ }
1305
+
1306
+ /**
1307
+ * One half of the CRT: `acc = m^dx R mod x` for the prime `x` of `c` limbs,
1308
+ * its exponent `dx`, its R^2 and R^3 (R = 2^(32 c)), and the `count`-limb
1309
+ * `m`. `m R mod x` is `mh R^3 + ml R^2`, each Montgomery-multiplied by R^-1,
1310
+ * for m = mh R + ml with both halves below R: no division by the secret
1311
+ * prime. `table`, `entry`, `mm` and `sel` are scratch.
1312
+ */
1313
+ const rsaSignHalf = (
1314
+ acc: u32[],
1315
+ m: u32[],
1316
+ x: u32[],
1317
+ r2: u32[],
1318
+ r3: u32[],
1319
+ dx: u32[],
1320
+ one: u32[],
1321
+ table: u32[],
1322
+ entry: u32[],
1323
+ mm: u32[],
1324
+ sel: u32[],
1325
+ t: u32[],
1326
+ count: i32,
1327
+ c: i32
1328
+ ): void => {
1329
+ if (
1330
+ c < 1 ||
1331
+ c > 64 ||
1332
+ count < c ||
1333
+ count > 2 * c ||
1334
+ toI32(m.length) < 128 ||
1335
+ toI32(entry.length) < 128 ||
1336
+ toI32(sel.length) < 128 ||
1337
+ toI32(x.length) < 128
1338
+ ) {
1339
+ return
1340
+ }
1341
+ const x0inv: u32 = rsaSignMontInverse(x[0])
1342
+ for (let l: i32 = 0; l < c; l++) {
1343
+ sel[l] = m[l]
1344
+ const h: i32 = c + l
1345
+ entry[l] = h < count ? m[h] : 0
1346
+ }
1347
+ rsaSignMontMul(mm, entry, r3, x, x0inv, t, c)
1348
+ rsaSignMontMul(acc, sel, r2, x, x0inv, t, c)
1349
+ rsaSignModAdd(mm, mm, acc, x, t, c)
1350
+ rsaSignPow(acc, mm, dx, x, x0inv, r2, one, table, entry, sel, t, c)
1351
+ }
1352
+
1353
+ /**
1354
+ * 0 when `s^e mod n` is `m`, nonzero otherwise, for the plain `s` below R and
1355
+ * the `count`-limb `e`. `e`, `s` and `m` are public, so square and multiply
1356
+ * may branch on the exponent's bits. `entry` and `mm` are scratch.
1357
+ */
1358
+ const rsaSignOpens = (
1359
+ s: u32[],
1360
+ m: u32[],
1361
+ el: u32[],
1362
+ n: u32[],
1363
+ n0inv: u32,
1364
+ r2: u32[],
1365
+ one: u32[],
1366
+ entry: u32[],
1367
+ mm: u32[],
1368
+ t: u32[],
1369
+ count: i32
1370
+ ): u32 => {
1371
+ if (
1372
+ count < 1 ||
1373
+ count > 128 ||
1374
+ toI32(m.length) < 128 ||
1375
+ toI32(el.length) < 128 ||
1376
+ toI32(entry.length) < 128 ||
1377
+ toI32(mm.length) < 128
1378
+ ) {
1379
+ return 1
1380
+ }
1381
+ rsaSignMontMul(mm, s, r2, n, n0inv, t, count)
1382
+ for (let l: i32 = 0; l < count; l++) {
1383
+ entry[l] = mm[l]
1384
+ }
1385
+ let started: boolean = false
1386
+ for (let bit: i32 = 32 * count - 1; bit >= 0; bit--) {
1387
+ const set: u32 = (el[toI32(bit / 32)] >> toU32(bit & 31)) & 1
1388
+ if (started) {
1389
+ rsaSignMontMul(entry, entry, entry, n, n0inv, t, count)
1390
+ if (set === 1) {
1391
+ rsaSignMontMul(entry, entry, mm, n, n0inv, t, count)
1392
+ }
1393
+ } else if (set === 1) {
1394
+ started = true
1395
+ }
1396
+ }
1397
+ rsaSignMontMul(entry, entry, one, n, n0inv, t, count)
1398
+ let differ: u32 = started ? 0 : 1
1399
+ for (let l: i32 = 0; l < count; l++) {
1400
+ differ = differ | (entry[l] ^ m[l])
1401
+ }
1402
+ return differ
1403
+ }
1404
+
1405
+ /**
1406
+ * RSASP1 under the key bytes `key` (`rsaSignKeyBytes`) by the CRT (RFC 8017
1407
+ * §5.2.1, step 2b): `s1 = m^dP mod p` and `s2 = m^dQ mod q`, each a fixed
1408
+ * 4-bit window over every nibble of a half-length exponent modulo a
1409
+ * half-length prime, then `h = (s1 - s2) qInv mod p` and `s = s2 + q h`, for
1410
+ * the `k`-byte `m` below `n`. The answer is raised to `e` and compared with
1411
+ * `m`, its limbs past `n`'s and its value against `n` checked too, before any
1412
+ * byte of it is returned, so a fault in either half, which would give a value
1413
+ * right modulo one prime and wrong modulo the other and so factor `n`
1414
+ * (Bellcore), answers `null`. `null` too for a key of the wrong shape and an
1415
+ * `m` of the wrong length or not below `n`. Every limb array that held a
1416
+ * prime, an exponent, a constant made from a prime or a power of `m` is
1417
+ * wiped. A key value of the first form, `3 k` bytes, is `rsaSignFullOp`'s.
1418
+ */
1419
+ const rsaSignPrivateOp = (key: u8[], m: u8[]): u8[] | null => {
1420
+ const k: i32 = rsaSignKeySize(key)
1421
+ if (k >= 256 && k <= 512 && toI32(key.length) === 3 * k) {
1422
+ return rsaSignFullOp(key, m)
1423
+ }
1424
+ const w: i32 = rsaSignHalfWidth(k)
1425
+ if (
1426
+ k < 256 ||
1427
+ k > 512 ||
1428
+ w < 4 ||
1429
+ w > 256 ||
1430
+ toI32(m.length) !== k ||
1431
+ toI32(key.length) < k ||
1432
+ (toI32(key[k - 1]) & 1) === 0
1433
+ ) {
1434
+ return null
1435
+ }
1436
+ const count: i32 = toI32((k + 3) / 4)
1437
+ const c: i32 = toI32(w / 4)
1438
+ const base: i32 = 3 * k
1439
+ const n: u32[] = new Array<u32>(128)
1440
+ rsaSignLimbs(n, key, 0, k, count)
1441
+ const ml: u32[] = new Array<u32>(128)
1442
+ rsaSignLimbs(ml, m, 0, k, count)
1443
+ // `m < n`: both are public, so the compare may exit early.
1444
+ let below: i32 = 0
1445
+ for (let i: i32 = count - 1; i >= 0; i--) {
1446
+ if (below === 0 && ml[i] !== n[i]) {
1447
+ below = ml[i] < n[i] ? 1 : -1
1448
+ }
1449
+ }
1450
+ if (below !== 1) {
1451
+ return null
1452
+ }
1453
+ const p: u32[] = new Array<u32>(128)
1454
+ rsaSignLimbs(p, key, base, w, c)
1455
+ const q: u32[] = new Array<u32>(128)
1456
+ rsaSignLimbs(q, key, base + w, w, c)
1457
+ const dp: u32[] = new Array<u32>(128)
1458
+ rsaSignLimbs(dp, key, base + 2 * w, w, c)
1459
+ const dq: u32[] = new Array<u32>(128)
1460
+ rsaSignLimbs(dq, key, base + 3 * w, w, c)
1461
+ const qinv: u32[] = new Array<u32>(128)
1462
+ rsaSignLimbs(qinv, key, base + 4 * w, w, c)
1463
+ const r2p: u32[] = new Array<u32>(128)
1464
+ rsaSignLimbs(r2p, key, base + 5 * w, w, c)
1465
+ const r3p: u32[] = new Array<u32>(128)
1466
+ rsaSignLimbs(r3p, key, base + 6 * w, w, c)
1467
+ const r2q: u32[] = new Array<u32>(128)
1468
+ rsaSignLimbs(r2q, key, base + 7 * w, w, c)
1469
+ const r3q: u32[] = new Array<u32>(128)
1470
+ rsaSignLimbs(r3q, key, base + 8 * w, w, c)
1471
+ const r2n: u32[] = new Array<u32>(128)
1472
+ rsaSignLimbs(r2n, key, base + 9 * w, k, count)
1473
+ const one: u32[] = new Array<u32>(128)
1474
+ one[0] = 1
1475
+ const t: u32[] = new Array<u32>(130)
1476
+ // table[j] = m^j R mod p (then mod q), j = 0 to 15, one after another.
1477
+ const table: u32[] = new Array<u32>(1024)
1478
+ const entry: u32[] = new Array<u32>(128)
1479
+ const mm: u32[] = new Array<u32>(128)
1480
+ const sel: u32[] = new Array<u32>(128)
1481
+ const sp: u32[] = new Array<u32>(128)
1482
+ const sq: u32[] = new Array<u32>(128)
1483
+ rsaSignHalf(sp, ml, p, r2p, r3p, dp, one, table, entry, mm, sel, t, count, c)
1484
+ rsaSignHalf(sq, ml, q, r2q, r3q, dq, one, table, entry, mm, sel, t, count, c)
1485
+ const p0inv: u32 = rsaSignMontInverse(p[0])
1486
+ // s2 out of Montgomery form mod q, then into it mod p (s2 < q < R).
1487
+ rsaSignMontMul(sq, sq, one, q, rsaSignMontInverse(q[0]), t, c)
1488
+ rsaSignMontMul(entry, sq, r2p, p, p0inv, t, c)
1489
+ // h = (s1 - s2) qInv mod p: the R of s1 R - s2 R cancels in the product.
1490
+ rsaSignModSub(entry, sp, entry, p, t, c)
1491
+ rsaSignMontMul(entry, entry, qinv, p, p0inv, t, c)
1492
+ // s = s2 + q h, below n, in at most 2 c limbs.
1493
+ const s: u32[] = new Array<u32>(128)
1494
+ rsaSignMul(s, entry, q, c)
1495
+ let carry: u64 = 0
1496
+ for (let l: i32 = 0; l < c; l++) {
1497
+ const v: u64 = toU64(s[l]) + toU64(sq[l]) + carry
1498
+ s[l] = toU32(v)
1499
+ carry = v >> 32
1500
+ }
1501
+ for (let l: i32 = 0; l < c; l++) {
1502
+ const v: u64 = toU64(s[c + l]) + carry
1503
+ s[c + l] = toU32(v)
1504
+ carry = v >> 32
1505
+ }
1506
+ // The check: no limb past n's, s below n, and s^e mod n is m.
1507
+ let differ: u32 = toU32(carry) | (rsaSignLess(s, n, count) ^ 1)
1508
+ for (let l: i32 = 0; l < c; l++) {
1509
+ const h: i32 = c + l
1510
+ differ = differ | (h < count ? 0 : s[h])
1511
+ }
1512
+ const el: u32[] = new Array<u32>(128)
1513
+ rsaSignLimbs(el, key, 2 * k, k, count)
1514
+ differ = differ | rsaSignOpens(s, ml, el, n, rsaSignMontInverse(n[0]), r2n, one, entry, mm, t, count)
1515
+ const ok: boolean = differ === 0
1516
+ const signature: u8[] = ok ? rsaSignBytes(s, k) : []
1517
+ wipe(p)
1518
+ wipe(q)
1519
+ wipe(dp)
1520
+ wipe(dq)
1521
+ wipe(qinv)
1522
+ wipe(r2p)
1523
+ wipe(r3p)
1524
+ wipe(r2q)
1525
+ wipe(r3q)
1526
+ wipe(t)
1527
+ wipe(table)
1528
+ wipe(entry)
1529
+ wipe(mm)
1530
+ wipe(sel)
1531
+ wipe(sp)
1532
+ wipe(sq)
1533
+ wipe(s)
1534
+ if (!ok) {
1535
+ return null
1536
+ }
1537
+ return signature
1538
+ }
1539
+
1540
+ /**
1541
+ * RSASP1 by the first form of the key (RFC 8017 §5.2.1, step 2a): `m^d mod
1542
+ * n`, by the fixed 4-bit window over every nibble of the `⌈k / 4⌉` limbs of
1543
+ * `d`, for the `k`-byte `m` below `n`. The key value is either form: `n`, `d`
1544
+ * and `e` alone in `3 k` bytes, whose R^2 modulo `n` is made here, or
1545
+ * `rsaSignKeyBytes`'s, whose R^2 modulo `n` is read. The answer is raised to
1546
+ * `e` and compared with `m`, and checked below `n`, before any byte of it is
1547
+ * returned, so a key whose exponents do not undo each other answers `null`,
1548
+ * as do a key of the wrong shape and an `m` of the wrong length or not below
1549
+ * `n`. Every limb array that held `d` or a power of `m` is wiped.
1550
+ */
1551
+ const rsaSignFullOp = (key: u8[], m: u8[]): u8[] | null => {
1552
+ const k: i32 = rsaSignKeySize(key)
1553
+ const w: i32 = rsaSignHalfWidth(k)
1554
+ if (
1555
+ k < 256 ||
1556
+ k > 512 ||
1557
+ w < 4 ||
1558
+ w > 256 ||
1559
+ toI32(m.length) !== k ||
1560
+ toI32(key.length) < k ||
1561
+ toI32(key.length) < 3 * k ||
1562
+ (toI32(key[k - 1]) & 1) === 0
1563
+ ) {
1564
+ return null
1565
+ }
1566
+ const count: i32 = toI32((k + 3) / 4)
1567
+ const n: u32[] = new Array<u32>(128)
1568
+ rsaSignLimbs(n, key, 0, k, count)
1569
+ const ml: u32[] = new Array<u32>(128)
1570
+ rsaSignLimbs(ml, m, 0, k, count)
1571
+ // `m < n`: both are public, so the compare may exit early.
1572
+ let below: i32 = 0
1573
+ for (let i: i32 = count - 1; i >= 0; i--) {
1574
+ if (below === 0 && ml[i] !== n[i]) {
1575
+ below = ml[i] < n[i] ? 1 : -1
1576
+ }
1577
+ }
1578
+ if (below !== 1) {
1579
+ return null
1580
+ }
1581
+ const dl: u32[] = new Array<u32>(128)
1582
+ rsaSignLimbs(dl, key, k, k, count)
1583
+ const el: u32[] = new Array<u32>(128)
1584
+ rsaSignLimbs(el, key, 2 * k, k, count)
1585
+ const t: u32[] = new Array<u32>(130)
1586
+ const r2n: u32[] = new Array<u32>(128)
1587
+ if (toI32(key.length) === 3 * k) {
1588
+ rsaSignR2(r2n, n, t, count)
1589
+ } else {
1590
+ rsaSignLimbs(r2n, key, 3 * k + 9 * w, k, count)
1591
+ }
1592
+ const one: u32[] = new Array<u32>(128)
1593
+ one[0] = 1
1594
+ const n0inv: u32 = rsaSignMontInverse(n[0])
1595
+ const table: u32[] = new Array<u32>(2048)
1596
+ const entry: u32[] = new Array<u32>(128)
1597
+ const mm: u32[] = new Array<u32>(128)
1598
+ const sel: u32[] = new Array<u32>(128)
1599
+ const acc: u32[] = new Array<u32>(128)
1600
+ rsaSignMontMul(mm, ml, r2n, n, n0inv, t, count)
1601
+ rsaSignPow(acc, mm, dl, n, n0inv, r2n, one, table, entry, sel, t, count)
1602
+ rsaSignMontMul(acc, acc, one, n, n0inv, t, count)
1603
+ const differ: u32 =
1604
+ (rsaSignLess(acc, n, count) ^ 1) | rsaSignOpens(acc, ml, el, n, n0inv, r2n, one, entry, mm, t, count)
1605
+ const ok: boolean = differ === 0
1606
+ const signature: u8[] = ok ? rsaSignBytes(acc, k) : []
1607
+ wipe(dl)
1608
+ wipe(t)
1609
+ wipe(table)
1610
+ wipe(entry)
1611
+ wipe(mm)
1612
+ wipe(sel)
1613
+ wipe(acc)
1614
+ if (!ok) {
1615
+ return null
1616
+ }
1617
+ return signature
1618
+ }
1619
+
1620
+ /**
1621
+ * Whether `m^d mod n` (`rsaSignFullOp`) opens to `m` under `e`: the load's
1622
+ * check that `d`, which CRT signing does not read but the salt does, is
1623
+ * `e`'s inverse. It is run once per key, never per signature.
1624
+ */
1625
+ const rsaSignFullOpens = (key: u8[], m: u8[]): boolean => {
1626
+ const s: u8[] | null = rsaSignFullOp(key, m)
1627
+ if (s === null) {
1628
+ return false
1629
+ }
1630
+ wipe(s)
1631
+ return true
1632
+ }