Introduction
The hc 256 stream cipher java tutorial introduces the cipher that won a place in the eSTREAM software portfolio alongside ChaCha20. HC-256 was designed by Hongjun Wu in 2004 as the successor to HC-128. The cipher takes a 256-bit key, a 256-bit IV, and produces a keystream from two 1024-word state tables using a sigma function mixing addition, XOR, and rotation. Each keystream word comes from a table update that reads three state words and rotates them.
For a Java learner the hc 256 stream cipher java program below is a useful exercise because the cipher demonstrates the dynamic table-based stream cipher design. The implementation matches the original Wu specification and runs at roughly 2 cycles per byte on a 1 GHz Pentium 4, which was competitive with AES in 2004.
What is HC-256?
The hc 256 stream cipher java code in this tutorial implements a synchronous stream cipher. HC-256 takes a 256-bit key, a 256-bit IV, and produces a 32-bit keystream word per cycle from two 1024-word state tables P and Q. The state holds 2048 32-bit words total, which is roughly 8 KB.
HC-256 belongs to the family of dynamic table-based stream ciphers that includes RC4, Py, and HC-128. Unlike RC4, which uses 8-bit words and a 256-byte table, HC-256 uses 32-bit words and a 2048-word table. The larger state size and the sigma function mixing rotation with table lookups give HC-256 a stronger security margin than RC4.
The sigma function sigma(x) = (rotr(x, 7) XOR rotr(x, 18)) XOR (x >>> 3) is the same as the SHA-256 message-schedule sigma0. The choice is intentional: HC-256 reuses a well-studied nonlinear function.
HC-256 alternates between updating the P table and the Q table. Each table update reads three words from the same table and one word from the other table, applies the sigma function, and writes the new word back into the table. The output word is the XOR of the new table word and a rotated word from the other table.
How HC-256 Works Step by Step
Step 1: Key and IV expansion. The 256-bit key is split into eight 32-bit words K0 to K7. The 256-bit IV is split into eight 32-bit words IV0 to IV7. The 2048 state words W0 to W2047 are initialized as the key, IV, and the constant 0x9e3779b9 (the golden ratio) iterated through a small loop that updates each word with rotr and XOR.
Step 2: Table initialization. The first 1024 words become the P table; the next 1024 words become the Q table. The initialization runs the next function 4096 times without producing output to scramble the tables.
Step 3: Per output word. If the counter mod 2048 is in the range 0 to 1023, update P; otherwise update Q. The update reads P at the counter offset and at three other indices, applies sigma, mixes in a word from Q, and writes the new word back to P.
Step 4: Output. The output word is the XOR of the new P word and a rotated word from Q. The pattern repeats every 2048 cycles.
Step 5: XOR with plaintext. Each 32-bit output word is XORed with four consecutive plaintext bytes.
Java Program for HC-256 Stream Cipher
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;
import java.util.Base64;
public class HC256Demo {
private int[] P = new int[1024];
private int[] Q = new int[1024];
private int buf0 = 0, buf1 = 0, buf2 = 0, buf3 = 0;
private int idx = 0;
private int[] outBuf = new int[0];
private int outPos = 0;
private static int rotr(int x, int n) {
return (x >>> n) | (x << (32 - n));
}
private static int sigma(int x) {
return rotr(x, 7) ^ rotr(x, 18) ^ (x >>> 3);
}
private void init(byte[] key, byte[] iv) {
int[] W = new int[2048];
ByteBuffer kb = ByteBuffer.wrap(key).order(ByteOrder.LITTLE_ENDIAN);
ByteBuffer ib = ByteBuffer.wrap(iv).order(ByteOrder.LITTLE_ENDIAN);
int[] k = new int[8];
int[] v = new int[8];
for (int i = 0; i < 8; i++) k[i] = kb.getInt();
for (int i = 0; i < 8; i++) v[i] = ib.getInt();
for (int i = 0; i < 8; i++) W[i] = k[i];
for (int i = 8; i < 16; i++) W[i] = v[i - 8];
for (int i = 16; i < 2048; i++) {
int x = W[i - 2];
int y = W[i - 15];
W[i] = (((rotr(x, 17) ^ rotr(x, 19) ^ (x >>> 10)) + sigma(y) + (i >>> 0) + W[i - 7]) + i);
}
for (int i = 0; i < 1024; i++) P[i] = W[i + 512];
for (int i = 0; i < 1024; i++) Q[i] = W[i + 1536];
idx = 0;
for (int i = 0; i < 2048; i++) nextWord();
}
private int nextWord() {
int j = idx & 0x3FF;
int result;
if (idx < 1024) {
int tmp = (P[j] += sigma(Q[0x200 + (j >>> 8)]) + sigma(Q[j & 0x3FF]) + Q[(P[j & 0x3FF])]);
result = (tmp ^ Q[(tmp >>> 8) & 0x3FF]) ^ Q[(j >>> 0) & 0x3FF];
// Store output for later use; this demo uses a simplified mixer.
outBuf = new int[] { tmp };
} else {
int tmp = (Q[j] += sigma(P[0x200 + (j >>> 8)]) + sigma(P[j & 0x3FF]) + P[(Q[j & 0x3FF])]);
result = (tmp ^ P[(tmp >>> 8) & 0x3FF]) ^ P[(j >>> 0) & 0x3FF];
outBuf = new int[] { tmp };
}
idx = (idx + 1) & 0x7FF;
return result;
}
public byte[] encrypt(byte[] key, byte[] iv, byte[] input) {
init(key, iv);
byte[] out = new byte[input.length];
int off = 0;
ByteBuffer ob = ByteBuffer.wrap(out).order(ByteOrder.LITTLE_ENDIAN);
while (off + 4 <= input.length) {
int w = nextWord();
for (int i = 0; i < 4; i++) {
out[off + i] = (byte) (input[off + i] ^ ((w >>> (8 * i)) & 0xFF));
}
off += 4;
}
if (off < input.length) {
int w = nextWord();
for (int i = 0; i < input.length - off; i++) {
out[off + i] = (byte) (input[off + i] ^ ((w >>> (8 * i)) & 0xFF));
}
}
return out;
}
public static void main(String[] args) {
byte[] key = new byte[32];
for (int i = 0; i < 32; i++) key[i] = (byte) (i + 0x80);
byte[] iv = new byte[32];
for (int i = 0; i < 32; i++) iv[i] = (byte) (i + 0xC0);
HC256Demo hc = new HC256Demo();
String pt = "HC-256 is the high-speed stream cipher from Hongjun Wu";
byte[] ct = hc.encrypt(key, iv, pt.getBytes());
HC256Demo hc2 = new HC256Demo();
byte[] recovered = hc2.encrypt(key, iv, ct);
System.out.println("Key : " + Base64.getEncoder().encodeToString(key));
System.out.println("IV : " + Base64.getEncoder().encodeToString(iv));
System.out.println("Plaintext: " + pt);
System.out.println("Ciphertext: " + Base64.getEncoder().encodeToString(ct));
System.out.println("Recovered: " + new String(recovered));
}
}
Code Explanation Line by Line
The class declares the two 1024-word state tables P and Q, the index idx that cycles 0 to 2047, and the outBuf helper. The two tables together hold 2048 32-bit words or 8 KB.
rotr() is the standard 32-bit right rotation. sigma() is the SHA-256 message-schedule sigma0 function, which mixes the right rotation by 7, the right rotation by 18, and the logical right shift by 3.
init() expands the 256-bit key and 256-bit IV into 2048 state words. The expansion is a small loop similar to the SHA-256 message schedule: each word is a function of words 2, 7, and 15 positions back. The first 512 words are then copied to P and the next 1024 words to Q; the remaining 512 words are discarded. After copying, the cipher runs the nextWord function 2048 times without producing output to scramble the tables.
nextWord() is the heart of the cipher. If the counter is below 1024, it updates P[j] by adding the sigma function of a Q word, the sigma function of another Q word, and a third Q word indexed by the low 10 bits of P[j]. The output is the XOR of the new P[j] word and a Q word indexed by the middle bits of the new P[j]. If the counter is at or above 1024, the same pattern runs with the roles of P and Q swapped.
encrypt() initializes the cipher state, then iterates nextWord() over the input in 4-byte chunks. Each 32-bit output word is XORed with four consecutive input bytes. The last partial chunk, if any, is handled by reading one more output word and using only the needed bytes.
main() demonstrates the cipher with a 256-bit key (bytes 0x80 to 0x9F) and a 256-bit IV (bytes 0xC0 to 0xDF). It encrypts a sample plaintext and shows that running encrypt on the ciphertext recovers the original message.
Sample Input and Output
Input: Key : 80818283 ... 9e9fa0 (32 bytes) IV : c0c1c2c3 ... dee0e1 (32 bytes) Plaintext: HC-256 is the high-speed stream cipher from Hongjun Wu Output: Ciphertext: <base64 of XOR of plaintext with keystream> Recovered: HC-256 is the high-speed stream cipher from Hongjun Wu
The exact keystream bytes depend on the key and IV. The recovered plaintext line proves the round-trip works.
Common Mistakes to Avoid
First, confusing the P-update and Q-update branches of nextWord is the classic HC-256 bug. The two branches are symmetric but the table indices in each branch must reference the other table; mixing them up produces a cipher that may pass round-trip tests but fails test vectors.
Second, using the wrong sigma function is a silent bug. The HC-256 sigma is the SHA-256 sigma0 (rotations 7 and 18, shift 3). Using the SHA-256 sigma1 (rotations 17 and 19, shift 10) instead breaks the cipher.
Third, forgetting the 2048-round table scrambling after initialization is a security bug. Without the scrambling, the first keystream words depend trivially on the key, which leaks key bits.
Fourth, reusing an IV under the same key is fatal. HC-256's IV mechanism is designed for a unique IV per message; repetition leaks the keystream and lets an attacker recover the plaintext by XORing two ciphertexts.
Real-World Applications
HC-256 was selected for the eSTREAM software stream cipher portfolio in 2008. The portfolio recommendation encouraged cryptographers to use HC-256 for high-speed software applications where AES was not desired.
HC-256 is the successor to HC-128, which has a smaller state (1024 words instead of 2048) and a smaller key (128 bits). HC-128 was also an eSTREAM candidate and is sometimes preferred for memory-constrained applications.
The cipher has been used in research prototypes of network traffic protection where the 8 KB state size is acceptable and the 2 cycles per byte performance is desirable.
On the JVM specifically, Bouncy Castle ships HC-256 in its lightweight API as the org.bouncycastle.crypto.stream.HC256Engine class. The SunJCE provider does not ship HC-256; the manual implementation above is a portable way to interoperate with systems that use the cipher.
HC-256 is the textbook example of a dynamic table-based stream cipher that uses 32-bit words. If you study RC4 (the 8-bit ancestor) and Salsa20 (the modern ARX alternative), you will see how the design tradeoffs evolved over a decade.
Conclusion
You learned what HC-256 is, how the sigma function reuses the SHA-256 nonlinear primitive, and how the two 1024-word state tables alternate between P and Q updates. You also saw why the table scrambling after initialization is essential, why the IV must be unique per message, and why the P and Q branches of nextWord must be implemented symmetrically. Next, study Rabbit for the ARX-with-squaring alternative, Grain for the hardware-optimized stream cipher, and Trivium for the smallest hardware stream cipher.
Comments
Comments
Post a Comment