155714Skris/* crypto/bn/bn_print.c */
255714Skris/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
355714Skris * All rights reserved.
455714Skris *
555714Skris * This package is an SSL implementation written
655714Skris * by Eric Young (eay@cryptsoft.com).
755714Skris * The implementation was written so as to conform with Netscapes SSL.
8280304Sjkim *
955714Skris * This library is free for commercial and non-commercial use as long as
1055714Skris * the following conditions are aheared to.  The following conditions
1155714Skris * apply to all code found in this distribution, be it the RC4, RSA,
1255714Skris * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
1355714Skris * included with this distribution is covered by the same copyright terms
1455714Skris * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15280304Sjkim *
1655714Skris * Copyright remains Eric Young's, and as such any Copyright notices in
1755714Skris * the code are not to be removed.
1855714Skris * If this package is used in a product, Eric Young should be given attribution
1955714Skris * as the author of the parts of the library used.
2055714Skris * This can be in the form of a textual message at program startup or
2155714Skris * in documentation (online or textual) provided with the package.
22280304Sjkim *
2355714Skris * Redistribution and use in source and binary forms, with or without
2455714Skris * modification, are permitted provided that the following conditions
2555714Skris * are met:
2655714Skris * 1. Redistributions of source code must retain the copyright
2755714Skris *    notice, this list of conditions and the following disclaimer.
2855714Skris * 2. Redistributions in binary form must reproduce the above copyright
2955714Skris *    notice, this list of conditions and the following disclaimer in the
3055714Skris *    documentation and/or other materials provided with the distribution.
3155714Skris * 3. All advertising materials mentioning features or use of this software
3255714Skris *    must display the following acknowledgement:
3355714Skris *    "This product includes cryptographic software written by
3455714Skris *     Eric Young (eay@cryptsoft.com)"
3555714Skris *    The word 'cryptographic' can be left out if the rouines from the library
3655714Skris *    being used are not cryptographic related :-).
37280304Sjkim * 4. If you include any Windows specific code (or a derivative thereof) from
3855714Skris *    the apps directory (application code) you must include an acknowledgement:
3955714Skris *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40280304Sjkim *
4155714Skris * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
4255714Skris * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
4355714Skris * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
4455714Skris * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
4555714Skris * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
4655714Skris * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
4755714Skris * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
4855714Skris * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
4955714Skris * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
5055714Skris * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
5155714Skris * SUCH DAMAGE.
52280304Sjkim *
5355714Skris * The licence and distribution terms for any publically available version or
5455714Skris * derivative of this code cannot be changed.  i.e. this code cannot simply be
5555714Skris * copied and put under another distribution licence
5655714Skris * [including the GNU Public Licence.]
5755714Skris */
5855714Skris
5955714Skris#include <stdio.h>
6055714Skris#include <ctype.h>
61296317Sdelphij#include <limits.h>
6255714Skris#include "cryptlib.h"
6355714Skris#include <openssl/buffer.h>
6455714Skris#include "bn_lcl.h"
6555714Skris
66280304Sjkimstatic const char Hex[] = "0123456789ABCDEF";
6755714Skris
6868651Skris/* Must 'OPENSSL_free' the returned data */
6955714Skrischar *BN_bn2hex(const BIGNUM *a)
70280304Sjkim{
71280304Sjkim    int i, j, v, z = 0;
72280304Sjkim    char *buf;
73280304Sjkim    char *p;
7455714Skris
75284285Sjkim    if (a->neg && BN_is_zero(a)) {
76284285Sjkim        /* "-0" == 3 bytes including NULL terminator */
77284285Sjkim        buf = OPENSSL_malloc(3);
78284285Sjkim    } else {
79284285Sjkim        buf = OPENSSL_malloc(a->top * BN_BYTES * 2 + 2);
80284285Sjkim    }
81280304Sjkim    if (buf == NULL) {
82280304Sjkim        BNerr(BN_F_BN_BN2HEX, ERR_R_MALLOC_FAILURE);
83280304Sjkim        goto err;
84280304Sjkim    }
85280304Sjkim    p = buf;
86280304Sjkim    if (a->neg)
87280304Sjkim        *(p++) = '-';
88280304Sjkim    if (BN_is_zero(a))
89280304Sjkim        *(p++) = '0';
90280304Sjkim    for (i = a->top - 1; i >= 0; i--) {
91280304Sjkim        for (j = BN_BITS2 - 8; j >= 0; j -= 8) {
92280304Sjkim            /* strip leading zeros */
93280304Sjkim            v = ((int)(a->d[i] >> (long)j)) & 0xff;
94280304Sjkim            if (z || (v != 0)) {
95280304Sjkim                *(p++) = Hex[v >> 4];
96280304Sjkim                *(p++) = Hex[v & 0x0f];
97280304Sjkim                z = 1;
98280304Sjkim            }
99280304Sjkim        }
100280304Sjkim    }
101280304Sjkim    *p = '\0';
102280304Sjkim err:
103280304Sjkim    return (buf);
104280304Sjkim}
10555714Skris
10668651Skris/* Must 'OPENSSL_free' the returned data */
10755714Skrischar *BN_bn2dec(const BIGNUM *a)
108280304Sjkim{
109280304Sjkim    int i = 0, num, ok = 0;
110280304Sjkim    char *buf = NULL;
111280304Sjkim    char *p;
112280304Sjkim    BIGNUM *t = NULL;
113280304Sjkim    BN_ULONG *bn_data = NULL, *lp;
114306196Sjkim    int bn_data_num;
11555714Skris
116280304Sjkim    /*-
117280304Sjkim     * get an upper bound for the length of the decimal integer
118280304Sjkim     * num <= (BN_num_bits(a) + 1) * log(2)
119280304Sjkim     *     <= 3 * BN_num_bits(a) * 0.1001 + log(2) + 1     (rounding error)
120280304Sjkim     *     <= BN_num_bits(a)/10 + BN_num_bits/1000 + 1 + 1
121280304Sjkim     */
122280304Sjkim    i = BN_num_bits(a) * 3;
123280304Sjkim    num = (i / 10 + i / 1000 + 1) + 1;
124306196Sjkim    bn_data_num = num / BN_DEC_NUM + 1;
125306196Sjkim    bn_data = OPENSSL_malloc(bn_data_num * sizeof(BN_ULONG));
126306196Sjkim    buf = OPENSSL_malloc(num + 3);
127280304Sjkim    if ((buf == NULL) || (bn_data == NULL)) {
128280304Sjkim        BNerr(BN_F_BN_BN2DEC, ERR_R_MALLOC_FAILURE);
129280304Sjkim        goto err;
130280304Sjkim    }
131280304Sjkim    if ((t = BN_dup(a)) == NULL)
132280304Sjkim        goto err;
13355714Skris
134127128Snectar#define BUF_REMAIN (num+3 - (size_t)(p - buf))
135280304Sjkim    p = buf;
136280304Sjkim    lp = bn_data;
137280304Sjkim    if (BN_is_zero(t)) {
138280304Sjkim        *(p++) = '0';
139280304Sjkim        *(p++) = '\0';
140280304Sjkim    } else {
141280304Sjkim        if (BN_is_negative(t))
142280304Sjkim            *p++ = '-';
143160814Ssimon
144280304Sjkim        while (!BN_is_zero(t)) {
145306196Sjkim            if (lp - bn_data >= bn_data_num)
146306196Sjkim                goto err;
147280304Sjkim            *lp = BN_div_word(t, BN_DEC_CONV);
148306196Sjkim            if (*lp == (BN_ULONG)-1)
149306196Sjkim                goto err;
150280304Sjkim            lp++;
151280304Sjkim        }
152280304Sjkim        lp--;
153280304Sjkim        /*
154280304Sjkim         * We now have a series of blocks, BN_DEC_NUM chars in length, where
155280304Sjkim         * the last one needs truncation. The blocks need to be reversed in
156280304Sjkim         * order.
157280304Sjkim         */
158280304Sjkim        BIO_snprintf(p, BUF_REMAIN, BN_DEC_FMT1, *lp);
159280304Sjkim        while (*p)
160280304Sjkim            p++;
161280304Sjkim        while (lp != bn_data) {
162280304Sjkim            lp--;
163280304Sjkim            BIO_snprintf(p, BUF_REMAIN, BN_DEC_FMT2, *lp);
164280304Sjkim            while (*p)
165280304Sjkim                p++;
166280304Sjkim        }
167280304Sjkim    }
168280304Sjkim    ok = 1;
169280304Sjkim err:
170280304Sjkim    if (bn_data != NULL)
171280304Sjkim        OPENSSL_free(bn_data);
172280304Sjkim    if (t != NULL)
173280304Sjkim        BN_free(t);
174280304Sjkim    if (!ok && buf) {
175280304Sjkim        OPENSSL_free(buf);
176280304Sjkim        buf = NULL;
177280304Sjkim    }
178160814Ssimon
179280304Sjkim    return (buf);
180280304Sjkim}
18155714Skris
18255714Skrisint BN_hex2bn(BIGNUM **bn, const char *a)
183280304Sjkim{
184280304Sjkim    BIGNUM *ret = NULL;
185280304Sjkim    BN_ULONG l = 0;
186280304Sjkim    int neg = 0, h, m, i, j, k, c;
187280304Sjkim    int num;
18855714Skris
189280304Sjkim    if ((a == NULL) || (*a == '\0'))
190280304Sjkim        return (0);
19155714Skris
192280304Sjkim    if (*a == '-') {
193280304Sjkim        neg = 1;
194280304Sjkim        a++;
195280304Sjkim    }
19655714Skris
197296317Sdelphij    for (i = 0; i <= (INT_MAX/4) && isxdigit((unsigned char)a[i]); i++)
198296317Sdelphij        continue;
19955714Skris
200296317Sdelphij    if (i > INT_MAX/4)
201296317Sdelphij        goto err;
202296317Sdelphij
203280304Sjkim    num = i + neg;
204280304Sjkim    if (bn == NULL)
205280304Sjkim        return (num);
20655714Skris
207280304Sjkim    /* a is the start of the hex digits, and it is 'i' long */
208280304Sjkim    if (*bn == NULL) {
209280304Sjkim        if ((ret = BN_new()) == NULL)
210280304Sjkim            return (0);
211280304Sjkim    } else {
212280304Sjkim        ret = *bn;
213280304Sjkim        BN_zero(ret);
214280304Sjkim    }
21555714Skris
216296317Sdelphij    /* i is the number of hex digits */
217280304Sjkim    if (bn_expand(ret, i * 4) == NULL)
218280304Sjkim        goto err;
21955714Skris
220280304Sjkim    j = i;                      /* least significant 'hex' */
221280304Sjkim    m = 0;
222280304Sjkim    h = 0;
223280304Sjkim    while (j > 0) {
224280304Sjkim        m = ((BN_BYTES * 2) <= j) ? (BN_BYTES * 2) : j;
225280304Sjkim        l = 0;
226280304Sjkim        for (;;) {
227280304Sjkim            c = a[j - m];
228280304Sjkim            if ((c >= '0') && (c <= '9'))
229280304Sjkim                k = c - '0';
230280304Sjkim            else if ((c >= 'a') && (c <= 'f'))
231280304Sjkim                k = c - 'a' + 10;
232280304Sjkim            else if ((c >= 'A') && (c <= 'F'))
233280304Sjkim                k = c - 'A' + 10;
234280304Sjkim            else
235280304Sjkim                k = 0;          /* paranoia */
236280304Sjkim            l = (l << 4) | k;
23755714Skris
238280304Sjkim            if (--m <= 0) {
239280304Sjkim                ret->d[h++] = l;
240280304Sjkim                break;
241280304Sjkim            }
242280304Sjkim        }
243280304Sjkim        j -= (BN_BYTES * 2);
244280304Sjkim    }
245280304Sjkim    ret->top = h;
246280304Sjkim    bn_correct_top(ret);
247280304Sjkim    ret->neg = neg;
24855714Skris
249280304Sjkim    *bn = ret;
250280304Sjkim    bn_check_top(ret);
251280304Sjkim    return (num);
252280304Sjkim err:
253280304Sjkim    if (*bn == NULL)
254280304Sjkim        BN_free(ret);
255280304Sjkim    return (0);
256280304Sjkim}
25755714Skris
25855714Skrisint BN_dec2bn(BIGNUM **bn, const char *a)
259280304Sjkim{
260280304Sjkim    BIGNUM *ret = NULL;
261280304Sjkim    BN_ULONG l = 0;
262280304Sjkim    int neg = 0, i, j;
263280304Sjkim    int num;
26455714Skris
265280304Sjkim    if ((a == NULL) || (*a == '\0'))
266280304Sjkim        return (0);
267280304Sjkim    if (*a == '-') {
268280304Sjkim        neg = 1;
269280304Sjkim        a++;
270280304Sjkim    }
27155714Skris
272296317Sdelphij    for (i = 0; i <= (INT_MAX/4) && isdigit((unsigned char)a[i]); i++)
273296317Sdelphij        continue;
27455714Skris
275296317Sdelphij    if (i > INT_MAX/4)
276296317Sdelphij        goto err;
277296317Sdelphij
278280304Sjkim    num = i + neg;
279280304Sjkim    if (bn == NULL)
280280304Sjkim        return (num);
28155714Skris
282280304Sjkim    /*
283280304Sjkim     * a is the start of the digits, and it is 'i' long. We chop it into
284280304Sjkim     * BN_DEC_NUM digits at a time
285280304Sjkim     */
286280304Sjkim    if (*bn == NULL) {
287280304Sjkim        if ((ret = BN_new()) == NULL)
288280304Sjkim            return (0);
289280304Sjkim    } else {
290280304Sjkim        ret = *bn;
291280304Sjkim        BN_zero(ret);
292280304Sjkim    }
29355714Skris
294296317Sdelphij    /* i is the number of digits, a bit of an over expand */
295280304Sjkim    if (bn_expand(ret, i * 4) == NULL)
296280304Sjkim        goto err;
29755714Skris
298280304Sjkim    j = BN_DEC_NUM - (i % BN_DEC_NUM);
299280304Sjkim    if (j == BN_DEC_NUM)
300280304Sjkim        j = 0;
301280304Sjkim    l = 0;
302280304Sjkim    while (*a) {
303280304Sjkim        l *= 10;
304280304Sjkim        l += *a - '0';
305280304Sjkim        a++;
306280304Sjkim        if (++j == BN_DEC_NUM) {
307280304Sjkim            BN_mul_word(ret, BN_DEC_CONV);
308280304Sjkim            BN_add_word(ret, l);
309280304Sjkim            l = 0;
310280304Sjkim            j = 0;
311280304Sjkim        }
312280304Sjkim    }
313280304Sjkim    ret->neg = neg;
31455714Skris
315280304Sjkim    bn_correct_top(ret);
316280304Sjkim    *bn = ret;
317280304Sjkim    bn_check_top(ret);
318280304Sjkim    return (num);
319280304Sjkim err:
320280304Sjkim    if (*bn == NULL)
321280304Sjkim        BN_free(ret);
322280304Sjkim    return (0);
323280304Sjkim}
32455714Skris
325238405Sjkimint BN_asc2bn(BIGNUM **bn, const char *a)
326280304Sjkim{
327280304Sjkim    const char *p = a;
328280304Sjkim    if (*p == '-')
329280304Sjkim        p++;
330238405Sjkim
331280304Sjkim    if (p[0] == '0' && (p[1] == 'X' || p[1] == 'x')) {
332280304Sjkim        if (!BN_hex2bn(bn, p + 2))
333280304Sjkim            return 0;
334280304Sjkim    } else {
335280304Sjkim        if (!BN_dec2bn(bn, p))
336280304Sjkim            return 0;
337280304Sjkim    }
338280304Sjkim    if (*a == '-')
339280304Sjkim        (*bn)->neg = 1;
340280304Sjkim    return 1;
341280304Sjkim}
342238405Sjkim
343109998Smarkm#ifndef OPENSSL_NO_BIO
344280304Sjkim# ifndef OPENSSL_NO_FP_API
34559191Skrisint BN_print_fp(FILE *fp, const BIGNUM *a)
346280304Sjkim{
347280304Sjkim    BIO *b;
348280304Sjkim    int ret;
34955714Skris
350280304Sjkim    if ((b = BIO_new(BIO_s_file())) == NULL)
351280304Sjkim        return (0);
352280304Sjkim    BIO_set_fp(b, fp, BIO_NOCLOSE);
353280304Sjkim    ret = BN_print(b, a);
354280304Sjkim    BIO_free(b);
355280304Sjkim    return (ret);
356280304Sjkim}
357280304Sjkim# endif
35855714Skris
35955714Skrisint BN_print(BIO *bp, const BIGNUM *a)
360280304Sjkim{
361280304Sjkim    int i, j, v, z = 0;
362280304Sjkim    int ret = 0;
36355714Skris
364280304Sjkim    if ((a->neg) && (BIO_write(bp, "-", 1) != 1))
365280304Sjkim        goto end;
366280304Sjkim    if (BN_is_zero(a) && (BIO_write(bp, "0", 1) != 1))
367280304Sjkim        goto end;
368280304Sjkim    for (i = a->top - 1; i >= 0; i--) {
369280304Sjkim        for (j = BN_BITS2 - 4; j >= 0; j -= 4) {
370280304Sjkim            /* strip leading zeros */
371280304Sjkim            v = ((int)(a->d[i] >> (long)j)) & 0x0f;
372280304Sjkim            if (z || (v != 0)) {
373280304Sjkim                if (BIO_write(bp, &(Hex[v]), 1) != 1)
374280304Sjkim                    goto end;
375280304Sjkim                z = 1;
376280304Sjkim            }
377280304Sjkim        }
378280304Sjkim    }
379280304Sjkim    ret = 1;
380280304Sjkim end:
381280304Sjkim    return (ret);
382280304Sjkim}
38359191Skris#endif
384238405Sjkim
385238405Sjkimchar *BN_options(void)
386280304Sjkim{
387280304Sjkim    static int init = 0;
388280304Sjkim    static char data[16];
389238405Sjkim
390280304Sjkim    if (!init) {
391280304Sjkim        init++;
392238405Sjkim#ifdef BN_LLONG
393280304Sjkim        BIO_snprintf(data, sizeof data, "bn(%d,%d)",
394280304Sjkim                     (int)sizeof(BN_ULLONG) * 8, (int)sizeof(BN_ULONG) * 8);
395238405Sjkim#else
396280304Sjkim        BIO_snprintf(data, sizeof data, "bn(%d,%d)",
397280304Sjkim                     (int)sizeof(BN_ULONG) * 8, (int)sizeof(BN_ULONG) * 8);
398238405Sjkim#endif
399280304Sjkim    }
400280304Sjkim    return (data);
401280304Sjkim}
402