Home | History | Annotate | Download | only in bn
      1 /* Copyright (C) 1995-1998 Eric Young (eay (at) cryptsoft.com)
      2  * All rights reserved.
      3  *
      4  * This package is an SSL implementation written
      5  * by Eric Young (eay (at) cryptsoft.com).
      6  * The implementation was written so as to conform with Netscapes SSL.
      7  *
      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 (at) cryptsoft.com).
     14  *
     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.
     21  *
     22  * Redistribution and use in source and binary forms, with or without
     23  * modification, are permitted provided that the following conditions
     24  * are met:
     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 (at) 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 (at) cryptsoft.com)"
     39  *
     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
     50  * SUCH DAMAGE.
     51  *
     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.] */
     56 
     57 #include <openssl/bn.h>
     58 
     59 #include <ctype.h>
     60 #include <stdio.h>
     61 #include <string.h>
     62 
     63 #include <openssl/bio.h>
     64 #include <openssl/err.h>
     65 #include <openssl/mem.h>
     66 
     67 #include "internal.h"
     68 
     69 BIGNUM *BN_bin2bn(const uint8_t *in, size_t len, BIGNUM *ret) {
     70   unsigned num_words, m;
     71   BN_ULONG word = 0;
     72   BIGNUM *bn = NULL;
     73 
     74   if (ret == NULL) {
     75     ret = bn = BN_new();
     76   }
     77 
     78   if (ret == NULL) {
     79     return NULL;
     80   }
     81 
     82   if (len == 0) {
     83     ret->top = 0;
     84     return ret;
     85   }
     86 
     87   num_words = ((len - 1) / BN_BYTES) + 1;
     88   m = (len - 1) % BN_BYTES;
     89   if (bn_wexpand(ret, num_words) == NULL) {
     90     if (bn) {
     91       BN_free(bn);
     92     }
     93     return NULL;
     94   }
     95 
     96   ret->top = num_words;
     97   ret->neg = 0;
     98 
     99   while (len--) {
    100     word = (word << 8) | *(in++);
    101     if (m-- == 0) {
    102       ret->d[--num_words] = word;
    103       word = 0;
    104       m = BN_BYTES - 1;
    105     }
    106   }
    107 
    108   /* need to call this due to clear byte at top if avoiding having the top bit
    109    * set (-ve number) */
    110   bn_correct_top(ret);
    111   return ret;
    112 }
    113 
    114 size_t BN_bn2bin(const BIGNUM *in, uint8_t *out) {
    115   size_t n, i;
    116   BN_ULONG l;
    117 
    118   n = i = BN_num_bytes(in);
    119   while (i--) {
    120     l = in->d[i / BN_BYTES];
    121     *(out++) = (unsigned char)(l >> (8 * (i % BN_BYTES))) & 0xff;
    122   }
    123   return n;
    124 }
    125 
    126 /* constant_time_select_ulong returns |x| if |v| is 1 and |y| if |v| is 0. Its
    127  * behavior is undefined if |v| takes any other value. */
    128 static BN_ULONG constant_time_select_ulong(int v, BN_ULONG x, BN_ULONG y) {
    129   BN_ULONG mask = v;
    130   mask--;
    131 
    132   return (~mask & x) | (mask & y);
    133 }
    134 
    135 /* constant_time_le_size_t returns 1 if |x| <= |y| and 0 otherwise. |x| and |y|
    136  * must not have their MSBs set. */
    137 static int constant_time_le_size_t(size_t x, size_t y) {
    138   return ((x - y - 1) >> (sizeof(size_t) * 8 - 1)) & 1;
    139 }
    140 
    141 /* read_word_padded returns the |i|'th word of |in|, if it is not out of
    142  * bounds. Otherwise, it returns 0. It does so without branches on the size of
    143  * |in|, however it necessarily does not have the same memory access pattern. If
    144  * the access would be out of bounds, it reads the last word of |in|. |in| must
    145  * not be zero. */
    146 static BN_ULONG read_word_padded(const BIGNUM *in, size_t i) {
    147   /* Read |in->d[i]| if valid. Otherwise, read the last word. */
    148   BN_ULONG l = in->d[constant_time_select_ulong(
    149       constant_time_le_size_t(in->dmax, i), in->dmax - 1, i)];
    150 
    151   /* Clamp to zero if above |d->top|. */
    152   return constant_time_select_ulong(constant_time_le_size_t(in->top, i), 0, l);
    153 }
    154 
    155 int BN_bn2bin_padded(uint8_t *out, size_t len, const BIGNUM *in) {
    156   size_t i;
    157   BN_ULONG l;
    158 
    159   /* Special case for |in| = 0. Just branch as the probability is negligible. */
    160   if (BN_is_zero(in)) {
    161     memset(out, 0, len);
    162     return 1;
    163   }
    164 
    165   /* Check if the integer is too big. This case can exit early in non-constant
    166    * time. */
    167   if ((size_t)in->top > (len + (BN_BYTES - 1)) / BN_BYTES) {
    168     return 0;
    169   }
    170   if ((len % BN_BYTES) != 0) {
    171     l = read_word_padded(in, len / BN_BYTES);
    172     if (l >> (8 * (len % BN_BYTES)) != 0) {
    173       return 0;
    174     }
    175   }
    176 
    177   /* Write the bytes out one by one. Serialization is done without branching on
    178    * the bits of |in| or on |in->top|, but if the routine would otherwise read
    179    * out of bounds, the memory access pattern can't be fixed. However, for an
    180    * RSA key of size a multiple of the word size, the probability of BN_BYTES
    181    * leading zero octets is low.
    182    *
    183    * See Falko Stenzke, "Manger's Attack revisited", ICICS 2010. */
    184   i = len;
    185   while (i--) {
    186     l = read_word_padded(in, i / BN_BYTES);
    187     *(out++) = (uint8_t)(l >> (8 * (i % BN_BYTES))) & 0xff;
    188   }
    189   return 1;
    190 }
    191 
    192 static const char hextable[] = "0123456789abcdef";
    193 
    194 char *BN_bn2hex(const BIGNUM *bn) {
    195   int i, j, v, z = 0;
    196   char *buf;
    197   char *p;
    198 
    199   buf = (char *)OPENSSL_malloc(bn->top * BN_BYTES * 2 + 2);
    200   if (buf == NULL) {
    201     OPENSSL_PUT_ERROR(BN, BN_bn2hex, ERR_R_MALLOC_FAILURE);
    202     return NULL;
    203   }
    204 
    205   p = buf;
    206   if (bn->neg) {
    207     *(p++) = '-';
    208   }
    209 
    210   if (BN_is_zero(bn)) {
    211     *(p++) = '0';
    212   }
    213 
    214   for (i = bn->top - 1; i >= 0; i--) {
    215     for (j = BN_BITS2 - 8; j >= 0; j -= 8) {
    216       /* strip leading zeros */
    217       v = ((int)(bn->d[i] >> (long)j)) & 0xff;
    218       if (z || v != 0) {
    219         *(p++) = hextable[v >> 4];
    220         *(p++) = hextable[v & 0x0f];
    221         z = 1;
    222       }
    223     }
    224   }
    225   *p = '\0';
    226 
    227   return buf;
    228 }
    229 
    230 /* decode_hex decodes |i| bytes of hex data from |in| and updates |bn|. */
    231 static void decode_hex(BIGNUM *bn, const char *in, int i) {
    232   int h, m, j, k, c;
    233   BN_ULONG l=0;
    234 
    235   j = i; /* least significant 'hex' */
    236   h = 0;
    237   while (j > 0) {
    238     m = ((BN_BYTES * 2) <= j) ? (BN_BYTES * 2) : j;
    239     l = 0;
    240     for (;;) {
    241       c = in[j - m];
    242       if ((c >= '0') && (c <= '9')) {
    243         k = c - '0';
    244       } else if ((c >= 'a') && (c <= 'f')) {
    245         k = c - 'a' + 10;
    246       } else if ((c >= 'A') && (c <= 'F')) {
    247         k = c - 'A' + 10;
    248       } else {
    249         k = 0; /* paranoia */
    250       }
    251 
    252       l = (l << 4) | k;
    253 
    254       if (--m <= 0) {
    255         bn->d[h++] = l;
    256         break;
    257       }
    258     }
    259 
    260     j -= (BN_BYTES * 2);
    261   }
    262 
    263   bn->top = h;
    264 }
    265 
    266 /* decode_dec decodes |in_len| bytes of decimal data from |in| and updates |bn|. */
    267 static void decode_dec(BIGNUM *bn, const char *in, int in_len) {
    268   int i, j;
    269   BN_ULONG l = 0;
    270 
    271   j = BN_DEC_NUM - (in_len % BN_DEC_NUM);
    272   if (j == BN_DEC_NUM) {
    273     j = 0;
    274   }
    275   l = 0;
    276   for (i = 0; i < in_len; i++) {
    277     l *= 10;
    278     l += in[i] - '0';
    279     if (++j == BN_DEC_NUM) {
    280       BN_mul_word(bn, BN_DEC_CONV);
    281       BN_add_word(bn, l);
    282       l = 0;
    283       j = 0;
    284     }
    285   }
    286 }
    287 
    288 typedef void (*decode_func) (BIGNUM *bn, const char *in, int i);
    289 typedef int (*char_test_func) (int c);
    290 
    291 static int bn_x2bn(BIGNUM **outp, const char *in, decode_func decode, char_test_func want_char) {
    292   BIGNUM *ret = NULL;
    293   int neg = 0, i;
    294   int num;
    295 
    296   if (in == NULL || *in == 0) {
    297     return 0;
    298   }
    299 
    300   if (*in == '-') {
    301     neg = 1;
    302     in++;
    303   }
    304 
    305   for (i = 0; want_char((unsigned char)in[i]); i++) {}
    306 
    307   num = i + neg;
    308   if (outp == NULL) {
    309     return num;
    310   }
    311 
    312   /* in is the start of the hex digits, and it is 'i' long */
    313   if (*outp == NULL) {
    314     ret = BN_new();
    315     if (ret == NULL) {
    316       return 0;
    317     }
    318   } else {
    319     ret = *outp;
    320     BN_zero(ret);
    321   }
    322 
    323   /* i is the number of hex digests; */
    324   if (bn_expand(ret, i * 4) == NULL) {
    325     goto err;
    326   }
    327 
    328   decode(ret, in, i);
    329 
    330   bn_correct_top(ret);
    331   if (!BN_is_zero(ret)) {
    332     ret->neg = neg;
    333   }
    334 
    335   *outp = ret;
    336   return num;
    337 
    338 err:
    339   if (*outp == NULL) {
    340     BN_free(ret);
    341   }
    342 
    343   return 0;
    344 }
    345 
    346 int BN_hex2bn(BIGNUM **outp, const char *in) {
    347   return bn_x2bn(outp, in, decode_hex, isxdigit);
    348 }
    349 
    350 char *BN_bn2dec(const BIGNUM *a) {
    351   int i = 0, num, ok = 0;
    352   char *buf = NULL;
    353   char *p;
    354   BIGNUM *t = NULL;
    355   BN_ULONG *bn_data = NULL, *lp;
    356 
    357   /* get an upper bound for the length of the decimal integer
    358    * num <= (BN_num_bits(a) + 1) * log(2)
    359    *     <= 3 * BN_num_bits(a) * 0.1001 + log(2) + 1     (rounding error)
    360    *     <= BN_num_bits(a)/10 + BN_num_bits/1000 + 1 + 1
    361    */
    362   i = BN_num_bits(a) * 3;
    363   num = i / 10 + i / 1000 + 1 + 1;
    364   bn_data =
    365       (BN_ULONG *)OPENSSL_malloc((num / BN_DEC_NUM + 1) * sizeof(BN_ULONG));
    366   buf = (char *)OPENSSL_malloc(num + 3);
    367   if ((buf == NULL) || (bn_data == NULL)) {
    368     OPENSSL_PUT_ERROR(BN, BN_bn2dec, ERR_R_MALLOC_FAILURE);
    369     goto err;
    370   }
    371   t = BN_dup(a);
    372   if (t == NULL) {
    373     goto err;
    374   }
    375 
    376 #define BUF_REMAIN (num + 3 - (size_t)(p - buf))
    377   p = buf;
    378   lp = bn_data;
    379   if (BN_is_zero(t)) {
    380     *(p++) = '0';
    381     *(p++) = '\0';
    382   } else {
    383     if (BN_is_negative(t)) {
    384       *p++ = '-';
    385     }
    386 
    387     while (!BN_is_zero(t)) {
    388       *lp = BN_div_word(t, BN_DEC_CONV);
    389       lp++;
    390     }
    391     lp--;
    392     /* We now have a series of blocks, BN_DEC_NUM chars
    393      * in length, where the last one needs truncation.
    394      * The blocks need to be reversed in order. */
    395     BIO_snprintf(p, BUF_REMAIN, BN_DEC_FMT1, *lp);
    396     while (*p) {
    397       p++;
    398     }
    399     while (lp != bn_data) {
    400       lp--;
    401       BIO_snprintf(p, BUF_REMAIN, BN_DEC_FMT2, *lp);
    402       while (*p) {
    403         p++;
    404       }
    405     }
    406   }
    407   ok = 1;
    408 
    409 err:
    410   OPENSSL_free(bn_data);
    411   BN_free(t);
    412   if (!ok) {
    413     OPENSSL_free(buf);
    414     buf = NULL;
    415   }
    416 
    417   return buf;
    418 }
    419 
    420 int BN_dec2bn(BIGNUM **outp, const char *in) {
    421   return bn_x2bn(outp, in, decode_dec, isdigit);
    422 }
    423 
    424 int BN_asc2bn(BIGNUM **outp, const char *in) {
    425   const char *const orig_in = in;
    426   if (*in == '-') {
    427     in++;
    428   }
    429 
    430   if (in[0] == '0' && (in[1] == 'X' || in[1] == 'x')) {
    431     if (!BN_hex2bn(outp, in+2)) {
    432       return 0;
    433     }
    434   } else {
    435     if (!BN_dec2bn(outp, in)) {
    436       return 0;
    437     }
    438   }
    439 
    440   if (*orig_in == '-' && !BN_is_zero(*outp)) {
    441     (*outp)->neg = 1;
    442   }
    443 
    444   return 1;
    445 }
    446 
    447 int BN_print(BIO *bp, const BIGNUM *a) {
    448   int i, j, v, z = 0;
    449   int ret = 0;
    450 
    451   if (a->neg && BIO_write(bp, "-", 1) != 1) {
    452     goto end;
    453   }
    454 
    455   if (BN_is_zero(a) && BIO_write(bp, "0", 1) != 1) {
    456     goto end;
    457   }
    458 
    459   for (i = a->top - 1; i >= 0; i--) {
    460     for (j = BN_BITS2 - 4; j >= 0; j -= 4) {
    461       /* strip leading zeros */
    462       v = ((int)(a->d[i] >> (long)j)) & 0x0f;
    463       if (z || v != 0) {
    464         if (BIO_write(bp, &hextable[v], 1) != 1) {
    465           goto end;
    466         }
    467         z = 1;
    468       }
    469     }
    470   }
    471   ret = 1;
    472 
    473 end:
    474   return ret;
    475 }
    476 
    477 int BN_print_fp(FILE *fp, const BIGNUM *a) {
    478   BIO *b;
    479   int ret;
    480 
    481   b = BIO_new(BIO_s_file());
    482   if (b == NULL) {
    483     return 0;
    484   }
    485   BIO_set_fp(b, fp, BIO_NOCLOSE);
    486   ret = BN_print(b, a);
    487   BIO_free(b);
    488 
    489   return ret;
    490 }
    491 
    492 BN_ULONG BN_get_word(const BIGNUM *bn) {
    493   switch (bn->top) {
    494     case 0:
    495       return 0;
    496     case 1:
    497       return bn->d[0];
    498     default:
    499       return BN_MASK2;
    500   }
    501 }
    502