59int randomize(
unsigned char *buf,
size_t len);
72int main(
int argc,
char *argv[]) {
80 while ((opt = getopt(argc, argv,
"e:")) != EOF) {
86 fprintf(stderr,
"Usage: rsakey [-e <expt>] <modbits> [<outfile>]\n");
92 fprintf(stderr,
"Error: You must specify the number of modulus bits.\n");
93 fprintf(stderr,
"Usage: rsakey [-e <expt>] <modbits> [<outfile>]\n");
96 modbits = (int)strtol(argv[optind++], NULL, 0);
97 if (modbits < CHAR_BIT) {
98 fprintf(stderr,
"Error: Invalid value for number of modulus bits.\n");
101 if (modbits % 2 == 1) ++modbits;
105 if ((ofp = fopen(argv[optind],
"wt")) == NULL) {
107 "Error: Unable to open output file for writing.\n"
110 argv[optind], strerror(errno));
117 "Error initializing RSA key structure:\n"
127 "Error: Invalid value for encryption exponent.\n"
136 "Error: Unable to randomize first prime.\n"
141 fprintf(stderr,
"p: ");
146 "Error: Unable to randomize second prime.\n"
151 fprintf(stderr,
"\nq: ");
166 "Error: Unable to randomize encryption exponent.\n"
175 "Error: Unable to compute decryption exponent.\n"
182 "Error: Unable to re-randomize encryption exponent.\n"
202 FILE *rnd = fopen(
"/dev/random",
"rb");
205 if (rnd == NULL)
return -1;
207 nr = fread(buf,
sizeof(*buf), len, rnd);
214 mp_size n_bytes = (n_bits + CHAR_BIT - 1) / CHAR_BIT;
218 if ((buf = malloc(n_bytes)) == NULL)
return MP_MEMORY;
226 if (n_bits % CHAR_BIT != 0) {
227 unsigned char b_mask = (1 << (n_bits % CHAR_BIT)) - 1;
228 unsigned char t_mask = (1 << (n_bits % CHAR_BIT)) >> 1;
235 buf[n_bytes - 1] |= 1;
240 memset(buf, 0, n_bytes);
256 if (fb != NULL && (
count % 50) == 0) fputc(
'.', fb);
261 if (
res ==
MP_TRUE && fb != NULL) fputc(
'+', fb);
291 fprintf(ofp,
"p = %s\n", obuf);
293 fprintf(ofp,
"q = %s\n", obuf);
295 fprintf(ofp,
"e = %s\n", obuf);
297 fprintf(ofp,
"d = %s\n", obuf);
299 fprintf(ofp,
"n = %s\n", obuf);
static bool mp_int_is_even(mp_int z)
Reports whether z is even, having remainder 0 when divided by 2.
mp_result mp_int_is_prime(mp_int z)
static int count(int *con, unsigned len, int status)
int randomize(unsigned char *buf, size_t len)
mp_result mp_int_randomize(mp_int a, mp_size n_bits)
mp_result find_prime(mp_int seed, FILE *fb)
void rsa_key_clear(rsa_key *kp)
void rsa_key_write(rsa_key *kp, FILE *ofp)
mp_result rsa_key_init(rsa_key *kp)
#define mp_int_string_len
#define mp_int_read_string
#define mp_int_read_unsigned