1 #include "crypto_onetimeauth_poly1305.h"
2 #include "crypto_secretbox_xsalsa20poly1305.h"
3 #include "crypto_stream_xsalsa20.h"
4 #include "randombytes.h"
5
6 int
crypto_secretbox_xsalsa20poly1305(unsigned char * c,const unsigned char * m,unsigned long long mlen,const unsigned char * n,const unsigned char * k)7 crypto_secretbox_xsalsa20poly1305(unsigned char *c, const unsigned char *m,
8 unsigned long long mlen,
9 const unsigned char *n,
10 const unsigned char *k)
11 {
12 int i;
13
14 if (mlen < 32) {
15 return -1;
16 }
17 crypto_stream_xsalsa20_xor(c, m, mlen, n, k);
18 crypto_onetimeauth_poly1305(c + 16, c + 32, mlen - 32, c);
19 for (i = 0; i < 16; ++i) {
20 c[i] = 0;
21 }
22 return 0;
23 }
24
25 int
crypto_secretbox_xsalsa20poly1305_open(unsigned char * m,const unsigned char * c,unsigned long long clen,const unsigned char * n,const unsigned char * k)26 crypto_secretbox_xsalsa20poly1305_open(unsigned char *m, const unsigned char *c,
27 unsigned long long clen,
28 const unsigned char *n,
29 const unsigned char *k)
30 {
31 unsigned char subkey[32];
32 int i;
33
34 if (clen < 32) {
35 return -1;
36 }
37 crypto_stream_xsalsa20(subkey, 32, n, k);
38 if (crypto_onetimeauth_poly1305_verify(c + 16, c + 32,
39 clen - 32, subkey) != 0) {
40 return -1;
41 }
42 crypto_stream_xsalsa20_xor(m, c, clen, n, k);
43 for (i = 0; i < 32; ++i) {
44 m[i] = 0;
45 }
46 return 0;
47 }
48
49 size_t
crypto_secretbox_xsalsa20poly1305_keybytes(void)50 crypto_secretbox_xsalsa20poly1305_keybytes(void)
51 {
52 return crypto_secretbox_xsalsa20poly1305_KEYBYTES;
53 }
54
55 size_t
crypto_secretbox_xsalsa20poly1305_noncebytes(void)56 crypto_secretbox_xsalsa20poly1305_noncebytes(void)
57 {
58 return crypto_secretbox_xsalsa20poly1305_NONCEBYTES;
59 }
60
61 size_t
crypto_secretbox_xsalsa20poly1305_zerobytes(void)62 crypto_secretbox_xsalsa20poly1305_zerobytes(void)
63 {
64 return crypto_secretbox_xsalsa20poly1305_ZEROBYTES;
65 }
66
67 size_t
crypto_secretbox_xsalsa20poly1305_boxzerobytes(void)68 crypto_secretbox_xsalsa20poly1305_boxzerobytes(void)
69 {
70 return crypto_secretbox_xsalsa20poly1305_BOXZEROBYTES;
71 }
72
73 size_t
crypto_secretbox_xsalsa20poly1305_macbytes(void)74 crypto_secretbox_xsalsa20poly1305_macbytes(void)
75 {
76 return crypto_secretbox_xsalsa20poly1305_MACBYTES;
77 }
78
79 size_t
crypto_secretbox_xsalsa20poly1305_messagebytes_max(void)80 crypto_secretbox_xsalsa20poly1305_messagebytes_max(void)
81 {
82 return crypto_secretbox_xsalsa20poly1305_MESSAGEBYTES_MAX;
83 }
84
85 void
crypto_secretbox_xsalsa20poly1305_keygen(unsigned char k[crypto_secretbox_xsalsa20poly1305_KEYBYTES])86 crypto_secretbox_xsalsa20poly1305_keygen(unsigned char k[crypto_secretbox_xsalsa20poly1305_KEYBYTES])
87 {
88 randombytes_buf(k, crypto_secretbox_xsalsa20poly1305_KEYBYTES);
89 }
90