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 OFB Output Feedback Mode

Reviewed & accurate
AI Summary

Introduction

The ofb output feedback mode java tutorial introduces a feedback mode that turns a block cipher into a synchronous stream cipher. OFB (Output Feedback) was specified by the National Bureau of Standards in FIPS 81 in 1980 and standardized internationally as ISO 10116. The mode takes a key, an initialization vector, and a plaintext of any length, and produces a ciphertext by XORing each plaintext block with a keystream block derived from the previous keystream block. OFB is the mode used by some legacy implementations of the Yahoo Messenger protocol and by older Kerberos 4 encryption.

For a Java learner the ofb output feedback mode java program below is a useful exercise because the mode demonstrates how a block cipher can be operated as a pure keystream generator. We implement OFB manually using AES/ECB/NoPadding as the block primitive and compare the output with the JDK's built-in AES/OFB/NoPadding implementation.

What is OFB Mode?

The ofb output feedback mode java code in this tutorial implements a feedback stream cipher mode. OFB takes a 128, 192, or 256-bit AES key, a 16-byte initialization vector, and a plaintext of any length. It outputs a ciphertext of the same length as the plaintext.

OFB is similar to CFB but the feedback is the keystream itself, not the ciphertext. In CFB, the previous ciphertext block is encrypted to produce the next keystream. In OFB, the previous keystream block is encrypted to produce the next keystream. The ciphertext does not feed back into the keystream generation.

The advantage of OFB over CFB is that the keystream can be precomputed because it does not depend on the plaintext. This is useful in protocols with strict latency requirements: the keystream can be generated during idle time and the encryption is just an XOR.

The disadvantage of OFB is that it is not self-synchronizing. A single bit error in the ciphertext corrupts only the corresponding plaintext bit (good), but if the keystream ever cycles back to a previous value, the cipher becomes insecure (bad). The keystream period for OFB-AES is theoretically up to 2 to the power 128 blocks but in practice is closer to 2 to the power 64 blocks.

OFB is not an authenticated mode. An attacker can flip bits in the ciphertext and the corresponding plaintext bits will flip; the mode provides no integrity. For real security you must combine OFB with a MAC.

How OFB Mode Works Step by Step

Step 1: Initialization. Set the feedback register equal to the IV. The IV must be unique per message under the same key; a random IV from a CSPRNG or a counter-based IV are both acceptable.

Step 2: For each plaintext block i from 1 to N. Compute keystream = E_K(feedback). Compute ciphertext block C_i = P_i XOR keystream. Set feedback = keystream.

Step 3: Output. The ciphertext is the concatenation of C_1, C_2, ..., C_N. The IV is transmitted alongside the ciphertext but is not secret.

Step 4: Decryption. For each ciphertext block i from 1 to N. Compute keystream = E_K(feedback). Compute P_i = C_i XOR keystream. Set feedback = keystream. Note that the block cipher decryption is never used; only the encryption primitive is needed.

Step 5: Partial block. If the plaintext length is not a multiple of 16 bytes, the last keystream block is generated normally and only the needed prefix of the keystream is XORed with the plaintext.

Step 6: No self-synchronization. If a ciphertext bit is corrupted, only the corresponding plaintext bit is corrupted. The keystream is unaffected because it does not depend on the ciphertext. This is the opposite of CFB where the next block's plaintext is also corrupted.

Java Program for OFB Mode


import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Base64;

public class OfbModeDemo {

    private static final int BLOCK = 16;
    private final SecretKeySpec keySpec;

    public OfbModeDemo(byte[] key) {
        this.keySpec = new SecretKeySpec(key, "AES");
    }

    private byte[] aesEcbEncrypt(byte[] block) throws Exception {
        Cipher c = Cipher.getInstance("AES/ECB/NoPadding");
        c.init(Cipher.ENCRYPT_MODE, keySpec);
        return c.doFinal(block);
    }

    private static byte[] xor(byte[] a, byte[] b) {
        byte[] out = new byte[a.length];
        for (int i = 0; i < a.length; i++) out[i] = (byte) (a[i] ^ b[i]);
        return out;
    }

    public byte[] encrypt(byte[] iv, byte[] plaintext) throws Exception {
        byte[] out = new byte[plaintext.length];
        byte[] feedback = iv;
        int off = 0;
        while (off < plaintext.length) {
            byte[] ks = aesEcbEncrypt(feedback);
            int len = Math.min(BLOCK, plaintext.length - off);
            byte[] pBlock = Arrays.copyOfRange(plaintext, off, off + len);
            byte[] cBlock = xor(pBlock, Arrays.copyOf(ks, len));
            System.arraycopy(cBlock, 0, out, off, len);
            // Update feedback with the keystream (not the ciphertext!)
            feedback = ks;
            off += len;
        }
        return out;
    }

    public byte[] decrypt(byte[] iv, byte[] ciphertext) throws Exception {
        // OFB encryption and decryption are identical because the keystream
        // is independent of the data.
        return encrypt(iv, ciphertext);
    }

    public static void main(String[] args) throws Exception {
        byte[] key = new byte[16];
        new SecureRandom().nextBytes(key);
        byte[] iv = new byte[16];
        new SecureRandom().nextBytes(iv);
        String pt = "OFB generates a pure keystream from the IV";

        OfbModeDemo ofb = new OfbModeDemo(key);
        byte[] ct = ofb.encrypt(iv, pt.getBytes("UTF-8"));
        byte[] recovered = ofb.decrypt(iv, ct);

        // Cross-check against the JDK built-in AES/OFB/NoPadding
        Cipher ref = Cipher.getInstance("AES/OFB/NoPadding");
        ref.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv));
        byte[] refCt = ref.doFinal(pt.getBytes("UTF-8"));

        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 (manual OFB): " + Base64.getEncoder().encodeToString(ct));
        System.out.println("Ciphertext (JDK OFB)   : " + Base64.getEncoder().encodeToString(refCt));
        System.out.println("Match     : " + Arrays.equals(ct, refCt));
        System.out.println("Recovered : " + new String(recovered, "UTF-8"));
    }
}

Code Explanation Line by Line

The class stores a SecretKeySpec and declares the constant BLOCK equal to 16. The implementation is identical in structure to the CFB implementation from the previous tutorial, with the feedback source swapped from ciphertext to keystream.

aesEcbEncrypt() wraps the JDK's "AES/ECB/NoPadding" cipher. We use this algorithm because we want the raw AES block encryption without chaining or padding. OFB only ever uses the encryption primitive, never the decryption primitive.

xor() is the helper that XORs two equal-length byte arrays. The XOR is applied between the keystream and the plaintext to produce the ciphertext.

encrypt() iterates over the plaintext in 16-byte blocks. For each block, it encrypts the feedback register (initially the IV) to produce a keystream block, XORs the keystream with the plaintext block to produce the ciphertext block, and updates the feedback register with the keystream block (not the ciphertext block). This feedback update is the heart of OFB: each keystream block depends only on the previous keystream block, not on the ciphertext.

decrypt() is literally the same as encrypt() because the keystream is independent of the data. The same routine handles both directions because XOR is its own inverse. This is one of the advantages of OFB: you only need the encryption primitive, and you only need one routine.

The partial-block handling copies the keystream block (not the ciphertext block) into the feedback register. For a strict OFB implementation, the feedback register would not be updated for a partial block because the next block would not be processed.

main() demonstrates the round trip with a 16-byte key and a 16-byte IV. It encrypts the plaintext, decrypts the ciphertext, and then cross-checks the manual implementation against the JDK's built-in "AES/OFB/NoPadding". The "Match" line proves that the manual implementation produces the same ciphertext as the JDK.

Sample Input and Output

Input:
  Key       : <16 random bytes, base64>
  IV        : <16 random bytes, base64>
  Plaintext: OFB generates a pure keystream from the IV

Output:
  Ciphertext (manual OFB): <base64 of 42 bytes>
  Ciphertext (JDK OFB)   : <same base64 of 42 bytes>
  Match     : true
  Recovered : OFB generates a pure keystream from the IV

The exact ciphertext bytes are random because the key and IV are random. The two invariant lines are the Match: true line, which proves the manual implementation matches the JDK, and the Recovered: plaintext line, which proves the round trip works.

Common Mistakes to Avoid

First, using a static IV is the classic OFB bug. If the IV is the same for two messages under the same key, the entire keystream is the same and XORing the two ciphertexts recovers the XOR of the two plaintexts. The IV must be unique per message under the same key.

Second, updating the feedback register with the ciphertext instead of the keystream is a silent bug. That change converts OFB into CFB. The two modes have different error propagation and different keystream properties; do not mix them up.

Third, using the decryption primitive in the encrypt routine is a bug. OFB only ever uses the encryption primitive. If you call D_K instead of E_K, the output is a different cipher that may not be secure.

Fourth, using OFB without a MAC is insecure. An attacker can flip bits in the ciphertext and the corresponding plaintext bits will flip; the mode provides no integrity. For real security you must combine OFB with a MAC.

Fifth, reusing the same key and IV for a long stream is risky. If the keystream ever cycles back to a previous value, the cipher becomes insecure because the keystream from that point on is identical to the previous keystream. The theoretical period of OFB-AES is 2 to the power 128 blocks but in practice is closer to 2 to the power 64 blocks.

Real-World Applications

OFB was used by some legacy implementations of the Yahoo Messenger protocol and by older Kerberos 4 encryption. The mode is rarely seen today because CTR and GCM are simpler and faster.

OFB is a building block inside some FIPS 140-2 validated modules for legacy protocols that require a stream cipher mode but cannot use CTR for regulatory reasons. The FIPS 140-2 standard lists OFB as an approved mode alongside CBC, CFB, and CTR.

OFB is the canonical textbook example of a synchronous stream cipher built from a block cipher. If you study Menezes-Oorshot-Vanstone or the Katz-Lindell textbook, you will see OFB presented as the simplest way to operate AES as a stream cipher.

On the JVM specifically, the JDK SunJCE provider ships "AES/OFB/NoPadding" and "AES/OFB/PKCS5Padding". The NoPadding variant is the standard OFB mode; the PKCS5Padding variant adds padding that is rarely needed because OFB does not require padding.

The OpenSSH client does not ship OFB because the cipher is not in the SSH-2 RFC 4344 mandatory list. The CTR and GCM modes have replaced OFB in every modern protocol that previously used it.

OFB is the textbook example of a mode whose keystream can be precomputed. If you study the implementation of the MEGA file storage encryption, you will see OFB-like precomputation of the keystream during idle time so that the actual file encryption is just an XOR pass.

Conclusion

You learned what OFB mode is, how the feedback from the keystream (not the ciphertext) turns AES into a pure stream cipher, and how to implement the full mode without padding using only the JDK AES block primitive. You also saw why the IV must be unique, why the encryption primitive is sufficient for both directions, and why OFB must be combined with a MAC for security. Next, study CFB for the self-synchronizing variant, CTR for the modern counter mode, and GCM for the modern AEAD that replaced OFB in TLS 1.3.

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