xref: /dragonfly/crypto/libressl/crypto/bn/bn_print.c (revision 38b720cd)
1 /* $OpenBSD: bn_print.c,v 1.28 2015/09/28 18:58:33 deraadt Exp $ */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  *
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  *
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  *
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  *
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 
59 #include <ctype.h>
60 #include <limits.h>
61 #include <stdio.h>
62 
63 #include <openssl/opensslconf.h>
64 
65 #include <openssl/bio.h>
66 #include <openssl/buffer.h>
67 #include <openssl/err.h>
68 
69 #include "bn_lcl.h"
70 
71 static const char Hex[]="0123456789ABCDEF";
72 
73 /* Must 'free' the returned data */
74 char *
75 BN_bn2hex(const BIGNUM *a)
76 {
77 	int i, j, v, z = 0;
78 	char *buf;
79 	char *p;
80 
81 	buf = malloc(BN_is_negative(a) + a->top * BN_BYTES * 2 + 2);
82 	if (buf == NULL) {
83 		BNerr(BN_F_BN_BN2HEX, ERR_R_MALLOC_FAILURE);
84 		goto err;
85 	}
86 	p = buf;
87 	if (BN_is_negative(a))
88 		*p++ = '-';
89 	if (BN_is_zero(a))
90 		*p++ = '0';
91 	for (i = a->top - 1; i >=0; i--) {
92 		for (j = BN_BITS2 - 8; j >= 0; j -= 8) {
93 			/* strip leading zeros */
94 			v = ((int)(a->d[i] >> (long)j)) & 0xff;
95 			if (z || (v != 0)) {
96 				*p++ = Hex[v >> 4];
97 				*p++ = Hex[v & 0x0f];
98 				z = 1;
99 			}
100 		}
101 	}
102 	*p = '\0';
103 
104 err:
105 	return (buf);
106 }
107 
108 /* Must 'free' the returned data */
109 char *
110 BN_bn2dec(const BIGNUM *a)
111 {
112 	int i = 0, num, ok = 0;
113 	char *buf = NULL;
114 	char *p;
115 	BIGNUM *t = NULL;
116 	BN_ULONG *bn_data = NULL, *lp;
117 
118 	if (BN_is_zero(a)) {
119 		buf = malloc(BN_is_negative(a) + 2);
120 		if (buf == NULL) {
121 			BNerr(BN_F_BN_BN2DEC, ERR_R_MALLOC_FAILURE);
122 			goto err;
123 		}
124 		p = buf;
125 		if (BN_is_negative(a))
126 			*p++ = '-';
127 		*p++ = '0';
128 		*p++ = '\0';
129 		return (buf);
130 	}
131 
132 	/* get an upper bound for the length of the decimal integer
133 	 * num <= (BN_num_bits(a) + 1) * log(2)
134 	 *     <= 3 * BN_num_bits(a) * 0.1001 + log(2) + 1     (rounding error)
135 	 *     <= BN_num_bits(a)/10 + BN_num_bits/1000 + 1 + 1
136 	 */
137 	i = BN_num_bits(a) * 3;
138 	num = (i / 10 + i / 1000 + 1) + 1;
139 	bn_data = reallocarray(NULL, num / BN_DEC_NUM + 1, sizeof(BN_ULONG));
140 	buf = malloc(num + 3);
141 	if ((buf == NULL) || (bn_data == NULL)) {
142 		BNerr(BN_F_BN_BN2DEC, ERR_R_MALLOC_FAILURE);
143 		goto err;
144 	}
145 	if ((t = BN_dup(a)) == NULL)
146 		goto err;
147 
148 #define BUF_REMAIN (num+3 - (size_t)(p - buf))
149 	p = buf;
150 	lp = bn_data;
151 	if (BN_is_negative(t))
152 		*p++ = '-';
153 
154 	i = 0;
155 	while (!BN_is_zero(t)) {
156 		*lp = BN_div_word(t, BN_DEC_CONV);
157 		lp++;
158 	}
159 	lp--;
160 	/* We now have a series of blocks, BN_DEC_NUM chars
161 	 * in length, where the last one needs truncation.
162 	 * The blocks need to be reversed in order. */
163 	snprintf(p, BUF_REMAIN, BN_DEC_FMT1, *lp);
164 	while (*p)
165 		p++;
166 	while (lp != bn_data) {
167 		lp--;
168 		snprintf(p, BUF_REMAIN, BN_DEC_FMT2, *lp);
169 		while (*p)
170 			p++;
171 	}
172 	ok = 1;
173 
174 err:
175 	free(bn_data);
176 	BN_free(t);
177 	if (!ok && buf) {
178 		free(buf);
179 		buf = NULL;
180 	}
181 
182 	return (buf);
183 }
184 
185 int
186 BN_hex2bn(BIGNUM **bn, const char *a)
187 {
188 	BIGNUM *ret = NULL;
189 	BN_ULONG l = 0;
190 	int neg = 0, h, m, i,j, k, c;
191 	int num;
192 
193 	if ((a == NULL) || (*a == '\0'))
194 		return (0);
195 
196 	if (*a == '-') {
197 		neg = 1;
198 		a++;
199 	}
200 
201 	for (i = 0; i <= (INT_MAX / 4) && isxdigit((unsigned char)a[i]); i++)
202 		;
203 	if (i > INT_MAX / 4)
204 		goto err;
205 
206 	num = i + neg;
207 	if (bn == NULL)
208 		return (num);
209 
210 	/* a is the start of the hex digits, and it is 'i' long */
211 	if (*bn == NULL) {
212 		if ((ret = BN_new()) == NULL)
213 			return (0);
214 	} else {
215 		ret= *bn;
216 		BN_zero(ret);
217 	}
218 
219 	/* i is the number of hex digits */
220 	if (bn_expand(ret, i * 4) == NULL)
221 		goto err;
222 
223 	j = i; /* least significant 'hex' */
224 	m = 0;
225 	h = 0;
226 	while (j > 0) {
227 		m = ((BN_BYTES*2) <= j) ? (BN_BYTES * 2) : j;
228 		l = 0;
229 		for (;;) {
230 			c = a[j - m];
231 			if ((c >= '0') && (c <= '9'))
232 				k = c - '0';
233 			else if ((c >= 'a') && (c <= 'f'))
234 				k = c - 'a' + 10;
235 			else if ((c >= 'A') && (c <= 'F'))
236 				k = c - 'A' + 10;
237 			else
238 				k = 0; /* paranoia */
239 			l = (l << 4) | k;
240 
241 			if (--m <= 0) {
242 				ret->d[h++] = l;
243 				break;
244 			}
245 		}
246 		j -= (BN_BYTES * 2);
247 	}
248 	ret->top = h;
249 	bn_correct_top(ret);
250 	ret->neg = neg;
251 
252 	*bn = ret;
253 	bn_check_top(ret);
254 	return (num);
255 
256 err:
257 	if (*bn == NULL)
258 		BN_free(ret);
259 	return (0);
260 }
261 
262 int
263 BN_dec2bn(BIGNUM **bn, const char *a)
264 {
265 	BIGNUM *ret = NULL;
266 	BN_ULONG l = 0;
267 	int neg = 0, i, j;
268 	int num;
269 
270 	if ((a == NULL) || (*a == '\0'))
271 		return (0);
272 	if (*a == '-') {
273 		neg = 1;
274 		a++;
275 	}
276 
277 	for (i = 0; i <= (INT_MAX / 4) && isdigit((unsigned char)a[i]); i++)
278 		;
279 	if (i > INT_MAX / 4)
280 		goto err;
281 
282 	num = i + neg;
283 	if (bn == NULL)
284 		return (num);
285 
286 	/* a is the start of the digits, and it is 'i' long.
287 	 * We chop it into BN_DEC_NUM digits at a time */
288 	if (*bn == NULL) {
289 		if ((ret = BN_new()) == NULL)
290 			return (0);
291 	} else {
292 		ret = *bn;
293 		BN_zero(ret);
294 	}
295 
296 	/* i is the number of digits, a bit of an over expand */
297 	if (bn_expand(ret, i * 4) == NULL)
298 		goto err;
299 
300 	j = BN_DEC_NUM - (i % BN_DEC_NUM);
301 	if (j == BN_DEC_NUM)
302 		j = 0;
303 	l = 0;
304 	while (*a) {
305 		l *= 10;
306 		l += *a - '0';
307 		a++;
308 		if (++j == BN_DEC_NUM) {
309 			BN_mul_word(ret, BN_DEC_CONV);
310 			BN_add_word(ret, l);
311 			l = 0;
312 			j = 0;
313 		}
314 	}
315 	ret->neg = neg;
316 
317 	bn_correct_top(ret);
318 	*bn = ret;
319 	bn_check_top(ret);
320 	return (num);
321 
322 err:
323 	if (*bn == NULL)
324 		BN_free(ret);
325 	return (0);
326 }
327 
328 int
329 BN_asc2bn(BIGNUM **bn, const char *a)
330 {
331 	const char *p = a;
332 	if (*p == '-')
333 		p++;
334 
335 	if (p[0] == '0' && (p[1] == 'X' || p[1] == 'x')) {
336 		if (!BN_hex2bn(bn, p + 2))
337 			return 0;
338 	} else {
339 		if (!BN_dec2bn(bn, p))
340 			return 0;
341 	}
342 	if (*a == '-')
343 		(*bn)->neg = 1;
344 	return 1;
345 }
346 
347 #ifndef OPENSSL_NO_BIO
348 int
349 BN_print_fp(FILE *fp, const BIGNUM *a)
350 {
351 	BIO *b;
352 	int ret;
353 
354 	if ((b = BIO_new(BIO_s_file())) == NULL)
355 		return (0);
356 	BIO_set_fp(b, fp, BIO_NOCLOSE);
357 	ret = BN_print(b, a);
358 	BIO_free(b);
359 	return (ret);
360 }
361 
362 int
363 BN_print(BIO *bp, const BIGNUM *a)
364 {
365 	int i, j, v, z = 0;
366 	int ret = 0;
367 
368 	if ((a->neg) && (BIO_write(bp, "-", 1) != 1))
369 		goto end;
370 	if (BN_is_zero(a) && (BIO_write(bp, "0", 1) != 1))
371 		goto end;
372 	for (i = a->top - 1; i >= 0; i--) {
373 		for (j = BN_BITS2 - 4; j >= 0; j -= 4) {
374 			/* strip leading zeros */
375 			v = ((int)(a->d[i] >> (long)j)) & 0x0f;
376 			if (z || (v != 0)) {
377 				if (BIO_write(bp, &(Hex[v]), 1) != 1)
378 					goto end;
379 				z = 1;
380 			}
381 		}
382 	}
383 	ret = 1;
384 
385 end:
386 	return (ret);
387 }
388 #endif
389 
390 char *
391 BN_options(void)
392 {
393 	static int init = 0;
394 	static char data[16];
395 
396 	if (!init) {
397 		init++;
398 #ifdef BN_LLONG
399 		snprintf(data,sizeof data, "bn(%d,%d)",
400 		    (int)sizeof(BN_ULLONG) * 8, (int)sizeof(BN_ULONG) * 8);
401 #else
402 		snprintf(data,sizeof data, "bn(%d,%d)",
403 		    (int)sizeof(BN_ULONG) * 8, (int)sizeof(BN_ULONG) * 8);
404 #endif
405 	}
406 	return (data);
407 }
408