Debian Codegraph @

mpi/mpicoder.c

raw
1 /* mpicoder.c - Coder for the external representation of MPIs
2 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003
3 * 2008 Free Software Foundation, Inc.
4 * Copyright (C) 2013, 2014 g10 Code GmbH
5 *
6 * This file is part of Libgcrypt.
7 *
8 * Libgcrypt is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU Lesser General Public License as
10 * published by the Free Software Foundation; either version 2.1 of
11 * the License, or (at your option) any later version.
12 *
13 * Libgcrypt is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this program; if not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include <config.h>
23 #include <stdio.h>
24 #include <string.h>
25 #include <stdlib.h>
26
27 #include "mpi-internal.h"
28 #include "g10lib.h"
29 #include "../cipher/bufhelp.h"
30
31 /* The maximum length we support in the functions converting an
32 * external representation to an MPI. This limit is used to catch
33 * programming errors and to avoid DoS due to insane long allocations.
34 * The 16 MiB limit is actually ridiculous large but some of those PQC
35 * algorithms use quite large keys and they might end up using MPIs
36 * for that. */
37 #define MAX_EXTERN_SCAN_BYTES (16*1024*1024)
38
39 /* The maximum length (in bits) we support for OpenPGP MPIs. Note
40 * that OpenPGP's MPI format uses only two bytes and thus would be
41 * limited to 64k anyway. Note that this limit matches that used by
42 * GnuPG. */
43 #define MAX_EXTERN_MPI_BITS 16384
44
45
46 /* Helper used to scan PGP style MPIs. Returns NULL on failure. */
47 static gcry_mpi_t
48 mpi_read_from_buffer (const unsigned char *buffer, unsigned *ret_nread,
49 int secure)
50 {
51 int i, j;
52 unsigned int nbits, nbytes, nlimbs, nread=0;
53 mpi_limb_t a;
54 gcry_mpi_t val = MPI_NULL;
55 unsigned int max_nread = *ret_nread;
56
57 if ( max_nread < 2 )
58 goto leave;
59 nbits = buffer[0] << 8 | buffer[1];
60 if ( nbits > MAX_EXTERN_MPI_BITS )
61 {
62 /* log_debug ("mpi too large (%u bits)\n", nbits); */
63 goto leave;
64 }
65 buffer += 2;
66 nread = 2;
67
68 nbytes = (nbits+7) / 8;
69 nlimbs = (nbytes+BYTES_PER_MPI_LIMB-1) / BYTES_PER_MPI_LIMB;
70 val = secure? mpi_alloc_secure (nlimbs) : mpi_alloc (nlimbs);
71 i = BYTES_PER_MPI_LIMB - nbytes % BYTES_PER_MPI_LIMB;
72 i %= BYTES_PER_MPI_LIMB;
73 j= val->nlimbs = nlimbs;
74 val->sign = 0;
75 for ( ; j > 0; j-- )
76 {
77 a = 0;
78 if (i == 0 && nread + BYTES_PER_MPI_LIMB <= max_nread)
79 {
80 #if BYTES_PER_MPI_LIMB == 4
81 a = buf_get_be32 (buffer);
82 #elif BYTES_PER_MPI_LIMB == 8
83 a = buf_get_be64 (buffer);
84 #else
85 # error please implement for this limb size.
86 #endif
87 buffer += BYTES_PER_MPI_LIMB;
88 nread += BYTES_PER_MPI_LIMB;
89 i += BYTES_PER_MPI_LIMB;
90 }
91 for (; i < BYTES_PER_MPI_LIMB; i++ )
92 {
93 if ( ++nread > max_nread )
94 {
95 /* log_debug ("mpi larger than buffer"); */
96 mpi_free (val);
97 val = NULL;
98 goto leave;
99 }
100 a <<= 8;
101 a |= *buffer++;
102 }
103 i = 0;
104 val->d[j-1] = a;
105 }
106
107 leave:
108 *ret_nread = nread;
109 return val;
110 }
111
112
113 /****************
114 * Fill the mpi VAL from the hex string in STR.
115 */
116 static int
117 mpi_fromstr (gcry_mpi_t val, const char *str, size_t slen)
118 {
119 static const int hex2int[2][256] =
120 {
121 {
122 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
123 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
124 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0x00, 0x10, 0x20, 0x30,
125 0x40, 0x50, 0x60, 0x70, 0x80, 0x90, -1, -1, -1, -1, -1, -1, -1, 0xa0,
126 0xb0, 0xc0, 0xd0, 0xe0, 0xf0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
127 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0xa0,
128 0xb0, 0xc0, 0xd0, 0xe0, 0xf0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
129 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
130 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
131 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
132 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
133 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
134 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
135 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
136 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
137 },
138 {
139 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
140 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
141 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0x00, 0x01, 0x02, 0x03,
142 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, -1, -1, -1, -1, -1, -1, -1, 0x0a,
143 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
144 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0x0a,
145 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
146 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
147 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
148 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
149 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
150 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
151 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
152 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
153 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
154 }
155 };
156 int sign = 0;
157 int prepend_zero = 0;
158 int i, j, c, c1, c2;
159 unsigned int nbits, nbytes, nlimbs;
160 mpi_limb_t a;
161
162 if ( *str == '-' )
163 {
164 sign = 1;
165 str++;
166 slen--;
167 }
168
169 /* Skip optional hex prefix. */
170 if ( *str == '0' && str[1] == 'x' )
171 {
172 str += 2;
173 slen -= 2;
174 }
175
176 nbits = slen * 4;
177 if ((nbits % 8))
178 prepend_zero = 1;
179
180 nbytes = (nbits+7) / 8;
181 nlimbs = (nbytes+BYTES_PER_MPI_LIMB-1) / BYTES_PER_MPI_LIMB;
182
183 if ( val->alloced < nlimbs )
184 mpi_resize (val, nlimbs);
185
186 i = BYTES_PER_MPI_LIMB - (nbytes % BYTES_PER_MPI_LIMB);
187 i %= BYTES_PER_MPI_LIMB;
188 j = val->nlimbs = nlimbs;
189 val->sign = sign;
190 for (; j > 0; j--)
191 {
192 a = 0;
193
194 if (prepend_zero == 0 && (i & 31) == 0)
195 {
196 while (slen >= sizeof(u32) * 2)
197 {
198 u32 n, m;
199 u32 x, y;
200
201 x = buf_get_le32(str);
202 y = buf_get_le32(str + 4);
203 str += 8;
204 slen -= 8;
205
206 a <<= 31; /* Two step to avoid compiler warning on 32-bit. */
207 a <<= 1;
208
209 n = (hex2int[0][(x >> 0) & 0xff]
210 | hex2int[1][(x >> 8) & 0xff]) << 8;
211 m = (hex2int[0][(y >> 0) & 0xff]
212 | hex2int[1][(y >> 8) & 0xff]) << 8;
213 n |= hex2int[0][(x >> 16) & 0xff];
214 n |= hex2int[1][(x >> 24) & 0xff];
215 m |= hex2int[0][(y >> 16) & 0xff];
216 m |= hex2int[1][(y >> 24) & 0xff];
217
218 a |= (n << 16) | m;
219 i += 32;
220 if ((int)(n | m) < 0)
221 {
222 /* Invalid character. */
223 mpi_clear (val);
224 return 1; /* Error. */
225 }
226 if (i == BITS_PER_MPI_LIMB)
227 break;
228 }
229 }
230
231 for (; i < BYTES_PER_MPI_LIMB; i++)
232 {
233 if (prepend_zero)
234 {
235 c1 = '0';
236 prepend_zero = 0;
237 }
238 else
239 {
240 c1 = *str++;
241 slen--;
242 }
243
244 if (!c1)
245 {
246 mpi_clear (val);
247 return 1; /* Error. */
248 }
249 c2 = *str++;
250 slen--;
251 if (!c2)
252 {
253 mpi_clear (val);
254 return 1; /* Error. */
255 }
256 c = hex2int[0][c1 & 0xff];
257 c |= hex2int[1][c2 & 0xff];
258 if (c < 0)
259 {
260 mpi_clear(val);
261 return 1; /* Error. */
262 }
263 a <<= 8;
264 a |= c;
265 }
266 i = 0;
267 val->d[j-1] = a;
268 }
269
270 return 0; /* Okay. */
271 }
272
273
274 /* Return an allocated buffer with the MPI (msb first). NBYTES
275 receives the length of this buffer. If FILL_LE is not 0, the
276 returned value is stored as little endian and right padded with
277 zeroes so that the returned buffer has at least FILL_LE bytes.
278
279 If EXTRAALLOC > 0 the returned buffer has these number of bytes
280 extra allocated at the end; if EXTRAALLOC < 0 the returned buffer
281 has the absolute value of EXTRAALLOC allocated at the begin of the
282 buffer (the are not initialized) and the MPI is stored right after
283 this. This feature is useful to allow the caller to prefix the
284 returned value. EXTRAALLOC is _not_ included in the value stored
285 at NBYTES.
286
287 Caller must free the return string. This function returns an
288 allocated buffer with NBYTES set to zero if the value of A is zero.
289 If sign is not NULL, it will be set to the sign of the A. On error
290 NULL is returned and ERRNO set appropriately. */
291 static unsigned char *
292 do_get_buffer (gcry_mpi_t a, unsigned int fill_le, int extraalloc,
293 unsigned int *nbytes, int *sign, int force_secure)
294 {
295 unsigned char *p, *buffer, *retbuffer;
296 unsigned int length, tmp;
297 mpi_limb_t alimb;
298 int i;
299 size_t n, n2;
300
301 if (sign)
302 *sign = a->sign;
303
304 *nbytes = a->nlimbs * BYTES_PER_MPI_LIMB;
305 n = *nbytes? *nbytes:1; /* Allocate at least one byte. */
306 if (n < fill_le)
307 n = fill_le;
308 if (extraalloc < 0)
309 n2 = n + -extraalloc;
310 else
311 n2 = n + extraalloc;
312
313 retbuffer = (force_secure || mpi_is_secure(a))? xtrymalloc_secure (n2)
314 : xtrymalloc (n2);
315 if (!retbuffer)
316 return NULL;
317 if (extraalloc < 0)
318 buffer = retbuffer + -extraalloc;
319 else
320 buffer = retbuffer;
321 p = buffer;
322
323 for (i=a->nlimbs-1; i >= 0; i--)
324 {
325 alimb = a->d[i];
326 #if BYTES_PER_MPI_LIMB == 4
327 buf_put_be32 (p, alimb);
328 p += 4;
329 #elif BYTES_PER_MPI_LIMB == 8
330 buf_put_be64 (p, alimb);
331 p += 8;
332 #else
333 # error please implement for this limb size.
334 #endif
335 }
336
337 if (fill_le)
338 {
339 length = *nbytes;
340 /* Reverse buffer and pad with zeroes. */
341 for (i = 0; i + 8 < length / 2; i += 8)
342 {
343 u64 head = buf_get_be64 (buffer + i);
344 u64 tail = buf_get_be64 (buffer + length - 8 - i);
345 buf_put_le64 (buffer + length - 8 - i, head);
346 buf_put_le64 (buffer + i, tail);
347 }
348 if (i + 4 < length / 2)
349 {
350 u32 head = buf_get_be32 (buffer + i);
351 u32 tail = buf_get_be32 (buffer + length - 4 - i);
352 buf_put_le32 (buffer + length - 4 - i, head);
353 buf_put_le32 (buffer + i, tail);
354 i += 4;
355 }
356 for (; i < length/2; i++)
357 {
358 tmp = buffer[i];
359 buffer[i] = buffer[length-1-i];
360 buffer[length-1-i] = tmp;
361 }
362 /* Pad with zeroes. */
363 for (p = buffer + length; length < fill_le; length++)
364 *p++ = 0;
365 *nbytes = length;
366
367 return retbuffer;
368 }
369
370 /* This is sub-optimal but we need to do the shift operation because
371 the caller has to free the returned buffer. */
372 for (p=buffer; *nbytes && !*p; p++, --*nbytes)
373 ;
374 if (p != buffer)
375 memmove (buffer, p, *nbytes);
376 return retbuffer;
377 }
378
379
380 byte *
381 _gcry_mpi_get_buffer (gcry_mpi_t a, unsigned int fill_le,
382 unsigned int *r_nbytes, int *sign)
383 {
384 if (mpi_get_flag (a, GCRYMPI_FLAG_OPAQUE))
385 {
386 unsigned int nbits;
387 byte *p = _gcry_mpi_get_opaque_copy (a, &nbits);
388
389 if (r_nbytes)
390 *r_nbytes = (nbits+7)/8;
391
392 return p;
393 }
394 else
395 return do_get_buffer (a, fill_le, 0, r_nbytes, sign, 0);
396 }
397
398 byte *
399 _gcry_mpi_get_buffer_extra (gcry_mpi_t a, unsigned int fill_le, int extraalloc,
400 unsigned int *r_nbytes, int *sign)
401 {
402 return do_get_buffer (a, fill_le, extraalloc, r_nbytes, sign, 0);
403 }
404
405 byte *
406 _gcry_mpi_get_secure_buffer (gcry_mpi_t a, unsigned int fill_le,
407 unsigned int *r_nbytes, int *sign)
408 {
409 return do_get_buffer (a, fill_le, 0, r_nbytes, sign, 1);
410 }
411
412
413 /*
414 * Use the NBYTES at BUFFER_ARG to update A. Set the sign of a to
415 * SIGN.
416 */
417 void
418 _gcry_mpi_set_buffer (gcry_mpi_t a, const void *buffer_arg,
419 unsigned int nbytes, int sign)
420 {
421 const unsigned char *buffer = (const unsigned char*)buffer_arg;
422 const unsigned char *p;
423 mpi_limb_t alimb;
424 int nlimbs;
425 int i;
426
427 if (mpi_is_immutable (a))
428 {
429 mpi_immutable_failed ();
430 return;
431 }
432
433 nlimbs = (nbytes + BYTES_PER_MPI_LIMB - 1) / BYTES_PER_MPI_LIMB;
434 RESIZE_IF_NEEDED(a, nlimbs);
435 a->sign = sign;
436
437 for (i=0, p = buffer+nbytes-1; p >= buffer+BYTES_PER_MPI_LIMB; )
438 {
439 #if BYTES_PER_MPI_LIMB == 4
440 alimb = buf_get_be32(p - 4 + 1);
441 p -= 4;
442 #elif BYTES_PER_MPI_LIMB == 8
443 alimb = buf_get_be64(p - 8 + 1);
444 p -= 8;
445 #else
446 # error please implement for this limb size.
447 #endif
448 a->d[i++] = alimb;
449 }
450 if ( p >= buffer )
451 {
452 byte last[BYTES_PER_MPI_LIMB] = { 0 };
453 unsigned int n = (p - buffer) + 1;
454
455 n = n > BYTES_PER_MPI_LIMB ? BYTES_PER_MPI_LIMB : n;
456 memcpy (last + BYTES_PER_MPI_LIMB - n, p - n + 1, n);
457 p -= n;
458
459 #if BYTES_PER_MPI_LIMB == 4
460 alimb = buf_get_be32(last);
461 #elif BYTES_PER_MPI_LIMB == 8
462 alimb = buf_get_be64(last);
463 #else
464 # error please implement for this limb size.
465 #endif
466
467 a->d[i++] = alimb;
468 }
469 a->nlimbs = i;
470 gcry_assert (i == nlimbs);
471 }
472
473
474 static void
475 onecompl (gcry_mpi_t a)
476 {
477 mpi_ptr_t ap;
478 mpi_size_t n;
479 unsigned int i;
480 unsigned int nbits;
481
482 if (!a || mpi_is_immutable (a))
483 {
484 mpi_immutable_failed ();
485 return;
486 }
487
488 nbits = mpi_get_nbits (a);
489
490 mpi_normalize (a);
491 ap = a->d;
492 n = a->nlimbs;
493
494 for( i = 0; i < n; i++ )
495 ap[i] ^= (mpi_limb_t)(-1);
496
497 a->sign = 0;
498 mpi_clear_highbit (a, nbits-1);
499 }
500
501
502 /* Perform a two's complement operation on buffer P of size N bytes. */
503 static void
504 twocompl (unsigned char *p, unsigned int n)
505 {
506 int i;
507
508 for (i=n-1; i >= 0 && !p[i]; i--)
509 ;
510 if (i >= 0)
511 {
512 unsigned char pi = p[i];
513 unsigned int ntz = _gcry_ctz (pi);
514
515 p[i] = ((p[i] ^ (0xfe << ntz)) | (0x01 << ntz)) & (0xff << ntz);
516
517 for (i--; i >= 7; i -= 8)
518 {
519 buf_put_he64(&p[i-7], ~buf_get_he64(&p[i-7]));
520 }
521 if (i >= 3)
522 {
523 buf_put_he32(&p[i-3], ~buf_get_he32(&p[i-3]));
524 i -= 4;
525 }
526 for (; i >= 0; i--)
527 {
528 p[i] ^= 0xff;
529 }
530 }
531 }
532
533
534 /* Convert the external representation of an integer stored in BUFFER
535 * with a length of BUFLEN into a newly create MPI returned in
536 * RET_MPI. If NSCANNED is not NULL, it will receive the number of
537 * bytes actually scanned after a successful operation. */
538 gcry_err_code_t
539 _gcry_mpi_scan (struct gcry_mpi **ret_mpi, enum gcry_mpi_format format,
540 const void *buffer_arg, size_t buflen, size_t *nscanned)
541 {
542 const unsigned char *buffer = (const unsigned char*)buffer_arg;
543 struct gcry_mpi *a = NULL;
544 unsigned int len;
545 int secure = (buffer && _gcry_is_secure (buffer));
546
547 if (buflen > MAX_EXTERN_SCAN_BYTES)
548 {
549 if (nscanned)
550 *nscanned = 0;
551 return GPG_ERR_INV_OBJ;
552 }
553
554 if (format == GCRYMPI_FMT_SSH)
555 len = 0;
556 else
557 len = buflen;
558
559 if (format == GCRYMPI_FMT_STD)
560 {
561 const unsigned char *s = buffer;
562
563 a = secure? mpi_alloc_secure ((len+BYTES_PER_MPI_LIMB-1)
564 /BYTES_PER_MPI_LIMB)
565 : mpi_alloc ((len+BYTES_PER_MPI_LIMB-1)/BYTES_PER_MPI_LIMB);
566 if (len)
567 {
568 _gcry_mpi_set_buffer (a, s, len, 0);
569 a->sign = !!(*s & 0x80);
570 if (a->sign)
571 {
572 onecompl (a);
573 mpi_add_ui (a, a, 1);
574 a->sign = 1;
575 }
576 }
577 if (ret_mpi)
578 {
579 mpi_normalize ( a );
580 *ret_mpi = a;
581 }
582 else
583 mpi_free(a);
584 if (nscanned)
585 *nscanned = len;
586 return 0;
587 }
588 else if (format == GCRYMPI_FMT_USG)
589 {
590 a = secure? mpi_alloc_secure ((len+BYTES_PER_MPI_LIMB-1)
591 /BYTES_PER_MPI_LIMB)
592 : mpi_alloc ((len+BYTES_PER_MPI_LIMB-1)/BYTES_PER_MPI_LIMB);
593
594 if (len)
595 _gcry_mpi_set_buffer (a, buffer, len, 0);
596 if (ret_mpi)
597 {
598 mpi_normalize ( a );
599 *ret_mpi = a;
600 }
601 else
602 mpi_free(a);
603 if (nscanned)
604 *nscanned = len;
605 return 0;
606 }
607 else if (format == GCRYMPI_FMT_PGP)
608 {
609 a = mpi_read_from_buffer (buffer, &len, secure);
610 if (nscanned)
611 *nscanned = len;
612 if (ret_mpi && a)
613 {
614 mpi_normalize (a);
615 *ret_mpi = a;
616 }
617 else if (a)
618 {
619 mpi_free(a);
620 a = NULL;
621 }
622 return a? 0 : GPG_ERR_INV_OBJ;
623 }
624 else if (format == GCRYMPI_FMT_SSH)
625 {
626 const unsigned char *s = buffer;
627 size_t n;
628
629 /* This test is not strictly necessary and an assert (!len)
630 would be sufficient. We keep this test in case we later
631 allow the BUFLEN argument to act as a sanitiy check. Same
632 below. */
633 if (len && len < 4)
634 return GPG_ERR_TOO_SHORT;
635
636 n = buf_get_be32 (s);
637 s += 4;
638 if (len)
639 len -= 4;
640 if (len && n > len)
641 return GPG_ERR_TOO_LARGE;
642
643 a = secure? mpi_alloc_secure ((n+BYTES_PER_MPI_LIMB-1)
644 /BYTES_PER_MPI_LIMB)
645 : mpi_alloc ((n+BYTES_PER_MPI_LIMB-1)/BYTES_PER_MPI_LIMB);
646 if (n)
647 {
648 _gcry_mpi_set_buffer( a, s, n, 0 );
649 a->sign = !!(*s & 0x80);
650 if (a->sign)
651 {
652 onecompl (a);
653 mpi_add_ui (a, a, 1);
654 a->sign = 1;
655 }
656 }
657 if (nscanned)
658 *nscanned = n+4;
659 if (ret_mpi)
660 {
661 mpi_normalize ( a );
662 *ret_mpi = a;
663 }
664 else
665 mpi_free(a);
666 return 0;
667 }
668 else if (format == GCRYMPI_FMT_HEX)
669 {
670 size_t slen;
671 /* We can only handle C strings for now. */
672 if (buflen)
673 return GPG_ERR_INV_ARG;
674
675 slen = strlen ((const char *)buffer);
676 if (slen > MAX_EXTERN_SCAN_BYTES)
677 return GPG_ERR_INV_OBJ;
678 a = secure? mpi_alloc_secure ((((slen+1)/2)+BYTES_PER_MPI_LIMB-1)
679 /BYTES_PER_MPI_LIMB)
680 : mpi_alloc((((slen+1)/2)+BYTES_PER_MPI_LIMB-1)
681 /BYTES_PER_MPI_LIMB);
682 if (mpi_fromstr (a, (const char *)buffer, slen))
683 {
684 mpi_free (a);
685 return GPG_ERR_INV_OBJ;
686 }
687 if (ret_mpi)
688 {
689 mpi_normalize ( a );
690 *ret_mpi = a;
691 }
692 else
693 mpi_free(a);
694 if (nscanned)
695 *nscanned = strlen ((const char*)buffer);
696 return 0;
697 }
698 else
699 return GPG_ERR_INV_ARG;
700 }
701
702
703 /* Convert the big integer A into the external representation
704 described by FORMAT and store it in the provided BUFFER which has
705 been allocated by the user with a size of BUFLEN bytes. NWRITTEN
706 receives the actual length of the external representation unless it
707 has been passed as NULL. BUFFER may be NULL to query the required
708 length. */
709 gcry_err_code_t
710 _gcry_mpi_print (enum gcry_mpi_format format,
711 unsigned char *buffer, size_t buflen,
712 size_t *nwritten, struct gcry_mpi *a)
713 {
714 unsigned int nbits = mpi_get_nbits (a);
715 size_t len;
716 size_t dummy_nwritten;
717 int negative;
718
719 if (!nwritten)
720 nwritten = &dummy_nwritten;
721
722 /* Libgcrypt does no always care to set clear the sign if the value
723 is 0. For printing this is a bit of a surprise, in particular
724 because if some of the formats don't support negative numbers but
725 should be able to print a zero. Thus we need this extra test
726 for a negative number. */
727 if (a->sign && _gcry_mpi_cmp_ui (a, 0))
728 negative = 1;
729 else
730 negative = 0;
731
732 len = buflen;
733 *nwritten = 0;
734 if (format == GCRYMPI_FMT_STD)
735 {
736 unsigned char *tmp;
737 int extra = 0;
738 unsigned int n;
739
740 tmp = _gcry_mpi_get_buffer (a, 0, &n, NULL);
741 if (!tmp)
742 return gpg_err_code_from_syserror ();
743
744 if (negative)
745 {
746 twocompl (tmp, n);
747 if (!(*tmp & 0x80))
748 {
749 /* Need to extend the sign. */
750 n++;
751 extra = 2;
752 }
753 }
754 else if (n && (*tmp & 0x80))
755 {
756 /* Positive but the high bit of the returned buffer is set.
757 Thus we need to print an extra leading 0x00 so that the
758 output is interpreted as a positive number. */
759 n++;
760 extra = 1;
761 }
762
763 if (buffer && n > len)
764 {
765 /* The provided buffer is too short. */
766 xfree (tmp);
767 return GPG_ERR_TOO_SHORT;
768 }
769 if (buffer)
770 {
771 unsigned char *s = buffer;
772
773 if (extra == 1)
774 *s++ = 0;
775 else if (extra)
776 *s++ = 0xff;
777 memcpy (s, tmp, n-!!extra);
778 }
779 xfree (tmp);
780 *nwritten = n;
781 return 0;
782 }
783 else if (format == GCRYMPI_FMT_USG)
784 {
785 unsigned int n = (nbits + 7)/8;
786
787 /* Note: We ignore the sign for this format. */
788 /* FIXME: for performance reasons we should put this into
789 mpi_aprint because we can then use the buffer directly. */
790
791 if (buffer && n > len)
792 return GPG_ERR_TOO_SHORT;
793 if (buffer)
794 {
795 unsigned char *tmp;
796
797 tmp = _gcry_mpi_get_buffer (a, 0, &n, NULL);
798 if (!tmp)
799 return gpg_err_code_from_syserror ();
800 memcpy (buffer, tmp, n);
801 xfree (tmp);
802 }
803 *nwritten = n;
804 return 0;
805 }
806 else if (format == GCRYMPI_FMT_PGP)
807 {
808 unsigned int n = (nbits + 7)/8;
809
810 /* The PGP format can only handle unsigned integers. */
811 if (negative)
812 return GPG_ERR_INV_ARG;
813
814 if (buffer && n+2 > len)
815 return GPG_ERR_TOO_SHORT;
816
817 if (buffer)
818 {
819 unsigned char *tmp;
820 unsigned char *s = buffer;
821
822 s[0] = nbits >> 8;
823 s[1] = nbits;
824
825 tmp = _gcry_mpi_get_buffer (a, 0, &n, NULL);
826 if (!tmp)
827 return gpg_err_code_from_syserror ();
828 memcpy (s+2, tmp, n);
829 xfree (tmp);
830 }
831 *nwritten = n+2;
832 return 0;
833 }
834 else if (format == GCRYMPI_FMT_SSH)
835 {
836 unsigned char *tmp;
837 int extra = 0;
838 unsigned int n;
839
840 tmp = _gcry_mpi_get_buffer (a, 0, &n, NULL);
841 if (!tmp)
842 return gpg_err_code_from_syserror ();
843
844 if (negative)
845 {
846 twocompl (tmp, n);
847 if (!(*tmp & 0x80))
848 {
849 /* Need to extend the sign. */
850 n++;
851 extra = 2;
852 }
853 }
854 else if (n && (*tmp & 0x80))
855 {
856 n++;
857 extra=1;
858 }
859
860 if (buffer && n+4 > len)
861 {
862 xfree(tmp);
863 return GPG_ERR_TOO_SHORT;
864 }
865
866 if (buffer)
867 {
868 unsigned char *s = buffer;
869
870 buf_put_be32 (s, n);
871 s += 4;
872 if (extra == 1)
873 *s++ = 0;
874 else if (extra)
875 *s++ = 0xff;
876 memcpy (s, tmp, n-!!extra);
877 }
878 xfree (tmp);
879 *nwritten = 4+n;
880 return 0;
881 }
882 else if (format == GCRYMPI_FMT_HEX)
883 {
884 unsigned char *tmp;
885 int i;
886 int extra = 0;
887 unsigned int n = 0;
888
889 tmp = _gcry_mpi_get_buffer (a, 0, &n, NULL);
890 if (!tmp)
891 return gpg_err_code_from_syserror ();
892 if (!n || (*tmp & 0x80))
893 extra = 2;
894
895 if (buffer && 2*n + extra + negative + 1 > len)
896 {
897 xfree(tmp);
898 return GPG_ERR_TOO_SHORT;
899 }
900 if (buffer)
901 {
902 static const u32 nibble2hex[] =
903 {
904 '0', '1', '2', '3', '4', '5', '6', '7',
905 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
906 };
907 unsigned char *s = buffer;
908
909 if (negative)
910 *s++ = '-';
911 if (extra)
912 {
913 *s++ = '0';
914 *s++ = '0';
915 }
916
917 for (i = 0; i + 4 < n; i += 4)
918 {
919 u32 c = buf_get_be32(tmp + i);
920 u32 o1, o2;
921
922 o1 = nibble2hex[(c >> 28) & 0xF];
923 o1 <<= 8;
924 o1 |= nibble2hex[(c >> 24) & 0xF];
925 o1 <<= 8;
926 o1 |= nibble2hex[(c >> 20) & 0xF];
927 o1 <<= 8;
928 o1 |= nibble2hex[(c >> 16) & 0xF];
929
930 o2 = nibble2hex[(c >> 12) & 0xF];
931 o2 <<= 8;
932 o2 |= (u64)nibble2hex[(c >> 8) & 0xF];
933 o2 <<= 8;
934 o2 |= (u64)nibble2hex[(c >> 4) & 0xF];
935 o2 <<= 8;
936 o2 |= (u64)nibble2hex[(c >> 0) & 0xF];
937
938 buf_put_be32 (s + 0, o1);
939 buf_put_be32 (s + 4, o2);
940 s += 8;
941 }
942 for (; i < n; i++)
943 {
944 unsigned int c = tmp[i];
945
946 *s++ = nibble2hex[c >> 4];
947 *s++ = nibble2hex[c & 0xF];
948 }
949 *s++ = 0;
950 *nwritten = s - buffer;
951 }
952 else
953 {
954 *nwritten = 2*n + extra + negative + 1;
955 }
956 xfree (tmp);
957 return 0;
958 }
959 else
960 return GPG_ERR_INV_ARG;
961 }
962
963
964 /*
965 * Like gcry_mpi_print but this function allocates the buffer itself.
966 * The caller has to supply the address of a pointer. NWRITTEN may be
967 * NULL.
968 */
969 gcry_err_code_t
970 _gcry_mpi_aprint (enum gcry_mpi_format format,
971 unsigned char **buffer, size_t *nwritten,
972 struct gcry_mpi *a)
973 {
974 size_t n;
975 gcry_err_code_t rc;
976
977 *buffer = NULL;
978 rc = _gcry_mpi_print (format, NULL, 0, &n, a);
979 if (rc)
980 return rc;
981
982 *buffer = mpi_is_secure(a) ? xtrymalloc_secure (n?n:1) : xtrymalloc (n?n:1);
983 if (!*buffer)
984 return gpg_err_code_from_syserror ();
985 /* If the returned buffer will have a length of 0, we nevertheless
986 allocated 1 byte (malloc needs it anyway) and store a 0. */
987 if (!n)
988 **buffer = 0;
989 rc = _gcry_mpi_print( format, *buffer, n, &n, a );
990 if (rc)
991 {
992 xfree (*buffer);
993 *buffer = NULL;
994 }
995 else if (nwritten)
996 *nwritten = n;
997 return rc;
998 }
999
1000
1001 /* Turn VALUE into an octet string and store it in an allocated buffer
1002 at R_FRAME or - if R_RAME is NULL - copy it into the caller
1003 provided buffer SPACE; either SPACE or R_FRAME may be used. If
1004 SPACE if not NULL, the caller must provide a buffer of at least
1005 NBYTES. If the resulting octet string is shorter than NBYTES pad
1006 it to the left with zeroes. If VALUE does not fit into NBYTES
1007 return an error code. */
1008 gpg_err_code_t
1009 _gcry_mpi_to_octet_string (unsigned char **r_frame, void *space,
1010 gcry_mpi_t value, size_t nbytes)
1011 {
1012 gpg_err_code_t rc;
1013 size_t nframe, noff, n;
1014 unsigned char *frame;
1015
1016 if (!r_frame == !space)
1017 return GPG_ERR_INV_ARG; /* Only one may be used. */
1018
1019 if (r_frame)
1020 *r_frame = NULL;
1021
1022 rc = _gcry_mpi_print (GCRYMPI_FMT_USG, NULL, 0, &nframe, value);
1023 if (rc)
1024 return rc;
1025 if (nframe > nbytes)
1026 return GPG_ERR_TOO_LARGE; /* Value too long to fit into NBYTES. */
1027
1028 noff = (nframe < nbytes)? nbytes - nframe : 0;
1029 n = nframe + noff;
1030 if (space)
1031 frame = space;
1032 else
1033 {
1034 frame = mpi_is_secure (value)? xtrymalloc_secure (n) : xtrymalloc (n);
1035 if (!frame)
1036 {
1037 rc = gpg_err_code_from_syserror ();
1038 return rc;
1039 }
1040 }
1041 if (noff)
1042 memset (frame, 0, noff);
1043 nframe += noff;
1044 rc = _gcry_mpi_print (GCRYMPI_FMT_USG, frame+noff, nframe-noff, NULL, value);
1045 if (rc)
1046 {
1047 xfree (frame);
1048 return rc;
1049 }
1050
1051 if (r_frame)
1052 *r_frame = frame;
1053 return 0;
1054 }