-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathChaCha20.h
282 lines (247 loc) · 8.85 KB
/
ChaCha20.h
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
/**
* @file chacha20.h
* @brief ChaCha20 stream cipher implementation for Windows Kernel Drivers.
*
* This implementation provides a ChaCha20 encryption/decryption interface suitable for use
* within a Windows Kernel driver environment. It does not rely on user-mode functions or
* dynamic allocation. All functions are designed to operate at IRQL <= DISPATCH_LEVEL.
*
* The code follows the ChaCha20 specification described in RFC 8439.
*
* Reference: https://www.rfc-editor.org/rfc/rfc8439
*/
#include <ntifs.h>
#include <ntddk.h>
#pragma warning(push)
#pragma warning(disable: 4214)
#ifdef _MSC_VER
#pragma warning(disable: 4201)
#endif
/**
* @def CHACHA20_BLOCK_SIZE
* @brief The size of a single ChaCha20 block in bytes.
*/
#define CHACHA20_BLOCK_SIZE 64
/**
* @def CHACHA20_KEY_SIZE
* @brief The size of a ChaCha20 key in bytes (256-bit key).
*/
#define CHACHA20_KEY_SIZE 32
/**
* @def CHACHA20_NONCE_SIZE
* @brief The size of a ChaCha20 nonce (IV) in bytes.
*/
#define CHACHA20_NONCE_SIZE 12
/**
* @def CHACHA20_ROUNDS
* @brief Number of rounds in the ChaCha20 block function.
*
* RFC 8439 specifies 20 rounds.
*/
#define CHACHA20_ROUNDS 20
/**
* @struct CHACHA20_CONTEXT
* @brief Context structure holding ChaCha20 state.
*
* The context includes the key setup, initial block counter, and nonce.
* The state is initialized once and can be used to encrypt/decrypt multiple
* blocks by updating the counter as data is processed.
*/
typedef struct _CHACHA20_CONTEXT
{
ULONG State[16]; /**< Internal state words of the ChaCha20 cipher */
} CHACHA20_CONTEXT, * PCHACHA20_CONTEXT;
//
// Internal Functions (static) Prototypes
//
/**
* @brief Perform a ChaCha20 quarter round on four 32-bit words.
*
* @param a Reference to the first word.
* @param b Reference to the second word.
* @param c Reference to the third word.
* @param d Reference to the fourth word.
*/
static __forceinline VOID
ChaCha20QuarterRound(
_Inout_ ULONG* a,
_Inout_ ULONG* b,
_Inout_ ULONG* c,
_Inout_ ULONG* d
)
{
*a += *b; *d ^= *a; *d = _rotl(*d, 16);
*c += *d; *b ^= *c; *b = _rotl(*b, 12);
*a += *b; *d ^= *a; *d = _rotl(*d, 8);
*c += *d; *b ^= *c; *b = _rotl(*b, 7);
}
/**
* @brief Generate one 64-byte block of keystream from the internal state.
*
* This function takes the current state, performs the ChaCha20 rounds,
* and produces a 64-byte keystream block. The internal state should not
* be modified directly by this function; the caller increments the counter
* after processing a block as needed.
*
* @param ctx Pointer to a CHACHA20_CONTEXT initialized with a key, nonce, and counter.
* @param keystream Buffer of at least 64 bytes to receive the generated keystream.
*/
static __forceinline VOID
ChaCha20BlockFunction(
_In_ PCHACHA20_CONTEXT ctx,
_Out_writes_all_(CHACHA20_BLOCK_SIZE) PUCHAR keystream
)
{
ULONG workingState[16];
ULONG i;
for (i = 0; i < 16; i++)
{
workingState[i] = ctx->State[i];
}
for (i = 0; i < CHACHA20_ROUNDS; i += 2)
{
ChaCha20QuarterRound(&workingState[0], &workingState[4], &workingState[8], &workingState[12]);
ChaCha20QuarterRound(&workingState[1], &workingState[5], &workingState[9], &workingState[13]);
ChaCha20QuarterRound(&workingState[2], &workingState[6], &workingState[10], &workingState[14]);
ChaCha20QuarterRound(&workingState[3], &workingState[7], &workingState[11], &workingState[15]);
ChaCha20QuarterRound(&workingState[0], &workingState[5], &workingState[10], &workingState[15]);
ChaCha20QuarterRound(&workingState[1], &workingState[6], &workingState[11], &workingState[12]);
ChaCha20QuarterRound(&workingState[2], &workingState[7], &workingState[8], &workingState[13]);
ChaCha20QuarterRound(&workingState[3], &workingState[4], &workingState[9], &workingState[14]);
}
for (i = 0; i < 16; i++)
{
ULONG outWord = workingState[i] + ctx->State[i];
keystream[(i * 4) + 0] = (UCHAR)(outWord & 0xFF);
keystream[(i * 4) + 1] = (UCHAR)((outWord >> 8) & 0xFF);
keystream[(i * 4) + 2] = (UCHAR)((outWord >> 16) & 0xFF);
keystream[(i * 4) + 3] = (UCHAR)((outWord >> 24) & 0xFF);
}
}
/**
* @brief Increment the 64-bit block counter in the context.
*
* The counter is located at State[12] and State[13] in the ChaCha20 state.
* This function increments the block counter after each processed block.
*
* @param ctx Pointer to the CHACHA20_CONTEXT.
*/
static __forceinline VOID
ChaCha20IncrementCounter(
_Inout_ PCHACHA20_CONTEXT ctx
)
{
ctx->State[12]++;
if (ctx->State[12] == 0)
{
ctx->State[13]++;
}
}
//
// Public Funcs
//
/**
* @brief Initialize a ChaCha20 context with a given key, nonce, and initial block counter.
*
* This function sets up the state array from the given 256-bit key, 96-bit nonce,
* and 32-bit initial counter. The initial counter can be used to start encryption
* at a non-zero block index if desired.
*
* @param ctx Pointer to a CHACHA20_CONTEXT to initialize.
* @param key A 32-byte (256-bit) key.
* @param nonce A 12-byte (96-bit) nonce.
* @param initialCounter A 32-bit initial block counter, often starting at 0.
*
* @return NTSTATUS indicating success or failure.
*
* @retval STATUS_SUCCESS if the context is successfully initialized.
* @retval STATUS_INVALID_PARAMETER if any parameter is invalid.
*/
__forceinline
NTSTATUS
Chacha20Initialize(
PCHACHA20_CONTEXT ctx,
PCUCHAR key,
PCUCHAR nonce,
ULONG initialCounter
)
{
static UCHAR sigma[16] = { 0, };
__movsb(sigma, "expand 32-byte k", 16);
ULONG i;
if (ctx == NULL || key == NULL || nonce == NULL)
{
return STATUS_INVALID_PARAMETER;
}
ctx->State[0] = ((ULONG)sigma[0]) | ((ULONG)sigma[1] << 8) | ((ULONG)sigma[2] << 16) | ((ULONG)sigma[3] << 24);
ctx->State[1] = ((ULONG)sigma[4]) | ((ULONG)sigma[5] << 8) | ((ULONG)sigma[6] << 16) | ((ULONG)sigma[7] << 24);
ctx->State[2] = ((ULONG)sigma[8]) | ((ULONG)sigma[9] << 8) | ((ULONG)sigma[10] << 16) | ((ULONG)sigma[11] << 24);
ctx->State[3] = ((ULONG)sigma[12]) | ((ULONG)sigma[13] << 8) | ((ULONG)sigma[14] << 16) | ((ULONG)sigma[15] << 24);
for (i = 0; i < 8; i++)
{
ctx->State[4 + i] = ((ULONG)key[i * 4 + 0]) |
((ULONG)key[i * 4 + 1] << 8) |
((ULONG)key[i * 4 + 2] << 16) |
((ULONG)key[i * 4 + 3] << 24);
}
ctx->State[12] = initialCounter;
ctx->State[14] = ((ULONG)nonce[0]) | ((ULONG)nonce[1] << 8) | ((ULONG)nonce[2] << 16) | ((ULONG)nonce[3] << 24);
ctx->State[15] = ((ULONG)nonce[4]) | ((ULONG)nonce[5] << 8) | ((ULONG)nonce[6] << 16) | ((ULONG)nonce[7] << 24);
ctx->State[13] = ((ULONG)nonce[0]) | ((ULONG)nonce[1] << 8) | ((ULONG)nonce[2] << 16) | ((ULONG)nonce[3] << 24);
ctx->State[14] = ((ULONG)nonce[4]) | ((ULONG)nonce[5] << 8) | ((ULONG)nonce[6] << 16) | ((ULONG)nonce[7] << 24);
ctx->State[15] = ((ULONG)nonce[8]) | ((ULONG)nonce[9] << 8) | ((ULONG)nonce[10] << 16) | ((ULONG)nonce[11] << 24);
return STATUS_SUCCESS;
}
/**
* @brief Encrypt or decrypt data using the ChaCha20 cipher.
*
* ChaCha20 is a stream cipher; encryption and decryption are identical operations:
* ciphertext = plaintext XOR keystream
* plaintext = ciphertext XOR keystream
*
* This function will process a given buffer in place. The caller is responsible for
* ensuring the buffer is non-paged or locked in memory as necessary for kernel-level access.
*
* The context is updated as data is processed (the internal counter increments for each block).
* As a result, subsequent calls continue from where the previous call left off, allowing for
* large data streams to be processed incrementally.
*
* @param ctx Pointer to an initialized CHACHA20_CONTEXT.
* @param data Pointer to the data buffer to encrypt/decrypt in-place.
* @param dataLength Size of the data buffer in bytes.
*
* @return NTSTATUS indicating success or failure.
*
* @retval STATUS_SUCCESS if operation completed successfully.
* @retval STATUS_INVALID_PARAMETER if input parameters are invalid.
*/
__forceinline
NTSTATUS
Chacha20Crypt(
PCHACHA20_CONTEXT ctx,
PUCHAR data,
SIZE_T dataLength
)
{
UCHAR block[CHACHA20_BLOCK_SIZE];
SIZE_T offset = 0;
SIZE_T bytesToProcess;
if (ctx == NULL || data == NULL)
{
return STATUS_INVALID_PARAMETER;
}
while (offset < dataLength)
{
SIZE_T bytesRemaining = dataLength - offset;
bytesToProcess = (bytesRemaining < CHACHA20_BLOCK_SIZE) ? bytesRemaining : CHACHA20_BLOCK_SIZE;
ChaCha20BlockFunction(ctx, block);
for (SIZE_T i = 0; i < bytesToProcess; i++)
{
data[offset + i] ^= block[i];
}
ChaCha20IncrementCounter(ctx);
offset += bytesToProcess;
}
return STATUS_SUCCESS;
}
#pragma warning(pop)