summaryrefslogtreecommitdiff
path: root/libs/libsodium/src/crypto_secretbox/xsalsa20poly1305/secretbox_xsalsa20poly1305.c
blob: 7240050dfd1536215e4918d02c00109b69a57a63 (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
#include "crypto_onetimeauth_poly1305.h"
#include "crypto_secretbox_xsalsa20poly1305.h"
#include "crypto_stream_xsalsa20.h"
#include "randombytes.h"

int
crypto_secretbox_xsalsa20poly1305(unsigned char *c, const unsigned char *m,
                                  unsigned long long mlen,
                                  const unsigned char *n,
                                  const unsigned char *k)
{
    int i;

    if (mlen < 32) {
        return -1;
    }
    crypto_stream_xsalsa20_xor(c, m, mlen, n, k);
    crypto_onetimeauth_poly1305(c + 16, c + 32, mlen - 32, c);
    for (i = 0; i < 16; ++i) {
        c[i] = 0;
    }
    return 0;
}

int
crypto_secretbox_xsalsa20poly1305_open(unsigned char *m, const unsigned char *c,
                                       unsigned long long clen,
                                       const unsigned char *n,
                                       const unsigned char *k)
{
    unsigned char subkey[32];
    int           i;

    if (clen < 32) {
        return -1;
    }
    crypto_stream_xsalsa20(subkey, 32, n, k);
    if (crypto_onetimeauth_poly1305_verify(c + 16, c + 32,
                                           clen - 32, subkey) != 0) {
        return -1;
    }
    crypto_stream_xsalsa20_xor(m, c, clen, n, k);
    for (i = 0; i < 32; ++i) {
        m[i] = 0;
    }
    return 0;
}

size_t
crypto_secretbox_xsalsa20poly1305_keybytes(void)
{
    return crypto_secretbox_xsalsa20poly1305_KEYBYTES;
}

size_t
crypto_secretbox_xsalsa20poly1305_noncebytes(void)
{
    return crypto_secretbox_xsalsa20poly1305_NONCEBYTES;
}

size_t
crypto_secretbox_xsalsa20poly1305_zerobytes(void)
{
    return crypto_secretbox_xsalsa20poly1305_ZEROBYTES;
}

size_t
crypto_secretbox_xsalsa20poly1305_boxzerobytes(void)
{
    return crypto_secretbox_xsalsa20poly1305_BOXZEROBYTES;
}

size_t
crypto_secretbox_xsalsa20poly1305_macbytes(void)
{
    return crypto_secretbox_xsalsa20poly1305_MACBYTES;
}

size_t
crypto_secretbox_xsalsa20poly1305_messagebytes_max(void)
{
    return crypto_secretbox_xsalsa20poly1305_MESSAGEBYTES_MAX;
}

void
crypto_secretbox_xsalsa20poly1305_keygen(unsigned char k[crypto_secretbox_xsalsa20poly1305_KEYBYTES])
{
    randombytes_buf(k, crypto_secretbox_xsalsa20poly1305_KEYBYTES);
}