1 // SPDX-License-Identifier: GPL-2.0+
3 * Copyright (c) 2020, Alexandru Gagniuc <mr.nuke.me@gmail.com>
4 * Copyright (c) 2013, Google Inc.
8 #include <u-boot/fdt-libcrypto.h>
10 int fdt_add_bignum(void *blob, int noffset, const char *prop_name,
11 BIGNUM *num, int num_bits)
13 int nwords = num_bits / 32;
16 BIGNUM *tmp, *big2, *big32, *big2_32;
26 * Note: This code assumes that all of the above succeed, or all fail.
27 * In practice memory allocations generally do not fail (unless the
28 * process is killed), so it does not seem worth handling each of these
29 * as a separate case. Technicaly this could leak memory on failure,
30 * but a) it won't happen in practice, and b) it doesn't matter as we
31 * will immediately exit with a failure code.
33 if (!tmp || !big2 || !big32 || !big2_32) {
34 fprintf(stderr, "Out of memory (bignum)\n");
39 fprintf(stderr, "Out of memory (bignum context)\n");
42 BN_set_word(big2, 2L);
43 BN_set_word(big32, 32L);
44 BN_exp(big2_32, big2, big32, ctx); /* B = 2^32 */
46 size = nwords * sizeof(uint32_t);
49 fprintf(stderr, "Out of memory (%d bytes)\n", size);
53 /* Write out modulus as big endian array of integers */
54 for (ptr = buf + nwords - 1; ptr >= buf; ptr--) {
55 BN_mod(tmp, num, big2_32, ctx); /* n = N mod B */
56 *ptr = cpu_to_fdt32(BN_get_word(tmp));
57 BN_rshift(num, num, 32); /* N = N/B */
61 * We try signing with successively increasing size values, so this
62 * might fail several times
64 ret = fdt_setprop(blob, noffset, prop_name, buf, size);
71 return ret ? -FDT_ERR_NOSPACE : 0;