-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrsa_gmp.c
96 lines (62 loc) · 1.65 KB
/
rsa_gmp.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/*
* $Id: rsa_gmp.c,v 1.2 2009/06/10 03:05:47 ahn Exp $
*
* This is the server-side RSA math support code that uses the GNU MP
* library. Berkeley MP is no longer supported. No crypto code is
* contained in this file.
*
* Originally written by Ray Jones. Updated by Dave Ahn.
* */
#include "config.h"
#include <gmp.h>
#include "rsa_gmp.h"
/* convert from unsigned char array to GMP form */
void raw_to_num(mpz_t out, const unsigned char *in, const int digits) {
int i;
mpz_t temp;
mpz_t twofiftysix;
mpz_t thisval;
mpz_init(temp);
mpz_init(twofiftysix);
mpz_init(thisval);
mpz_set_ui(temp, 0);
mpz_set_ui(twofiftysix, 256);
for (i=0; i<digits; i++) {
mpz_mul(temp, temp, twofiftysix);
mpz_set_ui(thisval, in[digits - i - 1]);
mpz_add(temp, temp, thisval);
}
mpz_set(out, temp);
mpz_clear(temp);
mpz_clear(twofiftysix);
mpz_clear(thisval);
}
/* convert from GMP form to unsigned char array */
void num_to_raw(unsigned char *out, mpz_t in, const int digits) {
/* note: mpz_t in overwritten */
int i;
unsigned long temp;
mpz_t zero;
mpz_init(zero);
mpz_set_ui(zero, 0);
for (i=0; i<digits; i++) {
if (!mpz_cmp(in, zero))
temp = 0;
else {
#if __GNU_MP_VERSION < 2
/* gmp 1 doesn't seem to have mpz_fdiv_q_ui that returns the
remainder in integer form. use fdiv_qr_ui and discard the
remainder */
mpz_t foo;
mpz_init(foo);
temp = mpz_fdiv_qr_ui(in, foo, in, 256);
mpz_clear(foo);
#else
/* gmp 2.x */
temp = mpz_fdiv_q_ui(in, in, 256);
#endif
}
out[i] = (unsigned char) temp & 0xFF;
}
mpz_clear(zero);
}