2 * Copyright (c) 2022 Rubicon Communications, LLC.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at:
7 * http://www.apache.org/licenses/LICENSE-2.0
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
17 * chacha-merged.c version 20080118
22 #ifndef __included_wg_hchacha20_h__
23 #define __included_wg_hchacha20_h__
25 #include <vlib/vlib.h>
27 /* clang-format off */
28 #define U32C(v) (v##U)
29 #define U32V(v) ((u32)(v) & U32C(0xFFFFFFFF))
31 #define ROTL32(v, n) \
32 (U32V((v) << (n)) | ((v) >> (32 - (n))))
34 #define U8TO32_LITTLE(p) \
36 ((u32)((p)[1]) << 8) | \
37 ((u32)((p)[2]) << 16) | \
38 ((u32)((p)[3]) << 24))
40 #define ROTATE(v,c) (ROTL32(v,c))
41 #define XOR(v,w) ((v) ^ (w))
42 #define PLUS(v,w) (U32V((v) + (w)))
44 #define QUARTERROUND(a,b,c,d) \
45 a = PLUS(a,b); d = ROTATE(XOR(d,a),16); \
46 c = PLUS(c,d); b = ROTATE(XOR(b,c),12); \
47 a = PLUS(a,b); d = ROTATE(XOR(d,a), 8); \
48 c = PLUS(c,d); b = ROTATE(XOR(b,c), 7);
51 static const char sigma[16] = "expand 32-byte k";
54 hchacha20 (u32 derived_key[8], const u8 nonce[16], const u8 key[32])
57 u32 x[] = { U8TO32_LITTLE (sigma + 0), U8TO32_LITTLE (sigma + 4),
58 U8TO32_LITTLE (sigma + 8), U8TO32_LITTLE (sigma + 12),
59 U8TO32_LITTLE (key + 0), U8TO32_LITTLE (key + 4),
60 U8TO32_LITTLE (key + 8), U8TO32_LITTLE (key + 12),
61 U8TO32_LITTLE (key + 16), U8TO32_LITTLE (key + 20),
62 U8TO32_LITTLE (key + 24), U8TO32_LITTLE (key + 28),
63 U8TO32_LITTLE (nonce + 0), U8TO32_LITTLE (nonce + 4),
64 U8TO32_LITTLE (nonce + 8), U8TO32_LITTLE (nonce + 12) };
66 for (i = 20; i > 0; i -= 2)
68 QUARTERROUND (x[0], x[4], x[8], x[12])
69 QUARTERROUND (x[1], x[5], x[9], x[13])
70 QUARTERROUND (x[2], x[6], x[10], x[14])
71 QUARTERROUND (x[3], x[7], x[11], x[15])
72 QUARTERROUND (x[0], x[5], x[10], x[15])
73 QUARTERROUND (x[1], x[6], x[11], x[12])
74 QUARTERROUND (x[2], x[7], x[8], x[13])
75 QUARTERROUND (x[3], x[4], x[9], x[14])
78 clib_memcpy (derived_key + 0, x + 0, sizeof (u32) * 4);
79 clib_memcpy (derived_key + 4, x + 12, sizeof (u32) * 4);
82 #endif /* __included_wg_hchacha20_h__ */
85 * fd.io coding-style-patch-verification: ON
88 * eval: (c-set-style "gnu")