summaryrefslogtreecommitdiff
path: root/ecp/util/util.c
blob: abe562dedbc732ad7e8e2c7b35314dec62f6255d (plain)
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
#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"

int ecp_util_read_key(int fd, ecp_ecdh_public_t *public, ecp_ecdh_private_t *private) {
    char buffer[ECP_SIZE_ECDH_KEY_BUF];
    ssize_t rv;
    int _rv;

    memset(buffer, 0, sizeof(buffer));
    rv = read(fd, buffer, sizeof(buffer));
    if (rv < (ECP_SIZE_ECDH_KEY_BUF - 1)) return ECP_ERR;
    if (buffer[ECP_SIZE_ECDH_KEY_BUF - 1] == '\n') buffer[ECP_SIZE_ECDH_KEY_BUF - 1] = '\0';

    _rv = ecp_str2key((uint8_t *)public, buffer);
    if (_rv) return _rv;

    if (private) {
        memset(buffer, 0, sizeof(buffer));
        rv = read(fd, buffer, sizeof(buffer));
        if (rv < (ECP_SIZE_ECDH_KEY_BUF - 1)) return ECP_ERR;
        if (buffer[ECP_SIZE_ECDH_KEY_BUF - 1] == '\n') buffer[ECP_SIZE_ECDH_KEY_BUF - 1] = '\0';

        _rv = ecp_str2key((uint8_t *)private, buffer);
        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;
}