1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
4 * This package is an SSL implementation written
5 * by Eric Young (eay@cryptsoft.com).
6 * The implementation was written so as to conform with Netscapes SSL.
8 * This library is free for commercial and non-commercial use as long as
9 * the following conditions are aheared to. The following conditions
10 * apply to all code found in this distribution, be it the RC4, RSA,
11 * lhash, DES, etc., code; not just the SSL code. The SSL documentation
12 * included with this distribution is covered by the same copyright terms
13 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15 * Copyright remains Eric Young's, and as such any Copyright notices in
16 * the code are not to be removed.
17 * If this package is used in a product, Eric Young should be given attribution
18 * as the author of the parts of the library used.
19 * This can be in the form of a textual message at program startup or
20 * in documentation (online or textual) provided with the package.
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
25 * 1. Redistributions of source code must retain the copyright
26 * notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
30 * 3. All advertising materials mentioning features or use of this software
31 * must display the following acknowledgement:
32 * "This product includes cryptographic software written by
33 * Eric Young (eay@cryptsoft.com)"
34 * The word 'cryptographic' can be left out if the rouines from the library
35 * being used are not cryptographic related :-).
36 * 4. If you include any Windows specific code (or a derivative thereof) from
37 * the apps directory (application code) you must include an acknowledgement:
38 * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
52 * The licence and distribution terms for any publically available version or
53 * derivative of this code cannot be changed. i.e. this code cannot simply be
54 * copied and put under another distribution licence
55 * [including the GNU Public Licence.] */
57 #include <openssl/bn.h>
62 #include <openssl/bio.h>
63 #include <openssl/err.h>
64 #include <openssl/mem.h>
68 BIGNUM *BN_bin2bn(const uint8_t *in, size_t len, BIGNUM *ret) {
69 unsigned num_words, m;
86 num_words = ((len - 1) / BN_BYTES) + 1;
87 m = (len - 1) % BN_BYTES;
88 if (bn_wexpand(ret, num_words) == NULL) {
99 word = (word << 8) | *(in++);
101 ret->d[--num_words] = word;
107 /* need to call this due to clear byte at top if avoiding having the top bit
108 * set (-ve number) */
113 size_t BN_bn2bin(const BIGNUM *in, uint8_t *out) {
117 n = i = BN_num_bytes(in);
119 l = in->d[i / BN_BYTES];
120 *(out++) = (unsigned char)(l >> (8 * (i % BN_BYTES))) & 0xff;
125 /* constant_time_select_ulong returns |x| if |v| is 1 and |y| if |v| is 0. Its
126 * behavior is undefined if |v| takes any other value. */
127 static BN_ULONG constant_time_select_ulong(int v, BN_ULONG x, BN_ULONG y) {
131 return (~mask & x) | (mask & y);
134 /* constant_time_le_size_t returns 1 if |x| <= |y| and 0 otherwise. |x| and |y|
135 * must not have their MSBs set. */
136 static int constant_time_le_size_t(size_t x, size_t y) {
137 return ((x - y - 1) >> (sizeof(size_t) * 8 - 1)) & 1;
140 /* read_word_padded returns the |i|'th word of |in|, if it is not out of
141 * bounds. Otherwise, it returns 0. It does so without branches on the size of
142 * |in|, however it necessarily does not have the same memory access pattern. If
143 * the access would be out of bounds, it reads the last word of |in|. |in| must
145 static BN_ULONG read_word_padded(const BIGNUM *in, size_t i) {
146 /* Read |in->d[i]| if valid. Otherwise, read the last word. */
147 BN_ULONG l = in->d[constant_time_select_ulong(
148 constant_time_le_size_t(in->dmax, i), in->dmax - 1, i)];
150 /* Clamp to zero if above |d->top|. */
151 return constant_time_select_ulong(constant_time_le_size_t(in->top, i), 0, l);
154 int BN_bn2bin_padded(uint8_t *out, size_t len, const BIGNUM *in) {
158 /* Special case for |in| = 0. Just branch as the probability is negligible. */
159 if (BN_is_zero(in)) {
164 /* Check if the integer is too big. This case can exit early in non-constant
166 if ((size_t)in->top > (len + (BN_BYTES - 1)) / BN_BYTES) {
169 if ((len % BN_BYTES) != 0) {
170 l = read_word_padded(in, len / BN_BYTES);
171 if (l >> (8 * (len % BN_BYTES)) != 0) {
176 /* Write the bytes out one by one. Serialization is done without branching on
177 * the bits of |in| or on |in->top|, but if the routine would otherwise read
178 * out of bounds, the memory access pattern can't be fixed. However, for an
179 * RSA key of size a multiple of the word size, the probability of BN_BYTES
180 * leading zero octets is low.
182 * See Falko Stenzke, "Manger's Attack revisited", ICICS 2010. */
185 l = read_word_padded(in, i / BN_BYTES);
186 *(out++) = (uint8_t)(l >> (8 * (i % BN_BYTES))) & 0xff;
191 static const char hextable[] = "0123456789abcdef";
193 char *BN_bn2hex(const BIGNUM *bn) {
198 buf = (char *)OPENSSL_malloc(bn->top * BN_BYTES * 2 + 2);
200 OPENSSL_PUT_ERROR(BN, BN_bn2hex, ERR_R_MALLOC_FAILURE);
209 if (BN_is_zero(bn)) {
213 for (i = bn->top - 1; i >= 0; i--) {
214 for (j = BN_BITS2 - 8; j >= 0; j -= 8) {
215 /* strip leading zeros */
216 v = ((int)(bn->d[i] >> (long)j)) & 0xff;
218 *(p++) = hextable[v >> 4];
219 *(p++) = hextable[v & 0x0f];
229 /* decode_hex decodes |i| bytes of hex data from |in| and updates |bn|. */
230 static void decode_hex(BIGNUM *bn, const char *in, int i) {
234 j = i; /* least significant 'hex' */
237 m = ((BN_BYTES * 2) <= j) ? (BN_BYTES * 2) : j;
241 if ((c >= '0') && (c <= '9')) {
243 } else if ((c >= 'a') && (c <= 'f')) {
245 } else if ((c >= 'A') && (c <= 'F')) {
248 k = 0; /* paranoia */
265 /* decode_dec decodes |i| bytes of decimal data from |in| and updates |bn|. */
266 static void decode_dec(BIGNUM *bn, const char *in, int i) {
270 j = BN_DEC_NUM - (i % BN_DEC_NUM);
271 if (j == BN_DEC_NUM) {
279 if (++j == BN_DEC_NUM) {
280 BN_mul_word(bn, BN_DEC_CONV);
288 typedef void (*decode_func) (BIGNUM *bn, const char *in, int i);
289 typedef int (*char_test_func) (int c);
291 static int bn_x2bn(BIGNUM **outp, const char *in, decode_func decode, char_test_func want_char) {
296 if (in == NULL || *in == 0) {
305 for (i = 0; want_char((unsigned char)in[i]); i++) {}
312 /* in is the start of the hex digits, and it is 'i' long */
324 /* i is the number of hex digests; */
325 if (bn_expand(ret, i * 4) == NULL) {
344 int BN_hex2bn(BIGNUM **outp, const char *in) {
345 return bn_x2bn(outp, in, decode_hex, isxdigit);
348 char *BN_bn2dec(const BIGNUM *a) {
349 int i = 0, num, ok = 0;
353 BN_ULONG *bn_data = NULL, *lp;
355 /* get an upper bound for the length of the decimal integer
356 * num <= (BN_num_bits(a) + 1) * log(2)
357 * <= 3 * BN_num_bits(a) * 0.1001 + log(2) + 1 (rounding error)
358 * <= BN_num_bits(a)/10 + BN_num_bits/1000 + 1 + 1
360 i = BN_num_bits(a) * 3;
361 num = i / 10 + i / 1000 + 1 + 1;
363 (BN_ULONG *)OPENSSL_malloc((num / BN_DEC_NUM + 1) * sizeof(BN_ULONG));
364 buf = (char *)OPENSSL_malloc(num + 3);
365 if ((buf == NULL) || (bn_data == NULL)) {
366 OPENSSL_PUT_ERROR(BN, BN_bn2dec, ERR_R_MALLOC_FAILURE);
374 #define BUF_REMAIN (num + 3 - (size_t)(p - buf))
381 if (BN_is_negative(t)) {
385 while (!BN_is_zero(t)) {
386 *lp = BN_div_word(t, BN_DEC_CONV);
390 /* We now have a series of blocks, BN_DEC_NUM chars
391 * in length, where the last one needs truncation.
392 * The blocks need to be reversed in order. */
393 BIO_snprintf(p, BUF_REMAIN, BN_DEC_FMT1, *lp);
397 while (lp != bn_data) {
399 BIO_snprintf(p, BUF_REMAIN, BN_DEC_FMT2, *lp);
408 if (bn_data != NULL) {
409 OPENSSL_free(bn_data);
422 int BN_dec2bn(BIGNUM **outp, const char *in) {
423 return bn_x2bn(outp, in, decode_dec, isdigit);
426 int BN_asc2bn(BIGNUM **outp, const char *in) {
427 const char *const orig_in = in;
432 if (in[0] == '0' && (in[1] == 'X' || in[1] == 'x')) {
433 if (!BN_hex2bn(outp, in+2)) {
437 if (!BN_dec2bn(outp, in)) {
442 if (*orig_in == '-') {
449 int BN_print(BIO *bp, const BIGNUM *a) {
453 if (a->neg && BIO_write(bp, "-", 1) != 1) {
457 if (BN_is_zero(a) && BIO_write(bp, "0", 1) != 1) {
461 for (i = a->top - 1; i >= 0; i--) {
462 for (j = BN_BITS2 - 4; j >= 0; j -= 4) {
463 /* strip leading zeros */
464 v = ((int)(a->d[i] >> (long)j)) & 0x0f;
466 if (BIO_write(bp, &hextable[v], 1) != 1) {
479 int BN_print_fp(FILE *fp, const BIGNUM *a) {
483 b = BIO_new(BIO_s_file());
487 BIO_set_fp(b, fp, BIO_NOCLOSE);
488 ret = BN_print(b, a);
494 BN_ULONG BN_get_word(const BIGNUM *bn) {