xref: /freebsd/sys/contrib/libsodium/src/libsodium/crypto_stream/xchacha20/stream_xchacha20.c (revision 3611ec604864a7d4dcc9a3ea898c80eb35eef8a0)
1 
2 #include <stdlib.h>
3 
4 #include "crypto_core_hchacha20.h"
5 #include "crypto_stream_chacha20.h"
6 #include "crypto_stream_xchacha20.h"
7 #include "private/common.h"
8 #include "randombytes.h"
9 
10 size_t
crypto_stream_xchacha20_keybytes(void)11 crypto_stream_xchacha20_keybytes(void)
12 {
13     return crypto_stream_xchacha20_KEYBYTES;
14 }
15 
16 size_t
crypto_stream_xchacha20_noncebytes(void)17 crypto_stream_xchacha20_noncebytes(void)
18 {
19     return crypto_stream_xchacha20_NONCEBYTES;
20 }
21 
22 size_t
crypto_stream_xchacha20_messagebytes_max(void)23 crypto_stream_xchacha20_messagebytes_max(void)
24 {
25     return crypto_stream_xchacha20_MESSAGEBYTES_MAX;
26 }
27 
28 int
crypto_stream_xchacha20(unsigned char * c,unsigned long long clen,const unsigned char * n,const unsigned char * k)29 crypto_stream_xchacha20(unsigned char *c, unsigned long long clen,
30                         const unsigned char *n, const unsigned char *k)
31 {
32     unsigned char k2[crypto_core_hchacha20_OUTPUTBYTES];
33 
34     crypto_core_hchacha20(k2, n, k, NULL);
35     COMPILER_ASSERT(crypto_stream_chacha20_KEYBYTES <= sizeof k2);
36     COMPILER_ASSERT(crypto_stream_chacha20_NONCEBYTES ==
37                     crypto_stream_xchacha20_NONCEBYTES -
38                         crypto_core_hchacha20_INPUTBYTES);
39 
40     return crypto_stream_chacha20(c, clen, n + crypto_core_hchacha20_INPUTBYTES,
41                                   k2);
42 }
43 
44 int
crypto_stream_xchacha20_xor_ic(unsigned char * c,const unsigned char * m,unsigned long long mlen,const unsigned char * n,uint64_t ic,const unsigned char * k)45 crypto_stream_xchacha20_xor_ic(unsigned char *c, const unsigned char *m,
46                                unsigned long long mlen, const unsigned char *n,
47                                uint64_t ic, const unsigned char *k)
48 {
49     unsigned char k2[crypto_core_hchacha20_OUTPUTBYTES];
50 
51     crypto_core_hchacha20(k2, n, k, NULL);
52     return crypto_stream_chacha20_xor_ic(
53         c, m, mlen, n + crypto_core_hchacha20_INPUTBYTES, ic, k2);
54 }
55 
56 int
crypto_stream_xchacha20_xor(unsigned char * c,const unsigned char * m,unsigned long long mlen,const unsigned char * n,const unsigned char * k)57 crypto_stream_xchacha20_xor(unsigned char *c, const unsigned char *m,
58                             unsigned long long mlen, const unsigned char *n,
59                             const unsigned char *k)
60 {
61     return crypto_stream_xchacha20_xor_ic(c, m, mlen, n, 0U, k);
62 }
63 
64 void
crypto_stream_xchacha20_keygen(unsigned char k[crypto_stream_xchacha20_KEYBYTES])65 crypto_stream_xchacha20_keygen(
66     unsigned char k[crypto_stream_xchacha20_KEYBYTES])
67 {
68     randombytes_buf(k, crypto_stream_xchacha20_KEYBYTES);
69 }
70