@ac-kit/crypto-rsa 0.0.0-stage → 0.1.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 (76) hide show
  1. package/CHANGELOG.md +68 -0
  2. package/LICENSE +28 -0
  3. package/README.md +113 -2
  4. package/dist/_bytes.d.ts +18 -0
  5. package/dist/_bytes.d.ts.map +1 -0
  6. package/dist/_bytes.js +42 -0
  7. package/dist/_bytes.js.map +1 -0
  8. package/dist/encoding/_der.d.ts +51 -0
  9. package/dist/encoding/_der.d.ts.map +1 -0
  10. package/dist/encoding/_der.js +173 -0
  11. package/dist/encoding/_der.js.map +1 -0
  12. package/dist/encoding/rsa-algorithm.d.ts +132 -0
  13. package/dist/encoding/rsa-algorithm.d.ts.map +1 -0
  14. package/dist/encoding/rsa-algorithm.js +475 -0
  15. package/dist/encoding/rsa-algorithm.js.map +1 -0
  16. package/dist/hash/rsa-hash.d.ts +68 -0
  17. package/dist/hash/rsa-hash.d.ts.map +1 -0
  18. package/dist/hash/rsa-hash.js +86 -0
  19. package/dist/hash/rsa-hash.js.map +1 -0
  20. package/dist/index.d.ts +9 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +9 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/key/_generate.d.ts +39 -0
  25. package/dist/key/_generate.d.ts.map +1 -0
  26. package/dist/key/_generate.js +124 -0
  27. package/dist/key/_generate.js.map +1 -0
  28. package/dist/key/_key-state.d.ts +53 -0
  29. package/dist/key/_key-state.d.ts.map +1 -0
  30. package/dist/key/_key-state.js +26 -0
  31. package/dist/key/_key-state.js.map +1 -0
  32. package/dist/key/_primality.d.ts +22 -0
  33. package/dist/key/_primality.d.ts.map +1 -0
  34. package/dist/key/_primality.js +156 -0
  35. package/dist/key/_primality.js.map +1 -0
  36. package/dist/key/_primitives.d.ts +27 -0
  37. package/dist/key/_primitives.d.ts.map +1 -0
  38. package/dist/key/_primitives.js +247 -0
  39. package/dist/key/_primitives.js.map +1 -0
  40. package/dist/key/_validate.d.ts +60 -0
  41. package/dist/key/_validate.d.ts.map +1 -0
  42. package/dist/key/_validate.js +328 -0
  43. package/dist/key/_validate.js.map +1 -0
  44. package/dist/key/rsa-private-key.d.ts +180 -0
  45. package/dist/key/rsa-private-key.d.ts.map +1 -0
  46. package/dist/key/rsa-private-key.js +479 -0
  47. package/dist/key/rsa-private-key.js.map +1 -0
  48. package/dist/key/rsa-public-key.d.ts +117 -0
  49. package/dist/key/rsa-public-key.d.ts.map +1 -0
  50. package/dist/key/rsa-public-key.js +196 -0
  51. package/dist/key/rsa-public-key.js.map +1 -0
  52. package/dist/rsa-error.d.ts +54 -0
  53. package/dist/rsa-error.d.ts.map +1 -0
  54. package/dist/rsa-error.js +14 -0
  55. package/dist/rsa-error.js.map +1 -0
  56. package/dist/scheme/_scheme-checks.d.ts +50 -0
  57. package/dist/scheme/_scheme-checks.d.ts.map +1 -0
  58. package/dist/scheme/_scheme-checks.js +162 -0
  59. package/dist/scheme/_scheme-checks.js.map +1 -0
  60. package/dist/scheme/_signature.d.ts +8 -0
  61. package/dist/scheme/_signature.d.ts.map +1 -0
  62. package/dist/scheme/_signature.js +13 -0
  63. package/dist/scheme/_signature.js.map +1 -0
  64. package/dist/scheme/rsaes-oaep.d.ts +75 -0
  65. package/dist/scheme/rsaes-oaep.d.ts.map +1 -0
  66. package/dist/scheme/rsaes-oaep.js +191 -0
  67. package/dist/scheme/rsaes-oaep.js.map +1 -0
  68. package/dist/scheme/rsassa-pkcs1-v1_5.d.ts +73 -0
  69. package/dist/scheme/rsassa-pkcs1-v1_5.d.ts.map +1 -0
  70. package/dist/scheme/rsassa-pkcs1-v1_5.js +133 -0
  71. package/dist/scheme/rsassa-pkcs1-v1_5.js.map +1 -0
  72. package/dist/scheme/rsassa-pss.d.ts +88 -0
  73. package/dist/scheme/rsassa-pss.d.ts.map +1 -0
  74. package/dist/scheme/rsassa-pss.js +175 -0
  75. package/dist/scheme/rsassa-pss.js.map +1 -0
  76. package/package.json +75 -3
@@ -0,0 +1,247 @@
1
+ import { getRandomBytes } from "@ac-kit/crypto-random";
2
+ import { ConstantTimeModulus, constantTimeUnsignedAdd, constantTimeUnsignedModInverse, constantTimeUnsignedMultiply, } from "@ac-kit/crypto-safe";
3
+ import { RsaError } from "../rsa-error.js";
4
+ import { publicStateOf, } from "./_key-state.js";
5
+ /** Bytes of each random blinding factor of the exponents and the moduli. */
6
+ const BLINDING_BYTES = 8;
7
+ /**
8
+ * RSAEP / RSAVP1 (RFC 8017 §5.1.1, §5.2.2): `input^e mod n` over `k` bytes, or
9
+ * `undefined` when `input` is not below n. Constant time in `input`, which an
10
+ * encryption keeps secret; the range check is the only branch on it, and no
11
+ * encoding this package makes is out of range.
12
+ */
13
+ export function rsaPublicOperation(state, input) {
14
+ const { ring } = state;
15
+ const value = ring.create();
16
+ const out = new Uint8Array(state.modulus.length);
17
+ try {
18
+ if (ring.fromBytesBe(value, input) === 0) {
19
+ return undefined;
20
+ }
21
+ ring.power(value, value, state.publicExponent);
22
+ ring.toBytesBe(out, value);
23
+ return out;
24
+ }
25
+ finally {
26
+ value.fill(0);
27
+ }
28
+ }
29
+ /**
30
+ * RSADP / RSASP1 (RFC 8017 §5.1.2, §5.2.1): `input^d mod n` over `k` bytes, for
31
+ * an `input` below n (the caller checks). Constant time in the key, the input
32
+ * and the result, with the defences of the CFRG's RSA implementation guidance
33
+ * (draft-irtf-cfrg-rsa-guidance §6) on every call:
34
+ *
35
+ * - Base blinding: the input is multiplied by bb^e for a fresh random bb, and the
36
+ * result by bb⁻¹;
37
+ * - Exponent blinding: each exponent d_i becomes d_i + b_i·(r_i − 1) for a fresh
38
+ * 64-bit b_i (d + b·(e·d − 1) for a key without primes);
39
+ * - Modulus blinding: each prime's exponentiation runs modulo g_i·r_i for a fresh
40
+ * odd 64-bit g_i;
41
+ * - The result is checked by raising it to e, so that a fault in the CRT
42
+ * computation cannot release a value that factors n (Bellcore).
43
+ *
44
+ * @throws {RsaError} `privateKeyFault` when the check fails.
45
+ */
46
+ export function rsaPrivateOperation(state, input) {
47
+ const publicState = publicStateOf(state.publicKey);
48
+ const { ring } = publicState;
49
+ const length = publicState.modulus.length;
50
+ const original = ring.create();
51
+ const value = ring.create();
52
+ const blinding = ring.create();
53
+ const unblinding = ring.create();
54
+ const check = ring.create();
55
+ const blindingBytes = new Uint8Array(length);
56
+ const unblindingBytes = new Uint8Array(length);
57
+ const out = new Uint8Array(length);
58
+ try {
59
+ ring.fromBytesBe(original, input);
60
+ drawBlinding_(publicState, blindingBytes, unblindingBytes);
61
+ ring.fromBytesBe(blinding, blindingBytes);
62
+ ring.fromBytesBe(unblinding, unblindingBytes);
63
+ ring.power(value, blinding, publicState.publicExponent);
64
+ ring.multiply(value, value, original);
65
+ if (state.primes === undefined) {
66
+ exponentiateWithoutPrimes_(state, publicState, value);
67
+ }
68
+ else {
69
+ exponentiateCrt_(state.primes, publicState, value);
70
+ }
71
+ ring.multiply(value, value, unblinding);
72
+ ring.power(check, value, publicState.publicExponent);
73
+ const valid = ring.isEqual(check, original);
74
+ ring.toBytesBe(out, value);
75
+ if (valid === 0) {
76
+ out.fill(0);
77
+ throw new RsaError("privateKeyFault", "An RSA private-key result failed its check");
78
+ }
79
+ return out;
80
+ }
81
+ finally {
82
+ for (const element of [original, value, blinding, unblinding, check]) {
83
+ element.fill(0);
84
+ }
85
+ blindingBytes.fill(0);
86
+ unblindingBytes.fill(0);
87
+ }
88
+ }
89
+ /**
90
+ * A uniform bb in [1, n − 1] invertible modulo n, and bb⁻¹. Rejection reveals
91
+ * only that a discarded candidate was refused.
92
+ */
93
+ function drawBlinding_(state, blinding, unblinding) {
94
+ const { ring, modulus } = state;
95
+ const excess = 8 * modulus.length - state.modulusBitLength;
96
+ const element = ring.create();
97
+ try {
98
+ for (;;) {
99
+ const candidate = getRandomBytes(modulus.length);
100
+ try {
101
+ candidate[0] = candidate[0] & (0xff >>> excess);
102
+ const inRange = ring.fromBytesBe(element, candidate) & (1 - ring.isZero(element));
103
+ const invertible = constantTimeUnsignedModInverse(unblinding, candidate, modulus);
104
+ if ((inRange & invertible) === 1) {
105
+ blinding.set(candidate);
106
+ return;
107
+ }
108
+ }
109
+ finally {
110
+ candidate.fill(0);
111
+ }
112
+ }
113
+ }
114
+ finally {
115
+ element.fill(0);
116
+ }
117
+ }
118
+ /** `value = value^(d + b·(e·d − 1)) mod n` for a fresh 64-bit b. */
119
+ function exponentiateWithoutPrimes_(state, publicState, value) {
120
+ const exponent = blindExponent_(state.privateExponent, state.multipleOfLambda);
121
+ try {
122
+ publicState.ring.power(value, value, exponent);
123
+ }
124
+ finally {
125
+ exponent.fill(0);
126
+ }
127
+ }
128
+ /** `exponent + b · multiple` for a fresh random 64-bit b. */
129
+ function blindExponent_(exponent, multiple) {
130
+ const factor = getRandomBytes(BLINDING_BYTES);
131
+ const product = new Uint8Array(multiple.length + BLINDING_BYTES);
132
+ const blinded = new Uint8Array(Math.max(product.length, exponent.length) + 1);
133
+ try {
134
+ constantTimeUnsignedMultiply(product, factor, multiple);
135
+ constantTimeUnsignedAdd(blinded, product, exponent);
136
+ return blinded;
137
+ }
138
+ finally {
139
+ factor.fill(0);
140
+ product.fill(0);
141
+ }
142
+ }
143
+ /**
144
+ * `value = value^d mod n` by the CRT (RFC 8017 §5.1.2 step 2.b), each
145
+ * exponentiation blinded in its exponent and its modulus, then Garner's
146
+ * recombination in the arithmetic modulo n, where every partial sum is below n
147
+ * so the modular operations are exact.
148
+ */
149
+ function exponentiateCrt_(primes, publicState, value) {
150
+ const { ring } = publicState;
151
+ const length = publicState.modulus.length;
152
+ const valueBytes = new Uint8Array(length);
153
+ const residues = [];
154
+ const scratch = [];
155
+ const elements = [];
156
+ try {
157
+ ring.toBytesBe(valueBytes, value);
158
+ for (const prime of primes) {
159
+ residues.push(exponentiateModPrime_(prime, valueBytes));
160
+ }
161
+ const first = primes[0];
162
+ const second = primes[1];
163
+ const secondBytes = bytesOf_(second.ring, residues[1], scratch);
164
+ const difference = first.ring.create();
165
+ const coefficient = first.ring.create();
166
+ elements.push(difference, coefficient);
167
+ // h = (m_1 − m_2)·qInv mod p.
168
+ first.ring.reduceBytesBe(difference, secondBytes);
169
+ first.ring.subtract(difference, residues[0], difference);
170
+ first.ring.fromBytesBe(coefficient, first.coefficient);
171
+ first.ring.multiply(difference, difference, coefficient);
172
+ // m = m_2 + q·h.
173
+ const factor = ring.create();
174
+ const term = ring.create();
175
+ elements.push(factor, term);
176
+ ring.fromBytesBe(value, secondBytes);
177
+ ring.fromBytesBe(factor, second.prime);
178
+ ring.fromBytesBe(term, bytesOf_(first.ring, difference, scratch));
179
+ ring.multiply(term, term, factor);
180
+ ring.add(value, value, term);
181
+ for (let index = 2; index < primes.length; index++) {
182
+ const prime = primes[index];
183
+ const partial = prime.ring.create();
184
+ const primeCoefficient = prime.ring.create();
185
+ elements.push(partial, primeCoefficient);
186
+ // h = (m_i − m)·t_i mod r_i, m = m + R·h with R = r_1 ⋯ r_(i−1).
187
+ ring.toBytesBe(valueBytes, value);
188
+ prime.ring.reduceBytesBe(partial, valueBytes);
189
+ prime.ring.subtract(partial, residues[index], partial);
190
+ prime.ring.fromBytesBe(primeCoefficient, prime.coefficient);
191
+ prime.ring.multiply(partial, partial, primeCoefficient);
192
+ ring.fromBytesBe(factor, prime.productBefore);
193
+ ring.fromBytesBe(term, bytesOf_(prime.ring, partial, scratch));
194
+ ring.multiply(term, term, factor);
195
+ ring.add(value, value, term);
196
+ }
197
+ }
198
+ finally {
199
+ valueBytes.fill(0);
200
+ for (const array of [...residues, ...elements, ...scratch]) {
201
+ array.fill(0);
202
+ }
203
+ }
204
+ }
205
+ /**
206
+ * `c^(d_i + b·(r_i − 1)) mod (g·r_i)`, reduced modulo r_i, for fresh random b
207
+ * and odd g of 64 bits (g's top bit set, so the blinded modulus has a fixed
208
+ * length).
209
+ */
210
+ function exponentiateModPrime_(prime, valueBytes) {
211
+ const factor = getRandomBytes(BLINDING_BYTES);
212
+ const blindedModulus = new Uint8Array(prime.prime.length + BLINDING_BYTES);
213
+ const exponent = blindExponent_(prime.exponent, prime.primeMinusOne);
214
+ let blindedRing;
215
+ let blindedValue;
216
+ let blindedBytes;
217
+ try {
218
+ factor[0] = factor[0] | 0x80;
219
+ factor[BLINDING_BYTES - 1] = factor[BLINDING_BYTES - 1] | 1;
220
+ constantTimeUnsignedMultiply(blindedModulus, prime.prime, factor);
221
+ blindedRing = new ConstantTimeModulus(blindedModulus);
222
+ blindedValue = blindedRing.create();
223
+ blindedRing.reduceBytesBe(blindedValue, valueBytes);
224
+ blindedRing.power(blindedValue, blindedValue, exponent);
225
+ blindedBytes = new Uint8Array(blindedRing.byteLength);
226
+ blindedRing.toBytesBe(blindedBytes, blindedValue);
227
+ const residue = prime.ring.create();
228
+ prime.ring.reduceBytesBe(residue, blindedBytes);
229
+ return residue;
230
+ }
231
+ finally {
232
+ factor.fill(0);
233
+ blindedModulus.fill(0);
234
+ exponent.fill(0);
235
+ blindedValue?.fill(0);
236
+ blindedBytes?.fill(0);
237
+ blindedRing?.[Symbol.dispose]();
238
+ }
239
+ }
240
+ /** The bytes of `element`, recorded in `scratch` for wiping. */
241
+ function bytesOf_(ring, element, scratch) {
242
+ const bytes = new Uint8Array(ring.byteLength);
243
+ ring.toBytesBe(bytes, element);
244
+ scratch.push(bytes);
245
+ return bytes;
246
+ }
247
+ //# sourceMappingURL=_primitives.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_primitives.js","sourceRoot":"","sources":["../../src/key/_primitives.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EACN,mBAAmB,EACnB,uBAAuB,EACvB,8BAA8B,EAC9B,4BAA4B,GAE5B,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAIN,aAAa,GACb,MAAM,iBAAiB,CAAC;AAEzB,4EAA4E;A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,CAChB,IAAyB,EACzB,OAAuB,EACvB,OAAqB;IAErB,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;IAE9C,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IAC/B,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAEpB,OAAO,KAAK,CAAC;AACd,CAAC"}
@@ -0,0 +1,60 @@
1
+ import { type PrimeState, type PrivateKeyState } from "./_key-state.js";
2
+ import type { RsaPublicKey } from "./rsa-public-key.js";
3
+ /** A prime of a CRT key with its exponent and coefficient (RFC 8017 §3.2). */
4
+ export type CrtPrime = {
5
+ readonly prime: Uint8Array;
6
+ readonly exponent: Uint8Array;
7
+ /** Q⁻¹ mod p for the first prime, ignored for the second, t_i after. */
8
+ readonly coefficient: Uint8Array;
9
+ };
10
+ /** The secret integers of a private key, big-endian. */
11
+ export type PrivateIntegers = {
12
+ readonly privateExponent: Uint8Array;
13
+ readonly primes: readonly CrtPrime[] | undefined;
14
+ /**
15
+ * 0 when {@link deriveFromPrimes} stood in for a refused prime, so that the
16
+ * key is refused after the same work; 1 or absent otherwise.
17
+ */
18
+ readonly derivationValid?: number;
19
+ };
20
+ /** Options of the private-key import functions. */
21
+ export interface RsaPrivateKeyImportOptions {
22
+ /**
23
+ * Test each prime of a CRT key with trial division and five exhaustive
24
+ * Miller–Rabin rounds, as SP 800-56B §6.4.1.3 key-pair validation does.
25
+ * Default true. The test costs about five exponentiations modulo each prime,
26
+ * several times the consistency checks: about 80 ms for a 2048-bit key and
27
+ * half a second at 4096 bits on a current x86-64 machine, against 10 and 30
28
+ * ms without; pass false only for keys from a trusted source, such as this
29
+ * package's own exports. The consistency checks always run: they bind the
30
+ * primes to n, e and d, and every private-key operation checks its own
31
+ * result. A key of the first form (n, d) has no primes to test.
32
+ */
33
+ readonly checkPrimality?: boolean;
34
+ }
35
+ /**
36
+ * The state of the private key of `publicKey` with `integers`, after checking
37
+ * them: 0 < d < n; for a CRT key, that the primes multiply to n, each prime r
38
+ * is odd and above 3 (and, by default, probably prime), e·d_i ≡ 1 and d ≡ d_i
39
+ * modulo r − 1 with d_i < r − 1, and each coefficient is the inverse it must be
40
+ * and below its prime; without primes, that (2^e)^d ≡ 2 (mod n).
41
+ *
42
+ * @throws {RsaError} `invalidKey` when any check fails.
43
+ */
44
+ export declare function buildPrivateState(publicKey: RsaPublicKey, integers: PrivateIntegers, options: RsaPrivateKeyImportOptions): PrivateKeyState;
45
+ /** Overwrites the secrets of `primes` and disposes of their arithmetic. */
46
+ export declare function wipePrimes(primes: readonly PrimeState[]): void;
47
+ /**
48
+ * The CRT integers of a key from its primes alone (FIPS 186-5 A.1.1 3 and RFC
49
+ * 8017 §3.2): n = ∏ r_i, λ = lcm(r_i − 1), d = e⁻¹ mod λ unless given, d_i = d
50
+ * mod (r_i − 1), q⁻¹ mod p and t_i = (r_1 ⋯ r_(i−1))⁻¹ mod r_i. Constant time
51
+ * in the primes; the inverses that do not exist come out as garbage, which
52
+ * {@link buildPrivateState} then refuses. A prime that is not odd and above 3
53
+ * (0, 1 or none included) is replaced by an odd stand-in of its length, so that
54
+ * the arithmetic neither throws nor loops, and `derivationValid` is 0.
55
+ */
56
+ export declare function deriveFromPrimes(primes: readonly Uint8Array[], publicExponent: Uint8Array, privateExponent: Uint8Array | undefined): {
57
+ readonly modulus: Uint8Array<ArrayBuffer>;
58
+ readonly integers: PrivateIntegers;
59
+ };
60
+ //# sourceMappingURL=_validate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_validate.d.ts","sourceRoot":"","sources":["../../src/key/_validate.ts"],"names":[],"mappings":"AAYA,OAAO,EACN,KAAK,UAAU,EACf,KAAK,eAAe,EAEpB,MAAM,iBAAiB,CAAC;AAEzB,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAaxD,8EAA8E;AAC9E,MAAM,MAAM,QAAQ,GAAG;IACtB,QAAQ,CAAC,KAAK,EAAE,UAAU,CAAC;IAC3B,QAAQ,CAAC,QAAQ,EAAE,UAAU,CAAC;IAC9B,wEAAwE;IACxE,QAAQ,CAAC,WAAW,EAAE,UAAU,CAAC;CACjC,CAAC;AAEF,wDAAwD;AACxD,MAAM,MAAM,eAAe,GAAG;IAC7B,QAAQ,CAAC,eAAe,EAAE,UAAU,CAAC;IACrC,QAAQ,CAAC,MAAM,EAAE,SAAS,QAAQ,EAAE,GAAG,SAAS,CAAC;IACjD;;;OAGG;IACH,QAAQ,CAAC,eAAe,CAAC,EAAE,MAAM,CAAC;CAClC,CAAC;AAEF,mDAAmD;AACnD,MAAM,WAAW,0BAA0B;IAC1C;;;;;;;;;;OAUG;IACH,QAAQ,CAAC,cAAc,CAAC,EAAE,OAAO,CAAC;CAClC;AAED;;;;;;;;GAQG;AACH,wBAAgB,iBAAiB,CAChC,SAAS,EAAE,YAAY,EACvB,QAAQ,EAAE,eAAe,EACzB,OAAO,EAAE,0BAA0B,GACjC,eAAe,CAoEjB;AAED,2EAA2E;AAC3E,wBAAgB,UAAU,CAAC,MAAM,EAAE,SAAS,UAAU,EAAE,GAAG,IAAI,CAc9D;AAED;;;;;;;;GAQG;AACH,wBAAgB,gBAAgB,CAC/B,MAAM,EAAE,SAAS,UAAU,EAAE,EAC7B,cAAc,EAAE,UAAU,EAC1B,eAAe,EAAE,UAAU,GAAG,SAAS,GACrC;IACF,QAAQ,CAAC,OAAO,EAAE,UAAU,CAAC,WAAW,CAAC,CAAC;IAC1C,QAAQ,CAAC,QAAQ,EAAE,eAAe,CAAC;CACnC,CA2DA"}
@@ -0,0 +1,328 @@
1
+ import { ConstantTimeModulus, constantTimeUnsignedCompare, constantTimeUnsignedDivide, constantTimeUnsignedGcd, constantTimeUnsignedModInverse, constantTimeUnsignedMultiply, constantTimeUnsignedSubtract, } from "@ac-kit/crypto-safe";
2
+ import { leftPad, stripLeadingZeros } from "../_bytes.js";
3
+ import { RsaError } from "../rsa-error.js";
4
+ import { publicStateOf, } from "./_key-state.js";
5
+ import { passesMillerRabin, passesTrialDivision } from "./_primality.js";
6
+ /**
7
+ * Checks and assembles private-key state. Every check on a secret value runs in
8
+ * constant time and folds into one flag, so a refused key reveals only that it
9
+ * was refused, not which rule it broke.
10
+ */
11
+ /** SP 800-56B §6.4.1.3 key-pair validation: Miller–Rabin rounds per prime. */
12
+ const PRIMALITY_ROUNDS_ = 5;
13
+ const THREE_ = Uint8Array.of(3);
14
+ const FIVE_ = Uint8Array.of(5);
15
+ /**
16
+ * The state of the private key of `publicKey` with `integers`, after checking
17
+ * them: 0 < d < n; for a CRT key, that the primes multiply to n, each prime r
18
+ * is odd and above 3 (and, by default, probably prime), e·d_i ≡ 1 and d ≡ d_i
19
+ * modulo r − 1 with d_i < r − 1, and each coefficient is the inverse it must be
20
+ * and below its prime; without primes, that (2^e)^d ≡ 2 (mod n).
21
+ *
22
+ * @throws {RsaError} `invalidKey` when any check fails.
23
+ */
24
+ export function buildPrivateState(publicKey, integers, options) {
25
+ const publicState = publicStateOf(publicKey);
26
+ const { modulus, publicExponent } = publicState;
27
+ const length = modulus.length;
28
+ const privateExponent = leftPad(integers.privateExponent, length);
29
+ let valid = (integers.derivationValid ?? 1) &
30
+ fits_(integers.privateExponent, length) &
31
+ (1 - isZero_(privateExponent)) &
32
+ lessThan_(privateExponent, modulus);
33
+ let primes;
34
+ let multipleOfLambda = new Uint8Array(0);
35
+ try {
36
+ if (integers.primes === undefined) {
37
+ valid &= checkWithoutPrimes_(publicState.ring, publicExponent, privateExponent);
38
+ multipleOfLambda = new Uint8Array(length + publicExponent.length);
39
+ constantTimeUnsignedMultiply(multipleOfLambda, publicExponent, privateExponent);
40
+ constantTimeUnsignedSubtract(multipleOfLambda, multipleOfLambda, Uint8Array.of(1));
41
+ }
42
+ else {
43
+ const checked = checkPrimes_(integers.primes, modulus, publicExponent, privateExponent, options);
44
+ valid &= checked.valid;
45
+ primes = checked.primes;
46
+ }
47
+ if (valid !== 1) {
48
+ throw new RsaError("invalidKey", "The RSA private-key components are inconsistent or out of range");
49
+ }
50
+ return {
51
+ publicKey,
52
+ privateExponent,
53
+ primes,
54
+ multipleOfLambda,
55
+ disposed: false,
56
+ };
57
+ }
58
+ catch (error) {
59
+ privateExponent.fill(0);
60
+ multipleOfLambda.fill(0);
61
+ if (primes !== undefined) {
62
+ wipePrimes(primes);
63
+ }
64
+ throw error;
65
+ }
66
+ }
67
+ /** Overwrites the secrets of `primes` and disposes of their arithmetic. */
68
+ export function wipePrimes(primes) {
69
+ for (const prime of primes) {
70
+ for (const bytes of [
71
+ prime.prime,
72
+ prime.primeMinusOne,
73
+ prime.exponent,
74
+ prime.coefficient,
75
+ prime.productBefore,
76
+ ]) {
77
+ bytes.fill(0);
78
+ }
79
+ prime.ring[Symbol.dispose]();
80
+ }
81
+ }
82
+ /**
83
+ * The CRT integers of a key from its primes alone (FIPS 186-5 A.1.1 3 and RFC
84
+ * 8017 §3.2): n = ∏ r_i, λ = lcm(r_i − 1), d = e⁻¹ mod λ unless given, d_i = d
85
+ * mod (r_i − 1), q⁻¹ mod p and t_i = (r_1 ⋯ r_(i−1))⁻¹ mod r_i. Constant time
86
+ * in the primes; the inverses that do not exist come out as garbage, which
87
+ * {@link buildPrivateState} then refuses. A prime that is not odd and above 3
88
+ * (0, 1 or none included) is replaced by an odd stand-in of its length, so that
89
+ * the arithmetic neither throws nor loops, and `derivationValid` is 0.
90
+ */
91
+ export function deriveFromPrimes(primes, publicExponent, privateExponent) {
92
+ let derivationValid = 1;
93
+ const minimal = primes.map((prime) => {
94
+ const shape = oddAboveThree_(stripLeadingZeros(prime));
95
+ derivationValid &= shape.valid;
96
+ return shape.candidate;
97
+ });
98
+ const products = productsOf_(minimal);
99
+ const modulus = stripLeadingZeros(products.at(-1)).slice();
100
+ const length = modulus.length;
101
+ const lambda = lambdaOf_(minimal);
102
+ const scratch = [lambda, ...products];
103
+ try {
104
+ let d;
105
+ if (privateExponent === undefined) {
106
+ d = new Uint8Array(lambda.length);
107
+ constantTimeUnsignedModInverse(d, publicExponent, lambda);
108
+ }
109
+ else {
110
+ d = leftPad(privateExponent, Math.max(privateExponent.length, 1));
111
+ }
112
+ const crt = minimal.map((prime, index) => {
113
+ const minusOne = minusOneOf_(prime);
114
+ const exponent = new Uint8Array(prime.length);
115
+ const coefficient = new Uint8Array(prime.length);
116
+ scratch.push(minusOne);
117
+ constantTimeUnsignedDivide(new Uint8Array(0), exponent, d, minusOne);
118
+ if (index === 0) {
119
+ constantTimeUnsignedModInverse(coefficient, minimal[1], prime);
120
+ }
121
+ else if (index >= 2) {
122
+ constantTimeUnsignedModInverse(coefficient, products[index - 1], prime);
123
+ }
124
+ return { prime, exponent, coefficient };
125
+ });
126
+ return {
127
+ modulus,
128
+ integers: {
129
+ privateExponent: leftPad(d, Math.max(length, d.length)),
130
+ primes: crt,
131
+ derivationValid,
132
+ },
133
+ };
134
+ }
135
+ finally {
136
+ for (const bytes of scratch) {
137
+ bytes.fill(0);
138
+ }
139
+ }
140
+ }
141
+ /** λ = lcm(r_1 − 1, …, r_u − 1), as lcm(a, b) = (a / gcd(a, b)) · b. */
142
+ function lambdaOf_(primes) {
143
+ let lambda = minusOneOf_(primes[0]);
144
+ for (const prime of primes.slice(1)) {
145
+ const minusOne = minusOneOf_(prime);
146
+ const gcd = new Uint8Array(minusOne.length);
147
+ const quotient = new Uint8Array(lambda.length);
148
+ const next = new Uint8Array(lambda.length + minusOne.length);
149
+ constantTimeUnsignedGcd(gcd, lambda, minusOne);
150
+ constantTimeUnsignedDivide(quotient, new Uint8Array(0), lambda, gcd);
151
+ constantTimeUnsignedMultiply(next, quotient, minusOne);
152
+ for (const bytes of [minusOne, gcd, quotient, lambda]) {
153
+ bytes.fill(0);
154
+ }
155
+ lambda = next;
156
+ }
157
+ return lambda;
158
+ }
159
+ /** R_1, r_1·r_2, …, ∏ r_i, each over the sum of the factors' lengths. */
160
+ function productsOf_(primes) {
161
+ const products = [primes[0].slice()];
162
+ for (const prime of primes.slice(1)) {
163
+ const previous = products.at(-1);
164
+ const product = new Uint8Array(previous.length + prime.length);
165
+ constantTimeUnsignedMultiply(product, previous, prime);
166
+ products.push(product);
167
+ }
168
+ return products;
169
+ }
170
+ function checkPrimes_(crt, modulus, publicExponent, privateExponent, options) {
171
+ const length = modulus.length;
172
+ const one = Uint8Array.of(1);
173
+ const scratch = [];
174
+ const built = [];
175
+ let valid = 1;
176
+ if (crt.length < 2) {
177
+ throw new RsaError("invalidKey", "An RSA key in CRT form needs two primes at least");
178
+ }
179
+ try {
180
+ const primes = crt.map((entry) => {
181
+ const prime = stripLeadingZeros(entry.prime).slice();
182
+ scratch.push(prime);
183
+ return prime;
184
+ });
185
+ const products = productsOf_(primes);
186
+ scratch.push(...products);
187
+ valid &= isEqualPadded_(products.at(-1), modulus);
188
+ for (const [index, entry] of crt.entries()) {
189
+ const prime = primes[index];
190
+ const primeLength = prime.length;
191
+ // r is odd and above 3; a refused r gives way to an odd stand-in
192
+ // above 3 for the ring and the primality test, so that the work stays
193
+ // the same and nothing throws or loops.
194
+ const shape = oddAboveThree_(prime);
195
+ scratch.push(shape.candidate);
196
+ valid &= shape.valid & lessThan_(prime, modulus);
197
+ valid &=
198
+ fits_(entry.exponent, primeLength) &
199
+ fits_(entry.coefficient, primeLength);
200
+ const minusOne = minusOneOf_(prime);
201
+ const exponent = leftPad(entry.exponent, primeLength);
202
+ const coefficient = leftPad(entry.coefficient, primeLength);
203
+ const product = new Uint8Array(publicExponent.length + primeLength);
204
+ const remainder = new Uint8Array(primeLength);
205
+ scratch.push(minusOne, product, remainder);
206
+ // d_i < r − 1, e·d_i ≡ 1 and d ≡ d_i (mod r − 1).
207
+ valid &= lessThan_(exponent, minusOne);
208
+ constantTimeUnsignedMultiply(product, publicExponent, exponent);
209
+ valid &= remainderIs_(product, minusOne, one, remainder);
210
+ valid &= remainderIs_(privateExponent, minusOne, exponent, remainder);
211
+ if (index !== 1) {
212
+ // q⁻¹ mod p, or (r_1 ⋯ r_(i−1))⁻¹ mod r_i.
213
+ const factor = index === 0 ? primes[1] : products[index - 1];
214
+ const coefficientProduct = new Uint8Array(factor.length + primeLength);
215
+ scratch.push(coefficientProduct);
216
+ valid &= lessThan_(coefficient, prime);
217
+ constantTimeUnsignedMultiply(coefficientProduct, coefficient, factor);
218
+ valid &= remainderIs_(coefficientProduct, prime, one, remainder);
219
+ }
220
+ if (options.checkPrimality !== false) {
221
+ valid &=
222
+ passesTrialDivision(shape.candidate, true) &
223
+ passesMillerRabin(shape.candidate, PRIMALITY_ROUNDS_, true);
224
+ }
225
+ built.push({
226
+ prime,
227
+ primeMinusOne: minusOne.slice(),
228
+ exponent,
229
+ coefficient: index === 1 ? new Uint8Array(0) : coefficient,
230
+ productBefore: index >= 2
231
+ ? leftPad(products[index - 1], length)
232
+ : new Uint8Array(0),
233
+ ring: new ConstantTimeModulus(shape.candidate),
234
+ });
235
+ }
236
+ // The prime arrays now belong to the built state.
237
+ scratch.splice(0, primes.length);
238
+ return { valid, primes: built };
239
+ }
240
+ catch (error) {
241
+ wipePrimes(built);
242
+ throw error;
243
+ }
244
+ finally {
245
+ for (const bytes of scratch) {
246
+ bytes.fill(0);
247
+ }
248
+ }
249
+ }
250
+ /** (2^e)^d ≡ 2 (mod n), for a key with no primes: a probabilistic check. */
251
+ function checkWithoutPrimes_(ring, publicExponent, privateExponent) {
252
+ const two = ring.create();
253
+ const value = ring.create();
254
+ try {
255
+ ring.fromBytesBe(two, Uint8Array.of(2));
256
+ ring.power(value, two, publicExponent);
257
+ ring.power(value, value, privateExponent);
258
+ return ring.isEqual(value, two);
259
+ }
260
+ finally {
261
+ two.fill(0);
262
+ value.fill(0);
263
+ }
264
+ }
265
+ /**
266
+ * Whether the minimal `prime` is odd and above 3, and an odd stand-in above 3
267
+ * of its length: `prime` with its low bit set, or 5 for a one-byte prime that
268
+ * would still be 3 or less (a minimal value of two bytes or more is above 3).
269
+ * Constant time in `prime`; its length is public.
270
+ */
271
+ function oddAboveThree_(prime) {
272
+ const valid = prime.at(-1) & 1 & lessThan_(THREE_, prime);
273
+ const candidate = prime.slice();
274
+ candidate[candidate.length - 1] = candidate.at(-1) | 1;
275
+ selectBytes_(candidate, leftPad(FIVE_, candidate.length), 1 - lessThan_(THREE_, candidate));
276
+ return { valid, candidate };
277
+ }
278
+ /** R − 1 for an odd r: its lowest bit cleared. */
279
+ function minusOneOf_(prime) {
280
+ const minusOne = prime.slice();
281
+ minusOne[minusOne.length - 1] = minusOne.at(-1) & 0xfe;
282
+ return minusOne;
283
+ }
284
+ /** 1 when `value mod modulus = expected`, else 0; `remainder` is scratch. */
285
+ function remainderIs_(value, modulus, expected, remainder) {
286
+ // A zero modulus (from a refused prime) must not throw: use 1 instead.
287
+ const divisor = modulus.slice();
288
+ divisor[divisor.length - 1] = divisor.at(-1) | isZero_(modulus);
289
+ try {
290
+ constantTimeUnsignedDivide(new Uint8Array(0), remainder, value, divisor);
291
+ return isEqualPadded_(remainder, expected);
292
+ }
293
+ finally {
294
+ divisor.fill(0);
295
+ }
296
+ }
297
+ /** 1 when `a < b`, else 0. */
298
+ function lessThan_(a, b) {
299
+ return (constantTimeUnsignedCompare(a, b) >>> 31) & 1;
300
+ }
301
+ /** 1 when `a` is 0, else 0. */
302
+ function isZero_(a) {
303
+ let accumulator = 0;
304
+ for (const byte of a) {
305
+ accumulator |= byte;
306
+ }
307
+ return (accumulator - 1) >>> 31;
308
+ }
309
+ /** 1 when `a` and `b` have the same value, whatever their lengths. */
310
+ function isEqualPadded_(a, b) {
311
+ return 1 - (constantTimeUnsignedCompare(a, b) & 1);
312
+ }
313
+ /** 1 when the value of `bytes` fits in `length` bytes. */
314
+ function fits_(bytes, length) {
315
+ let excess = 0;
316
+ for (let index = 0; index < bytes.length - length; index++) {
317
+ excess |= bytes[index];
318
+ }
319
+ return (excess - 1) >>> 31;
320
+ }
321
+ /** `out = flag ? source : out` over `out.length` bytes (`source` as long). */
322
+ function selectBytes_(out, source, flag) {
323
+ const mask = -flag & 0xff;
324
+ for (let index = 0; index < out.length; index++) {
325
+ out[index] = out[index] ^ (mask & (out[index] ^ source[index]));
326
+ }
327
+ }
328
+ //# sourceMappingURL=_validate.js.map