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>
64 #include <openssl/bio.h>
65 #include <openssl/bytestring.h>
66 #include <openssl/err.h>
67 #include <openssl/mem.h>
69 #include "../fipsmodule/bn/internal.h"
72 int BN_bn2cbb_padded(CBB *out, size_t len, const BIGNUM *in) {
74 return CBB_add_space(out, &ptr, len) && BN_bn2bin_padded(ptr, len, in);
77 static const char hextable[] = "0123456789abcdef";
79 char *BN_bn2hex(const BIGNUM *bn) {
80 int width = bn_minimal_width(bn);
81 char *buf = OPENSSL_malloc(1 /* leading '-' */ + 1 /* zero is non-empty */ +
82 width * BN_BYTES * 2 + 1 /* trailing NUL */);
84 OPENSSL_PUT_ERROR(BN, ERR_R_MALLOC_FAILURE);
98 for (int i = width - 1; i >= 0; i--) {
99 for (int j = BN_BITS2 - 8; j >= 0; j -= 8) {
100 // strip leading zeros
101 int v = ((int)(bn->d[i] >> (long)j)) & 0xff;
103 *(p++) = hextable[v >> 4];
104 *(p++) = hextable[v & 0x0f];
114 // decode_hex decodes |in_len| bytes of hex data from |in| and updates |bn|.
115 static int decode_hex(BIGNUM *bn, const char *in, int in_len) {
116 if (in_len > INT_MAX/4) {
117 OPENSSL_PUT_ERROR(BN, BN_R_BIGNUM_TOO_LONG);
120 // |in_len| is the number of hex digits.
121 if (!bn_expand(bn, in_len * 4)) {
127 // Decode one |BN_ULONG| at a time.
128 int todo = BN_BYTES * 2;
135 for (j = todo; j > 0; j--) {
136 char c = in[in_len - j];
139 if (c >= '0' && c <= '9') {
141 } else if (c >= 'a' && c <= 'f') {
143 } else if (c >= 'A' && c <= 'F') {
147 // This shouldn't happen. The caller checks |isxdigit|.
150 word = (word << 4) | hex;
156 assert(i <= bn->dmax);
161 // decode_dec decodes |in_len| bytes of decimal data from |in| and updates |bn|.
162 static int decode_dec(BIGNUM *bn, const char *in, int in_len) {
166 // Decode |BN_DEC_NUM| digits at a time.
167 j = BN_DEC_NUM - (in_len % BN_DEC_NUM);
168 if (j == BN_DEC_NUM) {
172 for (i = 0; i < in_len; i++) {
175 if (++j == BN_DEC_NUM) {
176 if (!BN_mul_word(bn, BN_DEC_CONV) ||
177 !BN_add_word(bn, l)) {
187 typedef int (*decode_func) (BIGNUM *bn, const char *in, int in_len);
188 typedef int (*char_test_func) (int c);
190 static int bn_x2bn(BIGNUM **outp, const char *in, decode_func decode, char_test_func want_char) {
195 if (in == NULL || *in == 0) {
204 for (i = 0; want_char((unsigned char)in[i]) && i + neg < INT_MAX; i++) {}
211 // in is the start of the hex digits, and it is 'i' long
222 if (!decode(ret, in, i)) {
226 bn_set_minimal_width(ret);
227 if (!BN_is_zero(ret)) {
242 int BN_hex2bn(BIGNUM **outp, const char *in) {
243 return bn_x2bn(outp, in, decode_hex, isxdigit);
246 char *BN_bn2dec(const BIGNUM *a) {
247 // It is easier to print strings little-endian, so we assemble it in reverse
248 // and fix at the end.
251 if (!CBB_init(&cbb, 16) ||
252 !CBB_add_u8(&cbb, 0 /* trailing NUL */)) {
257 if (!CBB_add_u8(&cbb, '0')) {
266 while (!BN_is_zero(copy)) {
267 BN_ULONG word = BN_div_word(copy, BN_DEC_CONV);
268 if (word == (BN_ULONG)-1) {
272 const int add_leading_zeros = !BN_is_zero(copy);
273 for (int i = 0; i < BN_DEC_NUM && (add_leading_zeros || word != 0); i++) {
274 if (!CBB_add_u8(&cbb, '0' + word % 10)) {
283 if (BN_is_negative(a) &&
284 !CBB_add_u8(&cbb, '-')) {
290 if (!CBB_finish(&cbb, &data, &len)) {
294 // Reverse the buffer.
295 for (size_t i = 0; i < len/2; i++) {
296 uint8_t tmp = data[i];
297 data[i] = data[len - 1 - i];
298 data[len - 1 - i] = tmp;
305 OPENSSL_PUT_ERROR(BN, ERR_R_MALLOC_FAILURE);
312 int BN_dec2bn(BIGNUM **outp, const char *in) {
313 return bn_x2bn(outp, in, decode_dec, isdigit);
316 int BN_asc2bn(BIGNUM **outp, const char *in) {
317 const char *const orig_in = in;
322 if (in[0] == '0' && (in[1] == 'X' || in[1] == 'x')) {
323 if (!BN_hex2bn(outp, in+2)) {
327 if (!BN_dec2bn(outp, in)) {
332 if (*orig_in == '-' && !BN_is_zero(*outp)) {
339 int BN_print(BIO *bp, const BIGNUM *a) {
343 if (a->neg && BIO_write(bp, "-", 1) != 1) {
347 if (BN_is_zero(a) && BIO_write(bp, "0", 1) != 1) {
351 for (i = bn_minimal_width(a) - 1; i >= 0; i--) {
352 for (j = BN_BITS2 - 4; j >= 0; j -= 4) {
353 // strip leading zeros
354 v = ((int)(a->d[i] >> (long)j)) & 0x0f;
356 if (BIO_write(bp, &hextable[v], 1) != 1) {
369 int BN_print_fp(FILE *fp, const BIGNUM *a) {
373 b = BIO_new(BIO_s_file());
377 BIO_set_fp(b, fp, BIO_NOCLOSE);
378 ret = BN_print(b, a);
385 size_t BN_bn2mpi(const BIGNUM *in, uint8_t *out) {
386 const size_t bits = BN_num_bits(in);
387 const size_t bytes = (bits + 7) / 8;
388 // If the number of bits is a multiple of 8, i.e. if the MSB is set,
389 // prefix with a zero byte.
391 if (bytes != 0 && (bits & 0x07) == 0) {
395 const size_t len = bytes + extend;
398 (len & 0xffffffff) != len) {
399 // If we cannot represent the number then we emit zero as the interface
400 // doesn't allow an error to be signalled.
402 OPENSSL_memset(out, 0, 4);
418 BN_bn2bin(in, out + 4 + extend);
419 if (in->neg && len > 0) {
425 BIGNUM *BN_mpi2bn(const uint8_t *in, size_t len, BIGNUM *out) {
427 OPENSSL_PUT_ERROR(BN, BN_R_BAD_ENCODING);
430 const size_t in_len = ((size_t)in[0] << 24) |
431 ((size_t)in[1] << 16) |
432 ((size_t)in[2] << 8) |
434 if (in_len != len - 4) {
435 OPENSSL_PUT_ERROR(BN, BN_R_BAD_ENCODING);
439 int out_is_alloced = 0;
443 OPENSSL_PUT_ERROR(BN, ERR_R_MALLOC_FAILURE);
455 if (BN_bin2bn(in, in_len, out) == NULL) {
456 if (out_is_alloced) {
461 out->neg = ((*in) & 0x80) != 0;
463 BN_clear_bit(out, BN_num_bits(out) - 1);