-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenkey.c
109 lines (89 loc) · 1.92 KB
/
genkey.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include <stdio.h>
#include <string.h>
#include <openssl/bn.h>
#include <openssl/ec.h>
#include "common.h"
/* Usage: genkey FILENAME
* Generate a key and write it to the file FILENAME. */
/* Interpret the 256 bits in buf as a private key and return an EC_KEY *. */
static EC_KEY *generate_key_from_buffer(const unsigned char buf[32])
{
EC_KEY *key;
BIGNUM *bn;
int rc;
key = NULL;
bn = NULL;
key = EC_KEY_new_by_curve_name(EC_GROUP_NID);
if (key == NULL)
goto err;
bn = BN_bin2bn(buf, 32, NULL);
if (bn == NULL)
goto err;
rc = EC_KEY_set_private_key(key, bn);
if (rc != 1)
goto err;
BN_free(bn);
return key;
err:
if (key != NULL)
EC_KEY_free(key);
if (bn != NULL)
BN_free(bn);
return NULL;
}
/* Generate a key using EC_KEY_generate_key. */
static EC_KEY *generate_key(void)
{
EC_KEY *key;
int rc;
key = EC_KEY_new_by_curve_name(EC_GROUP_NID);
if (key == NULL)
return NULL;
rc = EC_KEY_generate_key(key);
if (rc != 1) {
EC_KEY_free(key);
return NULL;
}
return key;
}
int main(int argc, char *argv[])
{
const char *filename;
EC_KEY *key;
int rc;
if (argc != 2) {
fprintf(stderr, "need an output filename\n");
exit(1);
}
filename = argv[1];
key = generate_key(); // THIS GENERATES A SECURE KEY!!!!!!
// unsigned char buf[32];
// int i;
// srand(1234);
// for (i = 0; i < 32; i++) {
// buf[i] = rand() & 0xff;
// }
// key = generate_key_from_buffer(buf);
// ABOVE GENERATES WEAK KEY!!!!
// time_t cur_time = 1443700800-1000;
// while(KEYNOTEQUAL) { //CORRECT THIS AS SOON AS I CAN?
// cur_time = 1443700800 + 1;
// unsigned char buf[32];
// int i;
// srand(cur_time);
// for (i = 0; i < 32; i++) {
// buf[i] = rand() & 0xff;
// }
// if (key == NULL) {
// fprintf(stderr, "error generating key\n");
// exit(1);
// }
// }
rc = key_write_filename(filename, key);
if (rc != 1) {
fprintf(stderr, "error saving key\n");
exit(1);
}
EC_KEY_free(key);
return 0;
}