comparison libtommath/bn_mp_export.c @ 1436:60fc6476e044

Update to libtommath v1.0
author Matt Johnston <matt@ucc.asn.au>
date Sat, 24 Jun 2017 22:37:14 +0800
parents
children 8bba51a55704
comparison
equal deleted inserted replaced
1435:f849a5ca2efc 1436:60fc6476e044
1 #include <tommath_private.h>
2 #ifdef BN_MP_EXPORT_C
3 /* LibTomMath, multiple-precision integer library -- Tom St Denis
4 *
5 * LibTomMath is a library that provides multiple-precision
6 * integer arithmetic as well as number theoretic functionality.
7 *
8 * The library was designed directly after the MPI library by
9 * Michael Fromberger but has been written from scratch with
10 * additional optimizations in place.
11 *
12 * The library is free for all purposes without any express
13 * guarantee it works.
14 *
15 * Tom St Denis, [email protected], http://libtom.org
16 */
17
18 /* based on gmp's mpz_export.
19 * see http://gmplib.org/manual/Integer-Import-and-Export.html
20 */
21 int mp_export(void* rop, size_t* countp, int order, size_t size,
22 int endian, size_t nails, mp_int* op) {
23 int result;
24 size_t odd_nails, nail_bytes, i, j, bits, count;
25 unsigned char odd_nail_mask;
26
27 mp_int t;
28
29 if ((result = mp_init_copy(&t, op)) != MP_OKAY) {
30 return result;
31 }
32
33 if (endian == 0) {
34 union {
35 unsigned int i;
36 char c[4];
37 } lint;
38 lint.i = 0x01020304;
39
40 endian = (lint.c[0] == 4) ? -1 : 1;
41 }
42
43 odd_nails = (nails % 8);
44 odd_nail_mask = 0xff;
45 for (i = 0; i < odd_nails; ++i) {
46 odd_nail_mask ^= (1 << (7 - i));
47 }
48 nail_bytes = nails / 8;
49
50 bits = mp_count_bits(&t);
51 count = (bits / ((size * 8) - nails)) + (((bits % ((size * 8) - nails)) != 0) ? 1 : 0);
52
53 for (i = 0; i < count; ++i) {
54 for (j = 0; j < size; ++j) {
55 unsigned char* byte = (
56 (unsigned char*)rop +
57 (((order == -1) ? i : ((count - 1) - i)) * size) +
58 ((endian == -1) ? j : ((size - 1) - j))
59 );
60
61 if (j >= (size - nail_bytes)) {
62 *byte = 0;
63 continue;
64 }
65
66 *byte = (unsigned char)((j == ((size - nail_bytes) - 1)) ? (t.dp[0] & odd_nail_mask) : (t.dp[0] & 0xFF));
67
68 if ((result = mp_div_2d(&t, ((j == ((size - nail_bytes) - 1)) ? (8 - odd_nails) : 8), &t, NULL)) != MP_OKAY) {
69 mp_clear(&t);
70 return result;
71 }
72 }
73 }
74
75 mp_clear(&t);
76
77 if (countp != NULL) {
78 *countp = count;
79 }
80
81 return MP_OKAY;
82 }
83
84 #endif
85
86 /* $Source$ */
87 /* $Revision$ */
88 /* $Date$ */