summaryrefslogtreecommitdiff
path: root/code/util/util.c
blob: 4f4adc2fd6714264cae4d42202110d283f973f71 (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
81
82
83
84
85
86
87
88
89
90
91
92
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>

#include "core.h"
#include "cr.h"
#include "util.h"

int ecp_util_key_save(ECPContext *ctx, ECPDHKey *key, char *filename) {
    int fd;
    ssize_t rv;
    
    if ((fd = open(filename, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR)) < 0) return ECP_ERR;
    rv = write(fd, ecp_cr_dh_pub_get_buf(&key->public), ECP_ECDH_SIZE_KEY);
    if (rv != ECP_ECDH_SIZE_KEY) {
        close(fd);
        return ECP_ERR;
    }
    rv = write(fd, &key->private, sizeof(key->private));
    if (rv != sizeof(key->private)) {
        close(fd);
        return ECP_ERR;
    }
    close(fd);
    return ECP_OK;
}

int ecp_util_key_load(ECPContext *ctx, ECPDHKey *key, char *filename) {
    int fd;
    ssize_t rv;
    unsigned char buf[ECP_ECDH_SIZE_KEY];
    
    if ((fd = open(filename, O_RDONLY)) < 0) return ECP_ERR;
    rv = read(fd, buf, ECP_ECDH_SIZE_KEY);
    if (rv != ECP_ECDH_SIZE_KEY) {
        close(fd);
        return ECP_ERR;
    }
    rv = read(fd, &key->private, sizeof(key->private));
    if (rv != sizeof(key->private)) {
        close(fd);
        return ECP_ERR;
    }
    close(fd);

    ecp_cr_dh_pub_from_buf(&key->public, buf);
    
    key->valid = 1;
    return ECP_OK;
}

int ecp_util_node_save(ECPContext *ctx, ECPNode *node, char *filename) {
    int fd;
    ssize_t rv;
    
    if ((fd = open(filename, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR)) < 0) return ECP_ERR;
    rv = write(fd, ecp_cr_dh_pub_get_buf(&node->public), ECP_ECDH_SIZE_KEY);
    if (rv != ECP_ECDH_SIZE_KEY) {
        close(fd);
        return ECP_ERR;
    }
    rv = write(fd, &node->addr, sizeof(node->addr));
    if (rv != sizeof(node->addr)) {
        close(fd);
        return ECP_ERR;
    }
    close(fd);
    return ECP_OK;
}

int ecp_util_node_load(ECPContext *ctx, ECPNode *node, char *filename) {
    int fd;
    ssize_t rv;
    unsigned char buf[ECP_ECDH_SIZE_KEY];
    
    if ((fd = open(filename, O_RDONLY)) < 0) return ECP_ERR;
    rv = read(fd, buf, ECP_ECDH_SIZE_KEY);
    if (rv != ECP_ECDH_SIZE_KEY) {
        close(fd);
        return ECP_ERR;
    }
    rv = read(fd, &node->addr, sizeof(node->addr));
    if (rv != sizeof(node->addr)) {
        close(fd);
        return ECP_ERR;
    }
    close(fd);

    ecp_cr_dh_pub_from_buf(&node->public, buf);

    return ECP_OK;
}