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 <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <ecp/core.h>
#include <ecp/cr.h>
#include "util.h"
static int _read_key(int fd, uint8_t *key) {
char buffer[ECP_SIZE_ECDH_KEY_BUF];
char ch;
int cmt;
ssize_t rv;
int _rv;
do {
cmt = 0;
rv = read(fd, &ch, 1);
if (rv != 1) return ECP_ERR;
switch (ch) {
case '#':
case '\n': {
cmt = 1;
while (ch != '\n') {
rv = read(fd, &ch, 1);
if (rv != 1) return ECP_ERR;
}
break;
}
default: {
buffer[0] = ch;
break;
}
}
} while(cmt);
rv = read(fd, buffer + 1, sizeof(buffer) - 2);
if (rv < (sizeof(buffer) - 2)) return ECP_ERR;
buffer[ECP_SIZE_ECDH_KEY_BUF - 1] = '\0';
do {
rv = read(fd, &ch, 1);
} while ((rv == 1) && (ch != '\n'));
_rv = ecp_str2key(key, buffer);
return _rv;
}
int ecp_util_read_key(int fd, ecp_ecdh_public_t *public, ecp_ecdh_private_t *private) {
int rv;
rv = _read_key(fd, (uint8_t *)public);
if (rv) return rv;
if (private) {
rv = _read_key(fd, (uint8_t *)private);
if (rv) return rv;
}
return ECP_OK;
}
int ecp_util_write_key(int fd, ecp_ecdh_public_t *public, ecp_ecdh_private_t *private) {
char buffer[ECP_SIZE_ECDH_KEY_BUF];
ssize_t rv;
ecp_key2str(buffer, (uint8_t *)public);
buffer[ECP_SIZE_ECDH_KEY_BUF - 1] = '\n';
rv = write(fd, buffer, sizeof(buffer));
if (rv != sizeof(buffer)) return ECP_ERR;
if (private) {
ecp_key2str(buffer, (uint8_t *)private);
buffer[ECP_SIZE_ECDH_KEY_BUF - 1] = '\n';
rv = write(fd, buffer, sizeof(buffer));
if (rv != sizeof(buffer)) return ECP_ERR;
}
return ECP_OK;
}
int ecp_util_load_key(char *filename, ecp_ecdh_public_t *public, ecp_ecdh_private_t *private) {
int rv, fd;
if ((fd = open(filename, O_RDONLY)) < 0) return ECP_ERR;
rv = ecp_util_read_key(fd, public, private);
close(fd);
return rv;
}
int ecp_util_save_key(char *filename, ecp_ecdh_public_t *public, ecp_ecdh_private_t *private) {
int rv, fd;
if ((fd = open(filename, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR)) < 0) return ECP_ERR;
rv = ecp_util_write_key(fd, public, private);
close(fd);
return rv;
}
|