summaryrefslogtreecommitdiff
path: root/code/ecp/crypto/test/aead.c
blob: a2e0da7fc2a8f228cdab7c19406672bfaec8115b (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
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>

#include <crypto.h>
#include <curve25519.h>

#define NONCE_LEN   8
#define TAG_LEN     16
#define KEY_LEN     32

static int v_rng(void *buf, size_t bufsize) {
    int fd;
    
    if((fd = open("/dev/urandom", O_RDONLY)) < 0) return -1;
    size_t nb = read(fd, buf, bufsize);
    close(fd);
    if (nb != bufsize) return -1;
    return 0;
}

int main(int argc, char *argv[]) {
    unsigned char in_msg[1024];
    unsigned char out_msg[1024];
    size_t in_msg_len;
    size_t out_msg_len;
    int rv;
    unsigned char public1[KEY_LEN];
    unsigned char private1[KEY_LEN];
    unsigned char public2[KEY_LEN];
    unsigned char private2[KEY_LEN];
    unsigned char key1[KEY_LEN];
    unsigned char key2[KEY_LEN];
    unsigned char nonce[NONCE_LEN];

    strcpy((char *)in_msg, "PERA JE CAR!");
    in_msg_len = strlen((char *)in_msg) + 1;

    v_rng(nonce, NONCE_LEN);
    X25519_keypair(public1, private1, v_rng);
    X25519_keypair(public2, private2, v_rng);
    
    X25519(key1, private1, public2);
    rv = aead_chacha20_poly1305_seal(out_msg, &out_msg_len, 1024, key1, TAG_LEN, nonce, NONCE_LEN, in_msg, in_msg_len, NULL, 0);
    printf("SEAL RV:%d ILEN:%lu OLEN:%lu\n", rv, in_msg_len, out_msg_len);

    memset(in_msg, 0, sizeof(in_msg));

    X25519(key2, private2, public1);
    rv = aead_chacha20_poly1305_open(in_msg, &in_msg_len, 1024, key2, TAG_LEN, nonce, NONCE_LEN, out_msg, out_msg_len, NULL, 0);
    printf("OPEN RV:%d ILEN:%lu OLEN:%lu\n", rv, in_msg_len, out_msg_len);
    printf("MSG: %s\n", in_msg);
}