Skip to content

Commit 2f04e81

Browse files
authored
Add ChaCha20 stream cipher (#7754)
* Add ChaCha20 stream cipher This implementation is intended for educational purposes and should not be used as a replacement for a vetted cryptographic library in production. * Test ChaCha20 implementation * Add test for ChaCha20 handling partial blocks * Refactor CONSTANTS and littleEndianInt method * Refactor ChaCha20Test for clarity and readability Refactored nonce and expected byte array initialization for clarity. Updated test methods to improve readability by reducing line breaks.
1 parent e9957ea commit 2f04e81

2 files changed

Lines changed: 228 additions & 0 deletions

File tree

Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
1+
package com.thealgorithms.ciphers;
2+
3+
import java.util.Objects;
4+
5+
/**
6+
* Implements the ChaCha20 stream cipher described in RFC 8439.
7+
*
8+
* <p>This implementation is intended for educational purposes and should not
9+
* be used as a replacement for a vetted cryptographic library in production.
10+
*
11+
* @see <a href="https://www.rfc-editor.org/rfc/rfc8439.html">RFC 8439</a>
12+
*/
13+
public final class ChaCha20 {
14+
15+
private static final int BLOCK_SIZE = 64;
16+
private static final long MAX_COUNTER = 0xFFFF_FFFFL;
17+
private static final int[] CONSTANTS = {0x61707865, 0x3320646e, 0x79622d32, 0x6b206574};
18+
19+
private ChaCha20() {
20+
// Utility class
21+
}
22+
23+
/**
24+
* Encrypts bytes with ChaCha20. Decryption uses the same operation.
25+
*
26+
* @param input plaintext bytes; must not be {@code null}
27+
* @param key 32-byte key
28+
* @param nonce 12-byte nonce
29+
* @param initialCounter unsigned 32-bit initial block counter
30+
* @return encrypted bytes
31+
* @throws NullPointerException if an argument is {@code null}
32+
* @throws IllegalArgumentException if a key, nonce, or counter is invalid,
33+
* or the counter would overflow while processing the input
34+
*/
35+
public static byte[] encrypt(byte[] input, byte[] key, byte[] nonce, long initialCounter) {
36+
validateInputs(input, key, nonce, initialCounter);
37+
38+
long blockCount = (input.length + (long) BLOCK_SIZE - 1) / BLOCK_SIZE;
39+
if (blockCount > 0 && initialCounter > MAX_COUNTER - (blockCount - 1)) {
40+
throw new IllegalArgumentException("Counter would overflow");
41+
}
42+
43+
byte[] output = new byte[input.length];
44+
for (int offset = 0; offset < input.length; offset += BLOCK_SIZE) {
45+
long counter = initialCounter + offset / BLOCK_SIZE;
46+
byte[] keyStream = block(key, nonce, counter);
47+
int bytesToProcess = Math.min(BLOCK_SIZE, input.length - offset);
48+
49+
for (int i = 0; i < bytesToProcess; i++) {
50+
output[offset + i] = (byte) (input[offset + i] ^ keyStream[i]);
51+
}
52+
}
53+
return output;
54+
}
55+
56+
/**
57+
* Decrypts bytes with ChaCha20. This is identical to encryption.
58+
*
59+
* @param input ciphertext bytes; must not be {@code null}
60+
* @param key 32-byte key
61+
* @param nonce 12-byte nonce
62+
* @param initialCounter unsigned 32-bit initial block counter
63+
* @return decrypted bytes
64+
*/
65+
public static byte[] decrypt(byte[] input, byte[] key, byte[] nonce, long initialCounter) {
66+
return encrypt(input, key, nonce, initialCounter);
67+
}
68+
69+
private static void validateInputs(byte[] input, byte[] key, byte[] nonce, long counter) {
70+
Objects.requireNonNull(input, "input must not be null");
71+
Objects.requireNonNull(key, "key must not be null");
72+
Objects.requireNonNull(nonce, "nonce must not be null");
73+
74+
if (key.length != 32) {
75+
throw new IllegalArgumentException("Key must be 32 bytes");
76+
}
77+
if (nonce.length != 12) {
78+
throw new IllegalArgumentException("Nonce must be 12 bytes");
79+
}
80+
if (counter < 0 || counter > MAX_COUNTER) {
81+
throw new IllegalArgumentException("Counter must be an unsigned 32-bit value");
82+
}
83+
}
84+
85+
private static byte[] block(byte[] key, byte[] nonce, long counter) {
86+
int[] state = new int[16];
87+
System.arraycopy(CONSTANTS, 0, state, 0, CONSTANTS.length);
88+
89+
for (int i = 0; i < 8; i++) {
90+
state[4 + i] = littleEndianInt(key, i * 4);
91+
}
92+
93+
state[12] = (int) counter;
94+
state[13] = littleEndianInt(nonce, 0);
95+
state[14] = littleEndianInt(nonce, 4);
96+
state[15] = littleEndianInt(nonce, 8);
97+
98+
int[] workingState = state.clone();
99+
for (int i = 0; i < 10; i++) {
100+
quarterRound(workingState, 0, 4, 8, 12);
101+
quarterRound(workingState, 1, 5, 9, 13);
102+
quarterRound(workingState, 2, 6, 10, 14);
103+
quarterRound(workingState, 3, 7, 11, 15);
104+
105+
quarterRound(workingState, 0, 5, 10, 15);
106+
quarterRound(workingState, 1, 6, 11, 12);
107+
quarterRound(workingState, 2, 7, 8, 13);
108+
quarterRound(workingState, 3, 4, 9, 14);
109+
}
110+
111+
byte[] output = new byte[BLOCK_SIZE];
112+
for (int i = 0; i < workingState.length; i++) {
113+
int word = workingState[i] + state[i];
114+
output[i * 4] = (byte) word;
115+
output[i * 4 + 1] = (byte) (word >>> 8);
116+
output[i * 4 + 2] = (byte) (word >>> 16);
117+
output[i * 4 + 3] = (byte) (word >>> 24);
118+
}
119+
return output;
120+
}
121+
122+
static void quarterRound(int[] state, int a, int b, int c, int d) {
123+
state[a] += state[b];
124+
state[d] = Integer.rotateLeft(state[d] ^ state[a], 16);
125+
state[c] += state[d];
126+
state[b] = Integer.rotateLeft(state[b] ^ state[c], 12);
127+
state[a] += state[b];
128+
state[d] = Integer.rotateLeft(state[d] ^ state[a], 8);
129+
state[c] += state[d];
130+
state[b] = Integer.rotateLeft(state[b] ^ state[c], 7);
131+
}
132+
133+
private static int littleEndianInt(byte[] bytes, int offset) {
134+
return (bytes[offset] & 0xFF) | ((bytes[offset + 1] & 0xFF) << 8) | ((bytes[offset + 2] & 0xFF) << 16) | ((bytes[offset + 3] & 0xFF) << 24);
135+
}
136+
}
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
package com.thealgorithms.ciphers;
2+
3+
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
4+
import static org.junit.jupiter.api.Assertions.assertThrows;
5+
6+
import org.junit.jupiter.api.Test;
7+
8+
class ChaCha20Test {
9+
10+
@Test
11+
void quarterRoundMatchesRfc8439Vector() {
12+
int[] state = {0x11111111, 0x01020304, 0x9b8d6f43, 0x01234567};
13+
14+
ChaCha20.quarterRound(state, 0, 1, 2, 3);
15+
16+
assertArrayEquals(new int[] {0xea2a92f4, 0xcb1cf8ce, 0x4581472e, 0x5881c4bb}, state);
17+
}
18+
19+
@Test
20+
void encryptingZeroesMatchesRfc8439BlockVector() {
21+
byte[] key = new byte[32];
22+
for (int i = 0; i < key.length; i++) {
23+
key[i] = (byte) i;
24+
}
25+
26+
byte[] nonce = {0, 0, 0, 9, 0, 0, 0, 0x4a, 0, 0, 0, 0};
27+
byte[] expected = {0x10, (byte) 0xf1, (byte) 0xe7, (byte) 0xe4, (byte) 0xd1, 0x3b, 0x59, 0x15, 0x50, 0x0f, (byte) 0xdd, 0x1f, (byte) 0xa3, 0x20, 0x71, (byte) 0xc4, (byte) 0xc7, (byte) 0xd1, (byte) 0xf4, (byte) 0xc7, 0x33, (byte) 0xc0, 0x68, 0x03, 0x04, 0x22, (byte) 0xaa, (byte) 0x9a,
28+
(byte) 0xc3, (byte) 0xd4, 0x6c, 0x4e, (byte) 0xd2, (byte) 0x82, 0x64, 0x46, 0x07, (byte) 0x9f, (byte) 0xaa, 0x09, 0x14, (byte) 0xc2, (byte) 0xd7, 0x05, (byte) 0xd9, (byte) 0x8b, 0x02, (byte) 0xa2, (byte) 0xb5, 0x12, (byte) 0x9c, (byte) 0xd1, (byte) 0xde, 0x16, 0x4e, (byte) 0xb9,
29+
(byte) 0xcb, (byte) 0xd0, (byte) 0x83, (byte) 0xe8, (byte) 0xa2, 0x50, 0x3c, 0x4e};
30+
31+
byte[] actual = ChaCha20.encrypt(new byte[64], key, nonce, 1);
32+
33+
assertArrayEquals(expected, actual);
34+
}
35+
36+
@Test
37+
void decryptRestoresInputAcrossMultipleBlocks() {
38+
byte[] input = new byte[130];
39+
for (int i = 0; i < input.length; i++) {
40+
input[i] = (byte) (i * 3);
41+
}
42+
43+
byte[] key = new byte[32];
44+
byte[] nonce = new byte[12];
45+
46+
byte[] encrypted = ChaCha20.encrypt(input, key, nonce, 7);
47+
byte[] decrypted = ChaCha20.decrypt(encrypted, key, nonce, 7);
48+
49+
assertArrayEquals(input, decrypted);
50+
}
51+
52+
@Test
53+
void handlesPartialBlocksAroundBlockBoundary() {
54+
for (int length : new int[] {1, 63, 65}) {
55+
byte[] input = new byte[length];
56+
for (int i = 0; i < input.length; i++) {
57+
input[i] = (byte) (i + 1);
58+
}
59+
60+
byte[] key = new byte[32];
61+
byte[] nonce = new byte[12];
62+
byte[] encrypted = ChaCha20.encrypt(input, key, nonce, 0);
63+
64+
assertArrayEquals(input, ChaCha20.decrypt(encrypted, key, nonce, 0));
65+
}
66+
}
67+
68+
@Test
69+
void emptyInputReturnsEmptyOutput() {
70+
assertArrayEquals(new byte[0], ChaCha20.encrypt(new byte[0], new byte[32], new byte[12], 1));
71+
}
72+
73+
@Test
74+
void maximumCounterCanProcessOneBlock() {
75+
byte[] input = new byte[64];
76+
77+
assertArrayEquals(input, ChaCha20.decrypt(ChaCha20.encrypt(input, new byte[32], new byte[12], 0xFFFF_FFFFL), new byte[32], new byte[12], 0xFFFF_FFFFL));
78+
}
79+
80+
@Test
81+
void counterOverflowIsRejected() {
82+
assertThrows(IllegalArgumentException.class, () -> ChaCha20.encrypt(new byte[65], new byte[32], new byte[12], 0xFFFF_FFFFL));
83+
}
84+
85+
@Test
86+
void invalidKeyNonceAndCounterAreRejected() {
87+
assertThrows(IllegalArgumentException.class, () -> ChaCha20.encrypt(new byte[1], new byte[31], new byte[12], 0));
88+
assertThrows(IllegalArgumentException.class, () -> ChaCha20.encrypt(new byte[1], new byte[32], new byte[11], 0));
89+
assertThrows(IllegalArgumentException.class, () -> ChaCha20.encrypt(new byte[1], new byte[32], new byte[12], -1));
90+
assertThrows(IllegalArgumentException.class, () -> ChaCha20.encrypt(new byte[1], new byte[32], new byte[12], 0x1_0000_0000L));
91+
}
92+
}

0 commit comments

Comments
 (0)