1 // SPDX-License-Identifier: GPL-2.0+ and MIT
3 * RSA library - generate parameters for a public key
5 * Copyright (c) 2019 Linaro Limited
6 * Author: AKASHI Takahiro
8 * Big number routines in this file come from BearSSL:
9 * Copyright (c) 2016 Thomas Pornin <pornin@bolet.org>
15 #include <asm/byteorder.h>
16 #include <crypto/internal/rsa.h>
17 #include <u-boot/rsa-mod-exp.h>
20 * br_dec16be() - Convert 16-bit big-endian integer to native
21 * @src: Pointer to data
22 * Return: Native-endian integer
24 static unsigned br_dec16be(const void *src)
26 return be16_to_cpup(src);
30 * br_dec32be() - Convert 32-bit big-endian integer to native
31 * @src: Pointer to data
32 * Return: Native-endian integer
34 static uint32_t br_dec32be(const void *src)
36 return be32_to_cpup(src);
40 * br_enc32be() - Convert native 32-bit integer to big-endian
41 * @dst: Pointer to buffer to store big-endian integer in
42 * @x: Native 32-bit integer
44 static void br_enc32be(void *dst, uint32_t x)
49 memcpy(dst, &tmp, sizeof(tmp));
52 /* from BearSSL's src/inner.h */
57 static uint32_t NOT(uint32_t ctl)
63 * Multiplexer: returns x if ctl == 1, y if ctl == 0.
65 static uint32_t MUX(uint32_t ctl, uint32_t x, uint32_t y)
67 return y ^ (-ctl & (x ^ y));
71 * Equality check: returns 1 if x == y, 0 otherwise.
73 static uint32_t EQ(uint32_t x, uint32_t y)
78 return NOT((q | -q) >> 31);
82 * Inequality check: returns 1 if x != y, 0 otherwise.
84 static uint32_t NEQ(uint32_t x, uint32_t y)
89 return (q | -q) >> 31;
93 * Comparison: returns 1 if x > y, 0 otherwise.
95 static uint32_t GT(uint32_t x, uint32_t y)
98 * If both x < 2^31 and y < 2^31, then y-x will have its high
99 * bit set if x > y, cleared otherwise.
101 * If either x >= 2^31 or y >= 2^31 (but not both), then the
102 * result is the high bit of x.
104 * If both x >= 2^31 and y >= 2^31, then we can virtually
105 * subtract 2^31 from both, and we are back to the first case.
106 * Since (y-2^31)-(x-2^31) = y-x, the subtraction is already
112 return (z ^ ((x ^ y) & (x ^ z))) >> 31;
116 * Compute the bit length of a 32-bit integer. Returned value is between 0
117 * and 32 (inclusive).
119 static uint32_t BIT_LENGTH(uint32_t x)
124 c = GT(x, 0xFFFF); x = MUX(c, x >> 16, x); k += c << 4;
125 c = GT(x, 0x00FF); x = MUX(c, x >> 8, x); k += c << 3;
126 c = GT(x, 0x000F); x = MUX(c, x >> 4, x); k += c << 2;
127 c = GT(x, 0x0003); x = MUX(c, x >> 2, x); k += c << 1;
132 #define GE(x, y) NOT(GT(y, x))
133 #define LT(x, y) GT(y, x)
134 #define MUL(x, y) ((uint64_t)(x) * (uint64_t)(y))
140 * The 'i32' functions implement computations on big integers using
141 * an internal representation as an array of 32-bit integers. For
143 * -- x[0] contains the "announced bit length" of the integer
144 * -- x[1], x[2]... contain the value in little-endian order (x[1]
145 * contains the least significant 32 bits)
147 * Multiplications rely on the elementary 32x32->64 multiplication.
149 * The announced bit length specifies the number of bits that are
150 * significant in the subsequent 32-bit words. Unused bits in the
151 * last (most significant) word are set to 0; subsequent words are
152 * uninitialized and need not exist at all.
154 * The execution time and memory access patterns of all computations
155 * depend on the announced bit length, but not on the actual word
156 * values. For modular integers, the announced bit length of any integer
157 * modulo n is equal to the actual bit length of n; thus, computations
158 * on modular integers are "constant-time" (only the modulus length may
163 * Extract one word from an integer. The offset is counted in bits.
164 * The word MUST entirely fit within the word elements corresponding
165 * to the announced bit length of a[].
167 static uint32_t br_i32_word(const uint32_t *a, uint32_t off)
172 u = (size_t)(off >> 5) + 1;
173 j = (unsigned)off & 31;
177 return (a[u] >> j) | (a[u + 1] << (32 - j));
181 /* from BearSSL's src/int/i32_bitlen.c */
184 * Compute the actual bit length of an integer. The argument x should
185 * point to the first (least significant) value word of the integer.
186 * The len 'xlen' contains the number of 32-bit words to access.
188 * CT: value or length of x does not leak.
190 static uint32_t br_i32_bit_length(uint32_t *x, size_t xlen)
196 while (xlen -- > 0) {
202 twk = MUX(c, (uint32_t)xlen, twk);
204 return (twk << 5) + BIT_LENGTH(tw);
207 /* from BearSSL's src/int/i32_decode.c */
210 * Decode an integer from its big-endian unsigned representation. The
211 * "true" bit length of the integer is computed, but all words of x[]
212 * corresponding to the full 'len' bytes of the source are set.
214 * CT: value or length of x does not leak.
216 static void br_i32_decode(uint32_t *x, const void *src, size_t len)
218 const unsigned char *buf;
238 w = ((uint32_t)buf[0] << 16)
239 | br_dec16be(buf + 1);
246 x[v ++] = br_dec32be(buf + u);
249 x[0] = br_i32_bit_length(x + 1, v - 1);
252 /* from BearSSL's src/int/i32_encode.c */
255 * Encode an integer into its big-endian unsigned representation. The
256 * output length in bytes is provided (parameter 'len'); if the length
257 * is too short then the integer is appropriately truncated; if it is
258 * too long then the extra bytes are set to 0.
260 static void br_i32_encode(void *dst, size_t len, const uint32_t *x)
268 * Compute the announced size of x in bytes; extra bytes are
278 * Now we use k as index within x[]. That index starts at 1;
279 * we initialize it to the topmost complete word, and process
280 * any remaining incomplete word.
285 *buf ++ = x[k] >> 16;
296 * Encode all complete words.
299 br_enc32be(buf, x[k]);
305 /* from BearSSL's src/int/i32_ninv32.c */
308 * Compute -(1/x) mod 2^32. If x is even, then this function returns 0.
310 static uint32_t br_i32_ninv32(uint32_t x)
319 return MUX(x & 1, -y, 0);
322 /* from BearSSL's src/int/i32_add.c */
325 * Add b[] to a[] and return the carry (0 or 1). If ctl is 0, then a[]
326 * is unmodified, but the carry is still computed and returned. The
327 * arrays a[] and b[] MUST have the same announced bit length.
329 * a[] and b[] MAY be the same array, but partial overlap is not allowed.
331 static uint32_t br_i32_add(uint32_t *a, const uint32_t *b, uint32_t ctl)
337 m = (a[0] + 63) >> 5;
338 for (u = 1; u < m; u ++) {
339 uint32_t aw, bw, naw;
346 * Carry is 1 if naw < aw. Carry is also 1 if naw == aw
347 * AND the carry was already 1.
349 cc = (cc & EQ(naw, aw)) | LT(naw, aw);
350 a[u] = MUX(ctl, naw, aw);
355 /* from BearSSL's src/int/i32_sub.c */
358 * Subtract b[] from a[] and return the carry (0 or 1). If ctl is 0,
359 * then a[] is unmodified, but the carry is still computed and returned.
360 * The arrays a[] and b[] MUST have the same announced bit length.
362 * a[] and b[] MAY be the same array, but partial overlap is not allowed.
364 static uint32_t br_i32_sub(uint32_t *a, const uint32_t *b, uint32_t ctl)
370 m = (a[0] + 63) >> 5;
371 for (u = 1; u < m; u ++) {
372 uint32_t aw, bw, naw;
379 * Carry is 1 if naw > aw. Carry is 1 also if naw == aw
380 * AND the carry was already 1.
382 cc = (cc & EQ(naw, aw)) | GT(naw, aw);
383 a[u] = MUX(ctl, naw, aw);
388 /* from BearSSL's src/int/i32_div32.c */
391 * Constant-time division. The dividend hi:lo is divided by the
392 * divisor d; the quotient is returned and the remainder is written
393 * in *r. If hi == d, then the quotient does not fit on 32 bits;
394 * returned value is thus truncated. If hi > d, returned values are
397 static uint32_t br_divrem(uint32_t hi, uint32_t lo, uint32_t d, uint32_t *r)
399 /* TODO: optimize this */
407 for (k = 31; k > 0; k --) {
409 uint32_t w, ctl, hi2, lo2;
412 w = (hi << j) | (lo >> k);
413 ctl = GE(w, d) | (hi >> k);
416 hi = MUX(ctl, hi2, hi);
417 lo = MUX(ctl, lo2, lo);
422 *r = MUX(cf, lo - d, lo);
427 * Wrapper for br_divrem(); the remainder is returned, and the quotient
430 static uint32_t br_rem(uint32_t hi, uint32_t lo, uint32_t d)
434 br_divrem(hi, lo, d, &r);
439 * Wrapper for br_divrem(); the quotient is returned, and the remainder
442 static uint32_t br_div(uint32_t hi, uint32_t lo, uint32_t d)
446 return br_divrem(hi, lo, d, &r);
449 /* from BearSSL's src/int/i32_muladd.c */
452 * Multiply x[] by 2^32 and then add integer z, modulo m[]. This
453 * function assumes that x[] and m[] have the same announced bit
454 * length, and the announced bit length of m[] matches its true
457 * x[] and m[] MUST be distinct arrays.
459 * CT: only the common announced bit length of x and m leaks, not
460 * the values of x, z or m.
462 static void br_i32_muladd_small(uint32_t *x, uint32_t z, const uint32_t *m)
466 uint32_t a0, a1, b0, hi, g, q, tb;
467 uint32_t chf, clow, under, over;
471 * We can test on the modulus bit length since we accept to
478 if (m_bitlen <= 32) {
479 x[1] = br_rem(x[1], z, m[1]);
482 mlen = (m_bitlen + 31) >> 5;
485 * Principle: we estimate the quotient (x*2^32+z)/m by
486 * doing a 64/32 division with the high words.
490 * a = (w*a0 + a1) * w^N + a2
499 * I.e. the two top words of a are a0:a1, the top word of b is
500 * b0, we ensured that b0 is "full" (high bit set), and a is
501 * such that the quotient q = a/b fits on one word (0 <= q < w).
503 * If a = b*q + r (with 0 <= r < q), we can estimate q by
504 * doing an Euclidean division on the top words:
505 * a0*w+a1 = b0*u + v (with 0 <= v < w)
506 * Then the following holds:
510 a0 = br_i32_word(x, m_bitlen - 32);
512 memmove(x + 2, x + 1, (mlen - 1) * sizeof *x);
514 a1 = br_i32_word(x, m_bitlen - 32);
515 b0 = br_i32_word(m, m_bitlen - 32);
518 * We estimate a divisor q. If the quotient returned by br_div()
520 * -- If a0 == b0 then g == 0; we want q = 0xFFFFFFFF.
522 * -- if g == 0 then we set q = 0;
523 * -- otherwise, we set q = g - 1.
524 * The properties described above then ensure that the true
525 * quotient is q-1, q or q+1.
527 g = br_div(a0, a1, b0);
528 q = MUX(EQ(a0, b0), 0xFFFFFFFF, MUX(EQ(g, 0), 0, g - 1));
531 * We subtract q*m from x (with the extra high word of value 'hi').
532 * Since q may be off by 1 (in either direction), we may have to
533 * add or subtract m afterwards.
535 * The 'tb' flag will be true (1) at the end of the loop if the
536 * result is greater than or equal to the modulus (not counting
537 * 'hi' or the carry).
541 for (u = 1; u <= mlen; u ++) {
542 uint32_t mw, zw, xw, nxw;
546 zl = MUL(mw, q) + cc;
547 cc = (uint32_t)(zl >> 32);
551 cc += (uint64_t)GT(nxw, xw);
553 tb = MUX(EQ(nxw, mw), tb, GT(nxw, mw));
557 * If we underestimated q, then either cc < hi (one extra bit
558 * beyond the top array word), or cc == hi and tb is true (no
559 * extra bit, but the result is not lower than the modulus). In
560 * these cases we must subtract m once.
562 * Otherwise, we may have overestimated, which will show as
563 * cc > hi (thus a negative result). Correction is adding m once.
565 chf = (uint32_t)(cc >> 32);
567 over = chf | GT(clow, hi);
568 under = ~over & (tb | (~chf & LT(clow, hi)));
569 br_i32_add(x, m, over);
570 br_i32_sub(x, m, under);
573 /* from BearSSL's src/int/i32_reduce.c */
576 * Reduce an integer (a[]) modulo another (m[]). The result is written
577 * in x[] and its announced bit length is set to be equal to that of m[].
579 * x[] MUST be distinct from a[] and m[].
581 * CT: only announced bit lengths leak, not values of x, a or m.
583 static void br_i32_reduce(uint32_t *x, const uint32_t *a, const uint32_t *m)
585 uint32_t m_bitlen, a_bitlen;
586 size_t mlen, alen, u;
589 mlen = (m_bitlen + 31) >> 5;
597 * If the source is shorter, then simply copy all words from a[]
598 * and zero out the upper words.
601 alen = (a_bitlen + 31) >> 5;
602 if (a_bitlen < m_bitlen) {
603 memcpy(x + 1, a + 1, alen * sizeof *a);
604 for (u = alen; u < mlen; u ++) {
611 * The source length is at least equal to that of the modulus.
612 * We must thus copy N-1 words, and input the remaining words
615 memcpy(x + 1, a + 2 + (alen - mlen), (mlen - 1) * sizeof *a);
617 for (u = 1 + alen - mlen; u > 0; u --) {
618 br_i32_muladd_small(x, a[u], m);
623 * rsa_free_key_prop() - Free key properties
624 * @prop: Pointer to struct key_prop
626 * This function frees all the memories allocated by rsa_gen_key_prop().
628 void rsa_free_key_prop(struct key_prop *prop)
633 free((void *)prop->modulus);
634 free((void *)prop->public_exponent);
635 free((void *)prop->rr);
641 * rsa_gen_key_prop() - Generate key properties of RSA public key
642 * @key: Specifies key data in DER format
643 * @keylen: Length of @key
644 * @prop: Generated key property
646 * This function takes a blob of encoded RSA public key data in DER
647 * format, parse it and generate all the relevant properties
648 * in key_prop structure.
649 * Return a pointer to struct key_prop in @prop on success.
651 * Return: 0 on success, negative on error
653 int rsa_gen_key_prop(const void *key, uint32_t keylen, struct key_prop **prop)
655 struct rsa_key rsa_key;
656 uint32_t *n = NULL, *rr = NULL, *rrtmp = NULL;
657 const int max_rsa_size = 4096;
660 *prop = calloc(sizeof(**prop), 1);
661 n = calloc(sizeof(uint32_t), 1 + (max_rsa_size >> 5));
662 rr = calloc(sizeof(uint32_t), 1 + (max_rsa_size >> 5));
663 rrtmp = calloc(sizeof(uint32_t), 1 + (max_rsa_size >> 5));
664 if (!(*prop) || !n || !rr || !rrtmp) {
669 ret = rsa_parse_pub_key(&rsa_key, key, keylen);
674 /* removing leading 0's */
675 for (i = 0; i < rsa_key.n_sz && !rsa_key.n[i]; i++)
677 (*prop)->num_bits = (rsa_key.n_sz - i) * 8;
678 (*prop)->modulus = malloc(rsa_key.n_sz - i);
679 if (!(*prop)->modulus) {
683 memcpy((void *)(*prop)->modulus, &rsa_key.n[i], rsa_key.n_sz - i);
686 (*prop)->public_exponent = calloc(1, sizeof(uint64_t));
687 if (!(*prop)->public_exponent) {
691 memcpy((void *)(*prop)->public_exponent + sizeof(uint64_t)
693 rsa_key.e, rsa_key.e_sz);
694 (*prop)->exp_len = rsa_key.e_sz;
697 br_i32_decode(n, &rsa_key.n[i], rsa_key.n_sz - i);
698 (*prop)->n0inv = br_i32_ninv32(n[1]);
700 /* R^2 mod n; R = 2^(num_bits) */
701 rlen = (*prop)->num_bits * 2; /* #bits of R^2 = (2^num_bits)^2 */
703 *(uint8_t *)&rr[0] = (1 << (rlen % 8));
704 for (i = 1; i < (((rlen + 31) >> 5) + 1); i++)
706 br_i32_decode(rrtmp, rr, ((rlen + 7) >> 3) + 1);
707 br_i32_reduce(rr, rrtmp, n);
709 rlen = ((*prop)->num_bits + 7) >> 3; /* #bytes of R^2 mod n */
710 (*prop)->rr = malloc(rlen);
715 br_i32_encode((void *)(*prop)->rr, rlen, rr);
723 rsa_free_key_prop(*prop);