summaryrefslogtreecommitdiff
path: root/ecp/util/util.c
blob: ee51c73cdbdc06f045a78ed85d77ccf54b668ab3 (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 <sys/stat.h>

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

int ecp_util_key_save(ECPDHKey *key, char *filename) {
    int fd;
    ssize_t rv;

    if (!key->valid) return ECP_ERR;

    if ((fd = open(filename, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR)) < 0) return ECP_ERR;
    rv = write(fd, &key->public, sizeof(key->public));
    if (rv != sizeof(key->public)) {
        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(ECPDHKey *key, char *filename) {
    int fd;
    ssize_t rv;

    if ((fd = open(filename, O_RDONLY)) < 0) return ECP_ERR;
    rv = read(fd, &key->public, sizeof(key->public));
    if (rv != sizeof(key->public)) {
        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);

    key->valid = 1;
    return ECP_OK;
}

int ecp_util_node_save(ECPNode *node, char *filename) {
    int fd;
    ssize_t rv;

    if (!node->key_perma.valid) return ECP_ERR;

    if ((fd = open(filename, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR)) < 0) return ECP_ERR;
    rv = write(fd, &node->key_perma.public, sizeof(node->key_perma.public));
    if (rv != sizeof(node->key_perma.public)) {
        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(ECPNode *node, char *filename) {
    int fd;
    ssize_t rv;

    if ((fd = open(filename, O_RDONLY)) < 0) return ECP_ERR;
    rv = read(fd, &node->key_perma.public, sizeof(node->key_perma.public));
    if (rv != sizeof(node->key_perma.public)) {
        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);

    node->key_perma.valid = 1;
    return ECP_OK;
}