xref: /openbsd/lib/libcrypto/bn/bn_print.c (revision cecf84d4)
1 /* $OpenBSD: bn_print.c,v 1.23 2014/07/12 16:03:36 miod 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 <stdio.h>
61 
62 #include <openssl/opensslconf.h>
63 
64 #include <openssl/bio.h>
65 #include <openssl/buffer.h>
66 #include <openssl/err.h>
67 
68 #include "bn_lcl.h"
69 
70 static const char Hex[]="0123456789ABCDEF";
71 
72 /* Must 'free' the returned data */
73 char *
74 BN_bn2hex(const BIGNUM *a)
75 {
76 	int i, j, v, z = 0;
77 	char *buf;
78 	char *p;
79 
80 	buf = malloc(a->top * BN_BYTES * 2 + 2);
81 	if (buf == NULL) {
82 		BNerr(BN_F_BN_BN2HEX, ERR_R_MALLOC_FAILURE);
83 		goto err;
84 	}
85 	p = buf;
86 	if (a->neg)
87 		*(p++) = '-';
88 	if (BN_is_zero(a))
89 		*(p++) = '0';
90 	for (i = a->top - 1; i >=0; i--) {
91 		for (j = BN_BITS2 - 8; j >= 0; j -= 8) {
92 			/* strip leading zeros */
93 			v = ((int)(a->d[i] >> (long)j)) & 0xff;
94 			if (z || (v != 0)) {
95 				*(p++) = Hex[v >> 4];
96 				*(p++) = Hex[v & 0x0f];
97 				z = 1;
98 			}
99 		}
100 	}
101 	*p = '\0';
102 
103 err:
104 	return (buf);
105 }
106 
107 /* Must 'free' the returned data */
108 char *
109 BN_bn2dec(const BIGNUM *a)
110 {
111 	int i = 0, num, ok = 0;
112 	char *buf = NULL;
113 	char *p;
114 	BIGNUM *t = NULL;
115 	BN_ULONG *bn_data = NULL, *lp;
116 
117 	/* get an upper bound for the length of the decimal integer
118 	 * num <= (BN_num_bits(a) + 1) * log(2)
119 	 *     <= 3 * BN_num_bits(a) * 0.1001 + log(2) + 1     (rounding error)
120 	 *     <= BN_num_bits(a)/10 + BN_num_bits/1000 + 1 + 1
121 	 */
122 	i = BN_num_bits(a) * 3;
123 	num = (i / 10 + i / 1000 + 1) + 1;
124 	bn_data = reallocarray(NULL, num / BN_DEC_NUM + 1, sizeof(BN_ULONG));
125 	buf = malloc(num + 3);
126 	if ((buf == NULL) || (bn_data == NULL)) {
127 		BNerr(BN_F_BN_BN2DEC, ERR_R_MALLOC_FAILURE);
128 		goto err;
129 	}
130 	if ((t = BN_dup(a)) == NULL)
131 		goto err;
132 
133 #define BUF_REMAIN (num+3 - (size_t)(p - buf))
134 	p = buf;
135 	lp = bn_data;
136 	if (BN_is_zero(t)) {
137 		*(p++) = '0';
138 		*(p++) = '\0';
139 	} else {
140 		if (BN_is_negative(t))
141 			*p++ = '-';
142 
143 		i = 0;
144 		while (!BN_is_zero(t)) {
145 			*lp = BN_div_word(t, BN_DEC_CONV);
146 			lp++;
147 		}
148 		lp--;
149 		/* We now have a series of blocks, BN_DEC_NUM chars
150 		 * in length, where the last one needs truncation.
151 		 * The blocks need to be reversed in order. */
152 		snprintf(p, BUF_REMAIN, BN_DEC_FMT1, *lp);
153 		while (*p)
154 			p++;
155 		while (lp != bn_data) {
156 			lp--;
157 			snprintf(p, BUF_REMAIN, BN_DEC_FMT2, *lp);
158 			while (*p)
159 				p++;
160 		}
161 	}
162 	ok = 1;
163 
164 err:
165 	free(bn_data);
166 	BN_free(t);
167 	if (!ok && buf) {
168 		free(buf);
169 		buf = NULL;
170 	}
171 
172 	return (buf);
173 }
174 
175 int
176 BN_hex2bn(BIGNUM **bn, const char *a)
177 {
178 	BIGNUM *ret = NULL;
179 	BN_ULONG l = 0;
180 	int neg = 0, h, m, i,j, k, c;
181 	int num;
182 
183 	if ((a == NULL) || (*a == '\0'))
184 		return (0);
185 
186 	if (*a == '-') {
187 		neg = 1;
188 		a++;
189 	}
190 
191 	for (i = 0; isxdigit((unsigned char)a[i]); i++)
192 		;
193 
194 	num = i + neg;
195 	if (bn == NULL)
196 		return (num);
197 
198 	/* a is the start of the hex digits, and it is 'i' long */
199 	if (*bn == NULL) {
200 		if ((ret = BN_new()) == NULL)
201 			return (0);
202 	} else {
203 		ret= *bn;
204 		BN_zero(ret);
205 	}
206 
207 	/* i is the number of hex digests; */
208 	if (bn_expand(ret, i * 4) == NULL)
209 		goto err;
210 
211 	j = i; /* least significant 'hex' */
212 	m = 0;
213 	h = 0;
214 	while (j > 0) {
215 		m = ((BN_BYTES*2) <= j) ? (BN_BYTES * 2) : j;
216 		l = 0;
217 		for (;;) {
218 			c = a[j - m];
219 			if ((c >= '0') && (c <= '9'))
220 				k = c - '0';
221 			else if ((c >= 'a') && (c <= 'f'))
222 				k = c - 'a' + 10;
223 			else if ((c >= 'A') && (c <= 'F'))
224 				k = c - 'A' + 10;
225 			else
226 				k = 0; /* paranoia */
227 			l = (l << 4) | k;
228 
229 			if (--m <= 0) {
230 				ret->d[h++] = l;
231 				break;
232 			}
233 		}
234 		j -= (BN_BYTES * 2);
235 	}
236 	ret->top = h;
237 	bn_correct_top(ret);
238 	ret->neg = neg;
239 
240 	*bn = ret;
241 	bn_check_top(ret);
242 	return (num);
243 
244 err:
245 	if (*bn == NULL)
246 		BN_free(ret);
247 	return (0);
248 }
249 
250 int
251 BN_dec2bn(BIGNUM **bn, const char *a)
252 {
253 	BIGNUM *ret = NULL;
254 	BN_ULONG l = 0;
255 	int neg = 0, i, j;
256 	int num;
257 
258 	if ((a == NULL) || (*a == '\0'))
259 		return (0);
260 	if (*a == '-') {
261 		neg = 1;
262 		a++;
263 	}
264 
265 	for (i = 0; isdigit((unsigned char)a[i]); i++)
266 		;
267 
268 	num = i + neg;
269 	if (bn == NULL)
270 		return (num);
271 
272 	/* a is the start of the digits, and it is 'i' long.
273 	 * We chop it into BN_DEC_NUM digits at a time */
274 	if (*bn == NULL) {
275 		if ((ret = BN_new()) == NULL)
276 			return (0);
277 	} else {
278 		ret = *bn;
279 		BN_zero(ret);
280 	}
281 
282 	/* i is the number of digests, a bit of an over expand; */
283 	if (bn_expand(ret, i * 4) == NULL)
284 		goto err;
285 
286 	j = BN_DEC_NUM - (i % BN_DEC_NUM);
287 	if (j == BN_DEC_NUM)
288 		j = 0;
289 	l = 0;
290 	while (*a) {
291 		l *= 10;
292 		l += *a - '0';
293 		a++;
294 		if (++j == BN_DEC_NUM) {
295 			BN_mul_word(ret, BN_DEC_CONV);
296 			BN_add_word(ret, l);
297 			l = 0;
298 			j = 0;
299 		}
300 	}
301 	ret->neg = neg;
302 
303 	bn_correct_top(ret);
304 	*bn = ret;
305 	bn_check_top(ret);
306 	return (num);
307 
308 err:
309 	if (*bn == NULL)
310 		BN_free(ret);
311 	return (0);
312 }
313 
314 int
315 BN_asc2bn(BIGNUM **bn, const char *a)
316 {
317 	const char *p = a;
318 	if (*p == '-')
319 		p++;
320 
321 	if (p[0] == '0' && (p[1] == 'X' || p[1] == 'x')) {
322 		if (!BN_hex2bn(bn, p + 2))
323 			return 0;
324 	} else {
325 		if (!BN_dec2bn(bn, p))
326 			return 0;
327 	}
328 	if (*a == '-')
329 		(*bn)->neg = 1;
330 	return 1;
331 }
332 
333 #ifndef OPENSSL_NO_BIO
334 int
335 BN_print_fp(FILE *fp, const BIGNUM *a)
336 {
337 	BIO *b;
338 	int ret;
339 
340 	if ((b = BIO_new(BIO_s_file())) == NULL)
341 		return (0);
342 	BIO_set_fp(b, fp, BIO_NOCLOSE);
343 	ret = BN_print(b, a);
344 	BIO_free(b);
345 	return (ret);
346 }
347 
348 int
349 BN_print(BIO *bp, const BIGNUM *a)
350 {
351 	int i, j, v, z = 0;
352 	int ret = 0;
353 
354 	if ((a->neg) && (BIO_write(bp, "-", 1) != 1))
355 		goto end;
356 	if (BN_is_zero(a) && (BIO_write(bp, "0", 1) != 1))
357 		goto end;
358 	for (i = a->top - 1; i >= 0; i--) {
359 		for (j = BN_BITS2 - 4; j >= 0; j -= 4) {
360 			/* strip leading zeros */
361 			v = ((int)(a->d[i] >> (long)j)) & 0x0f;
362 			if (z || (v != 0)) {
363 				if (BIO_write(bp, &(Hex[v]), 1) != 1)
364 					goto end;
365 				z = 1;
366 			}
367 		}
368 	}
369 	ret = 1;
370 
371 end:
372 	return (ret);
373 }
374 #endif
375 
376 char *
377 BN_options(void)
378 {
379 	static int init = 0;
380 	static char data[16];
381 
382 	if (!init) {
383 		init++;
384 #ifdef BN_LLONG
385 		snprintf(data,sizeof data, "bn(%d,%d)",
386 		    (int)sizeof(BN_ULLONG) * 8, (int)sizeof(BN_ULONG) * 8);
387 #else
388 		snprintf(data,sizeof data, "bn(%d,%d)",
389 		    (int)sizeof(BN_ULONG) * 8, (int)sizeof(BN_ULONG) * 8);
390 #endif
391 	}
392 	return (data);
393 }
394