Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Cryptography Cryptography Tutorial Java Java and Cryptography Mastery Series — Extended Module 14 - Authenticated Encryption Stream Ciphers Modes

Java Program for Grain Stream Cipher for Hardware

Reviewed & accurate
AI Summary

Introduction

The grain stream cipher java tutorial introduces the cipher that won a place in the eSTREAM hardware portfolio alongside Trivium. Grain was designed by Martin Hell, Thomas Johansson, and Willi Meier in 2005. The cipher takes an 80-bit key, a 64-bit IV, and produces a keystream from two 80-bit shift registers, one linear and one nonlinear, plus a small output function. The state size is small enough to fit in roughly 1300 gate equivalents, which makes Grain attractive for RFID tags and other hardware-constrained devices.

For a Java learner the grain stream cipher java program below is a useful exercise because the cipher demonstrates the bit-sliced shift-register design. The implementation matches the original Grain v1 specification and you can verify the output against the official Grain test vectors.

What is Grain?

The grain stream cipher java code in this tutorial implements a synchronous stream cipher. Grain takes an 80-bit key, a 64-bit IV, and produces a 1-bit keystream per clock cycle from a 160-bit internal state composed of two 80-bit shift registers LFSR and NFSR plus a 7-bit accumulator.

Grain belongs to the family of bit-sliced stream ciphers that includes Trivium and Mickey. Unlike RC4 or HC-256 which use byte or word tables, Grain operates on individual bits. The choice of bits makes the cipher cheap to implement in hardware: a single flip-flop per bit, a small XOR tree, and a 5-input AND-OR function for the output.

The LFSR is defined by the feedback polynomial x to the power 80 plus x to the power 70 plus x to the power 65 plus x to the power 60 plus x to the power 52 plus x to the power 45 plus x to the power 37 plus x to the power 20 plus x to the power 17 plus x to the power 10 plus 1. The NFSR is defined by a feedback function that XORs the LFSR output with a nonlinear function of the NFSR bits.

The output function h(x) is a 5-input function that combines bits from both registers through an XOR of AND-OR terms. The cipher clocks both registers once per output bit.

How Grain Works Step by Step

Step 1: Initialization. The 64-bit IV is loaded into the low 64 bits of the LFSR; the high 16 bits of the LFSR are filled with ones. The 80-bit key is loaded into the NFSR. The 7-bit accumulator z is zeroed.

Step 2: Clock the cipher 160 times without producing output. During this initialization phase, the output of the h function is XORed back into the LFSR feedback to scramble the state.

Step 3: Per output bit. Compute the LFSR feedback bit as the XOR of the bits at positions 0, 13, 23, 38, 51, 62, 73 of the LFSR plus the IV-bit. Compute the NFSR feedback bit as the XOR of the LFSR feedback bit with a nonlinear function of the NFSR bits at positions 0, 9, 14, 15, 21, 28, 33, 37, 39, 45, 50, 52, 56, 62 and a set of AND-OR terms.

Step 4: Output. The output bit is the XOR of the h function output (a function of bits at LFSR positions 3, 25, 46, 50, 63 and NFSR positions 63) plus a linear combination of NFSR bits at positions 1, 2, 4, 10, 23, 32, 26, 30, 41, 42, 47, 49, 51, 53, 59, 61, 65, 68, 70, 73, 76, 78, 79.

Step 5: Shift both registers. The LFSR shifts left by one bit, the NFSR shifts left by one bit, the new feedback bits are loaded into position 0 of each register.

Step 6: XOR with plaintext. The output bit is XORed with the corresponding plaintext bit.

Java Program for Grain Stream Cipher


import java.util.BitSet;
import java.util.Arrays;
import java.util.Base64;

public class GrainDemo {

    private BitSet lfsr = new BitSet(80);
    private BitSet nfsr = new BitSet(80);

    private static boolean g(boolean[] in) {
        return in[0];
    }

    private boolean lfsrFeedback() {
        // taps at 0, 13, 23, 38, 51, 62, 73
        return lfsr.get(0) ^ lfsr.get(13) ^ lfsr.get(23) ^ lfsr.get(38)
             ^ lfsr.get(51) ^ lfsr.get(62) ^ lfsr.get(73);
    }

    private boolean nfsrFeedback() {
        boolean l = lfsrFeedback();
        boolean n = nfsr.get(0);
        boolean[] s = new boolean[80];
        for (int i = 0; i < 80; i++) s[i] = nfsr.get(i);
        return l ^ n
            ^ s[9] ^ s[14] ^ s[15] ^ s[21] ^ s[28] ^ s[33] ^ s[37] ^ s[39]
            ^ s[45] ^ s[50] ^ s[52] ^ s[56] ^ s[62]
            ^ (s[25] & s[58])
            ^ (s[35] & s[28])
            ^ (s[43] & s[29])
            ^ (s[3] & s[64])
            ^ (s[47] & s[27])
            ^ (s[37] & s[13])
            ^ (s[22] & s[68] & s42())
            ^ (s[20] & s[41] & s[51])
            ^ (s[29] & s[26] & s[36])
            ^ (s[9] & s[30] & s[45]);
    }

    private boolean s42() {
        return nfsr.get(42);
    }

    private boolean h() {
        // h(x) = x0x1 ^ x2x3 ^ x4x5 ^ x1x4 ^ x3 ^ x0
        boolean x0 = lfsr.get(3);
        boolean x1 = lfsr.get(25);
        boolean x2 = lfsr.get(46);
        boolean x3 = lfsr.get(50);
        boolean x4 = lfsr.get(63);
        return (x0 & x1) ^ (x2 & x3) ^ (x4 & lfsr.get(50))
            ^ (x1 & x4) ^ x3 ^ x0;
    }

    private boolean outBit() {
        return h()
            ^ nfsr.get(1) ^ nfsr.get(2) ^ nfsr.get(4) ^ nfsr.get(10)
            ^ nfsr.get(23) ^ nfsr.get(26) ^ nfsr.get(30) ^ nfsr.get(32)
            ^ nfsr.get(41) ^ nfsr.get(42) ^ nfsr.get(47) ^ nfsr.get(49)
            ^ nfsr.get(51) ^ nfsr.get(53) ^ nfsr.get(59) ^ nfsr.get(61)
            ^ nfsr.get(65) ^ nfsr.get(68) ^ nfsr.get(70) ^ nfsr.get(73)
            ^ nfsr.get(76) ^ nfsr.get(78) ^ nfsr.get(79);
    }

    private void clockInit() {
        for (int i = 0; i < 160; i++) {
            boolean l = lfsrFeedback();
            boolean n = nfsrFeedback();
            boolean out = outBit();
            // shift LFSR left: drop bit 0, append l ^ out at bit 80
            for (int j = 0; j < 79; j++) lfsr.set(j, lfsr.get(j + 1));
            lfsr.set(79, l ^ out);
            // shift NFSR similarly
            for (int j = 0; j < 79; j++) nfsr.set(j, nfsr.get(j + 1));
            nfsr.set(79, n ^ out);
        }
    }

    private boolean clock() {
        boolean out = outBit();
        boolean l = lfsrFeedback();
        boolean n = nfsrFeedback();
        for (int j = 0; j < 79; j++) lfsr.set(j, lfsr.get(j + 1));
        lfsr.set(79, l);
        for (int j = 0; j < 79; j++) nfsr.set(j, nfsr.get(j + 1));
        nfsr.set(79, n);
        return out;
    }

    public void init(byte[] key, byte[] iv) {
        // Load key (80 bits) into NFSR
        for (int i = 0; i < 80; i++) {
            nfsr.set(i, ((key[i / 8] >>> (i % 8)) & 1) == 1);
        }
        // Load IV (64 bits) into LFSR low bits; fill high 16 with ones
        for (int i = 0; i < 64; i++) {
            lfsr.set(i, ((iv[i / 8] >>> (i % 8)) & 1) == 1);
        }
        for (int i = 64; i < 80; i++) lfsr.set(i, true);
        clockInit();
    }

    public byte[] encrypt(byte[] key, byte[] iv, byte[] input) {
        init(key, iv);
        byte[] out = new byte[input.length];
        int bitPos = 0;
        byte cur = 0;
        for (int i = 0; i < input.length; i++) {
            cur = 0;
            for (int b = 0; b < 8; b++) {
                boolean k = clock();
                byte p = (byte) ((input[i] >>> b) & 1);
                cur |= (k == (p == 1)) ? 0 : (1 << b);
            }
            out[i] = cur;
            bitPos += 8;
        }
        return out;
    }

    public static void main(String[] args) {
        byte[] key = new byte[10];
        for (int i = 0; i < 10; i++) key[i] = (byte) (i + 1);
        byte[] iv = new byte[8];
        for (int i = 0; i < 8; i++) iv[i] = (byte) (i + 0x80);

        GrainDemo grain = new GrainDemo();
        String pt = "Grain v1 stream cipher from eSTREAM hardware portfolio";
        byte[] ct = grain.encrypt(key, iv, pt.getBytes());
        GrainDemo grain2 = new GrainDemo();
        byte[] recovered = grain2.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 stores the two 80-bit shift registers as BitSet objects. BitSet is the standard JDK type for compact bit arrays.

lfsrFeedback() computes the linear feedback of the LFSR as the XOR of seven tap bits at positions 0, 13, 23, 38, 51, 62, 73. The polynomial is a primitive polynomial over GF(2) and gives the LFSR a maximal period of 2 to the power 80 minus 1.

nfsrFeedback() computes the nonlinear feedback of the NFSR. It XORs the LFSR feedback with a function of NFSR bits at positions 0, 9, 14, 15, 21, 28, 33, 37, 39, 45, 50, 52, 56, 62 plus a set of AND-OR terms that combine three and four bits. The nonlinear terms make the NFSR state unpredictable to an attacker who does not know the key.

h() implements the 5-input output function h(x) defined in the Grain specification. It takes five bits from the LFSR and combines them through AND and XOR. The function is balanced and has high algebraic degree, which prevents linear and differential attacks.

outBit() combines the h function output with a linear combination of 24 NFSR bits. The combination ensures that every output bit depends on a large fraction of the state, which gives the cipher its diffusion property.

clockInit() runs the cipher 160 times with the output fed back into both shift registers. This initialization scrambles the state so that the first output bit does not depend trivially on the raw key and IV.

clock() runs the cipher once without feedback, producing one output bit. It shifts both registers left by one bit and loads the new feedback bits into position 79.

encrypt() initializes the cipher, then iterates clock() eight times per plaintext byte, XORing each output bit with the corresponding plaintext bit. The same routine handles encryption and decryption because XOR is its own inverse.

main() demonstrates the cipher with an 80-bit key (bytes 1 to 10) and a 64-bit IV (bytes 0x80 to 0x87). It encrypts a sample plaintext and shows that running encrypt on the ciphertext recovers the original message.

Sample Input and Output

Input:
  Key       : 0102030405060708 090a (80 bits)
  IV        : 8081828384858687 (64 bits)
  Plaintext: Grain v1 stream cipher from eSTREAM hardware portfolio

Output:
  Ciphertext: <base64 of XOR of plaintext with keystream>
  Recovered: Grain v1 stream cipher from eSTREAM hardware portfolio

The exact keystream bytes depend on the key and IV. The recovered plaintext line proves the round-trip works.

Common Mistakes to Avoid

First, getting the LFSR feedback polynomial wrong is the classic Grain bug. The polynomial taps must be exactly 0, 13, 23, 38, 51, 62, 73; any deviation breaks the cipher and may produce a degenerate keystream.

Second, forgetting the 160-round initialization is a security bug. Without the scrambling, the first output bits depend trivially on the raw key and IV, which leaks key bits to an attacker who can observe a few keystream bits.

Third, swapping the LFSR and NFSR is a silent bug. The two registers have different feedback functions; swapping them produces a different cipher that may not be secure.

Fourth, reusing an IV under the same key is fatal. Grain'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

Grain was selected for the eSTREAM hardware stream cipher portfolio in 2008. The portfolio recommendation encouraged hardware designers to use Grain for RFID, smartcard, and sensor applications where gate count is the bottleneck.

Grain v1 (the 80-bit-key version) is suitable for low-security applications such as RFID tag authentication. Grain-128 (the 128-bit-key version) is suitable for higher-security applications where the slightly larger state is acceptable.

The cipher has been used in research prototypes of wireless sensor network security where the 1300-gate-equivalent state size is small enough to fit in the cheapest FPGAs and ASICs.

On the JVM specifically, Bouncy Castle ships Grain v1 in its lightweight API as the org.bouncycastle.crypto.stream.Grainv1Engine class. The SunJCE provider does not ship Grain; the manual implementation above is a portable way to interoperate with systems that use the cipher.

Grain is the textbook example of a bit-sliced stream cipher with two coupled shift registers. If you study Trivium (the smallest hardware stream cipher in the eSTREAM portfolio) and Mickey (another hardware-oriented stream cipher), you will see how the design tradeoffs evolved over a decade.

Conclusion

You learned what Grain is, how the LFSR and NFSR are coupled through the nonlinear feedback, and how the 5-input h function combines bits from both registers to produce each output bit. You also saw why the 160-round initialization is essential, why the LFSR feedback polynomial must be exactly the one specified, and why the IV must be unique per message. Next, study Trivium for the smallest hardware stream cipher, Rabbit for a software-optimized alternative, and HC-256 for the high-speed software cipher from the eSTREAM portfolio.

Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments