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 ISO 10126 Padding with Random Bytes

Reviewed & accurate
AI Summary

Introduction

The iso 10126 padding java tutorial walks through the padding scheme defined in ISO/IEC 10126, an international standard for block cipher padding published by the International Organization for Standardization. The iso 10126 padding java example below shows the algorithm from scratch with random padding bytes. ISO 10126 specifies that the padding consists of N-1 random bytes followed by a final byte whose value is N, where N is the pad length. The iso 10126 padding java implementation demonstrates the non-deterministic property of the scheme. The random bytes mean the padding is non-deterministic: the same plaintext produces different padded outputs on each call, which can be useful for encrypted random data but complicates implementations that need a reproducible ciphertext.

For a Java learner the iso10126 padding java example below matters as a contrast to PKCS7. Where PKCS7 puts the pad length in every padding byte, ISO 10126 puts the pad length in only the last byte and fills the rest with random data. This means the unpad function has less redundancy to verify, but the random padding conceals the message length modulo the block size from an observer of the padded output.

ISO 10126 was withdrawn by ISO in 2008 in favor of ISO/IEC 9797-1, which generalizes the padding methods. The scheme survives in some legacy financial messaging standards and in textbook tutorials because the random-padding property is pedagogically interesting.

What is ISO 10126 Padding?

iso10126 padding java is a byte-level padding scheme for block ciphers. The scheme belongs to the family of length-explicit padding schemes; the pad length is encoded in the final byte. The defining property of ISO 10126 is that the leading N-1 padding bytes are random, which distinguishes it from PKCS7 (where every padding byte equals N), ANSI X9.23 (where the leading N-1 bytes are zero), and ISO 7816-4 (where the leading byte is 0x80 and the rest are zero).

For a block size B and a message length L, the pad length N is B minus (L modulo B). If L is a multiple of B, then N equals B; that is, a full block of padding is appended. The first N-1 padding bytes are random values from 0 to 255; the final padding byte is N. The receiver reads the last byte as N, verifies N is between 1 and B, and strips the last N bytes. The receiver cannot verify the random bytes (they are random), so the only verification is that N is in range.

The weaker verification is the security drawback of ISO 10126. PKCS7 verifies every padding byte, which makes a bit-flip in the padding detectable. ISO 10126 verifies only the last byte, so a bit-flip in a random padding byte is undetectable at the padding layer (though the cipher's MAC should still detect it). For this reason ISO 10126 is rarely used in new designs.

How ISO 10126 Padding Works Step by Step

Step 1: Compute the pad length. For a message of length L and a block size of B bytes, the pad length N is B minus (L modulo B). If L modulo B is zero, then N equals B.

Step 2: Generate N-1 random bytes. Use a cryptographically strong random number generator such as SecureRandom. The random bytes are between 0 and 255 inclusive.

Step 3: Build the padding bytes. The padding is the N-1 random bytes followed by the byte N. The last byte is the only one whose value is determined by the scheme.

Step 4: Append the padding. Concatenate the message with the padding bytes. The result is a multiple of B bytes.

Step 5: Encrypt with the block cipher. The cipher processes the padded message in B-byte blocks.

Step 6: After decryption, unpad. Read the last byte as N. Verify N is between 1 and B and that N does not exceed the message length. Strip the last N bytes. The random bytes are not verified, so the unpad function is weaker than PKCS7's unpad.

Java Program for ISO 10126 Padding with Random Bytes


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 Iso10126PaddingDemo {

    private static final int BLOCK = 16; // AES block size
    private static final SecureRandom RNG = new SecureRandom();

    static byte[] iso10126Pad(byte[] in) {
        int n = BLOCK - (in.length % BLOCK);
        byte[] out = new byte[in.length + n];
        System.arraycopy(in, 0, out, 0, in.length);
        byte[] rnd = new byte[n - 1];
        RNG.nextBytes(rnd);
        System.arraycopy(rnd, 0, out, in.length, n - 1);
        out[out.length - 1] = (byte) n;
        return out;
    }

    static byte[] iso10126Unpad(byte[] in) {
        if (in.length == 0 || in.length % BLOCK != 0) {
            throw new IllegalArgumentException("Invalid padded length");
        }
        int n = in[in.length - 1] & 0xFF;
        if (n < 1 || n > BLOCK || n > in.length) {
            throw new IllegalArgumentException("Invalid pad value " + n);
        }
        return Arrays.copyOfRange(in, 0, in.length - n);
    }

    static byte[] aesCbcEncrypt(byte[] key, byte[] iv, byte[] plaintext) throws Exception {
        Cipher aes = Cipher.getInstance("AES/ECB/NoPadding");
        aes.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"));

        byte[] padded = iso10126Pad(plaintext);
        byte[] out = new byte[padded.length];
        byte[] prev = iv;
        for (int off = 0; off < padded.length; off += BLOCK) {
            byte[] t = new byte[BLOCK];
            for (int i = 0; i < BLOCK; i++) {
                t[i] = (byte) (padded[off + i] ^ prev[i]);
            }
            byte[] c = aes.doFinal(t);
            System.arraycopy(c, 0, out, off, BLOCK);
            prev = c;
        }
        return out;
    }

    static byte[] aesCbcDecrypt(byte[] key, byte[] iv, byte[] ciphertext) throws Exception {
        Cipher aes = Cipher.getInstance("AES/ECB/NoPadding");
        aes.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"));

        byte[] out = new byte[ciphertext.length];
        byte[] prev = iv;
        for (int off = 0; off < ciphertext.length; off += BLOCK) {
            byte[] c = Arrays.copyOfRange(ciphertext, off, off + BLOCK);
            byte[] t = aes.doFinal(c);
            for (int i = 0; i < BLOCK; i++) {
                out[off + i] = (byte) (t[i] ^ prev[i]);
            }
            prev = c;
        }
        return iso10126Unpad(out);
    }

    public static void main(String[] args) throws Exception {
        byte[] key = new byte[16];
        RNG.nextBytes(key);
        byte[] iv = new byte[BLOCK];
        RNG.nextBytes(iv);

        String message = "ISO 10126 uses random padding bytes.";
        byte[] plaintext = message.getBytes("UTF-8");

        byte[] ciphertext = aesCbcEncrypt(key, iv, plaintext);
        byte[] recovered = aesCbcDecrypt(key, iv, ciphertext);

        // Encrypt the same plaintext twice to show the random padding differs.
        byte[] ciphertext2 = aesCbcEncrypt(key, iv, plaintext);

        System.out.println("Key        : " + Base64.getEncoder().encodeToString(key));
        System.out.println("IV         : " + Base64.getEncoder().encodeToString(iv));
        System.out.println("Plaintext  : " + message);
        System.out.println("Plaintext len: " + plaintext.length);
        byte[] padded = iso10126Pad(plaintext);
        System.out.println("Padded len : " + padded.length);
        System.out.println("Last pad byte: 0x" + Integer.toHexString(padded[padded.length - 1] & 0xFF));
        System.out.println("Ciphertext : " + Base64.getEncoder().encodeToString(ciphertext));
        System.out.println("Ciphertext2: " + Base64.getEncoder().encodeToString(ciphertext2));
        System.out.println("Recovered  : " + new String(recovered, "UTF-8"));
        System.out.println("Round trip ok: " + Arrays.equals(plaintext, recovered));
        System.out.println("Random padding differs: " + (!Arrays.equals(ciphertext, ciphertext2)));
    }
}

Code Explanation Line by Line

The class Iso10126PaddingDemo declares BLOCK = 16 and a single SecureRandom instance RNG. The iso10126Pad method computes N = 16 minus (in.length modulo 16), generates N-1 random bytes via RNG.nextBytes, and appends them followed by the byte N. The random bytes are filled by the OS-supplied entropy source, which on Linux is /dev/urandom and on Windows is the CryptoAPI RNG.

The iso10126Unpad method reads the last byte as N, validates N is between 1 and BLOCK and that N does not exceed the message length, and strips the last N bytes. The validation is weaker than PKCS7's because the random bytes cannot be verified; the only check is the range of N. This makes the unpad function fragile to bit-flips in the random padding, which are undetectable at the padding layer.

The aesCbcEncrypt and aesCbcDecrypt methods implement AES in CBC mode manually, using AES/ECB/NoPadding as the block primitive. The encrypt method pads with ISO 10126 before processing; the decrypt method unpads after processing. The CBC chain is identical to the standard construction.

The main method performs the round trip and then encrypts the same plaintext twice to demonstrate that the random padding makes the ciphertexts differ. The Random padding differs line confirms that ISO 10126 produces non-deterministic ciphertexts even with the same key and IV; in a real system, you must generate a fresh IV for every encryption, but the demo here isolates the padding effect.

Sample Input and Output

Key        : q1w...your-base64-key-here...
IV         : e2r...your-base64-iv-here...
Plaintext  : ISO 10126 uses random padding bytes.
Plaintext len: 32
Padded len : 48
Last pad byte: 0x10
Ciphertext : aB3...your-base64-ciphertext-here...
Ciphertext2: xY9...different-base64-ciphertext-here...
Recovered  : ISO 10126 uses random padding bytes.
Round trip ok: true
Random padding differs: true

The 32-byte plaintext becomes 48 bytes after ISO 10126 padding (32 modulo 16 = 0, so N = 16). The last pad byte is 0x10 (16 in decimal), confirming the always-pad-a-full-block rule. The two ciphertexts differ even though the key and IV are identical because the random padding bytes differ between the two calls. The round trip succeeds.

Common Mistakes to Avoid

The first mistake is using a weak random number generator. The random bytes must come from a cryptographically strong source such as SecureRandom. Using java.util.Random produces predictable outputs that leak the padding content to an attacker who can predict the seed.

The second mistake is reusing the IV. ISO 10126's random padding does not protect against IV reuse; you still need a fresh IV for every encryption under the same key. The random padding only conceals the message length modulo the block size from an observer of the padded output, not from an attacker who can compare two ciphertexts encrypted with the same IV.

The third mistake is relying on the padding as a tamper check. ISO 10126 verifies only the last byte, so an attacker who flips a bit in a random padding byte is undetected at the padding layer. Always pair ISO 10126 with an explicit MAC such as HMAC-SHA256 in the Encrypt-then-MAC construction.

The fourth mistake is using ISO 10126 in new designs. The scheme was withdrawn in 2008 and offers no security advantage over PKCS7. New designs should use PKCS7 padding with AES-CBC (for local storage) or, preferably, an AEAD cipher such as AES-GCM or ChaCha20-Poly1305 (for network protocols).

Real-World Applications

ISO 10126 was the international standard for block cipher padding from its publication until its withdrawal in 2008. It appears in some legacy financial messaging standards, in legacy smart card protocols, and in textbook tutorials. The scheme was withdrawn because the security community concluded that the random-padding property did not justify the weaker verification and the non-deterministic ciphertext, and that PKCS7 (with explicit MAC) or AEAD ciphers were strictly better.

In modern systems ISO 10126 is essentially obsolete. The OpenSSL command-line tool defaults to PKCS7 padding for AES-CBC; the BouncyCastle provider supports ISO 10126 as "ISO10126Padding" for compatibility but does not recommend it for new designs. The JDK SunJCE provider does not expose ISO 10126 by name; manual implementation, as in this tutorial, is the only way to use it.

The pedagogical value of ISO 10126 is the contrast with PKCS7 and ANSI X9.23. PKCS7 encodes the pad length in every padding byte (maximum redundancy, deterministic ciphertext); ANSI X9.23 uses zeros plus the pad-length byte (minimum redundancy, deterministic ciphertext); ISO 10126 uses random bytes plus the pad-length byte (minimum redundancy, non-deterministic ciphertext). The trade-off is between verifiability (PKCS7 wins), determinism (PKCS7 and X9.23 win), and length-concealment (ISO 10126 wins). Modern systems choose AEAD ciphers, which need no padding and therefore avoid the trade-off entirely.

The ISO/IEC 9797-1 standard, which replaced ISO 10126, defines Padding Method 1 (zeros only, ambiguous), Padding Method 2 (a single 0x80 followed by zeros, ISO 7816-4), and Padding Method 3 (a length byte at the start followed by zeros). Method 2 is the modern recommendation when padding is needed; ISO 10126 is not in the modern standard.

Conclusion

In this iso10126 padding java tutorial we built ISO 10126 from scratch, demonstrated its non-deterministic property, and explained why the scheme is no longer recommended. ISO 10126 is a historical alternative to PKCS7 with weaker verification and non-deterministic ciphertext; the modern recommendation is PKCS7 with an explicit MAC, or, better, an AEAD cipher that needs no padding. Next, study the ANSI X9.23 alternative, the ISO 7816-4 bit padding scheme, ciphertext stealing, and the Vaudenay padding oracle attack.

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