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 Null Padding When Message Is Block Aligned

Reviewed & accurate
AI Summary

Introduction

The null padding java tutorial walks through the simplest of all padding schemes: append zero bytes until the message is a multiple of the block size. The scheme is sometimes called "zero padding" or "null padding" and is the default behavior of the OpenSSL command-line tool with the -nopad option. The scheme has a fundamental ambiguity: when the message itself ends in zeros, the receiver cannot tell whether the trailing zeros are part of the message or padding, so the original message length must be carried out-of-band.

For a Java learner the null padding java example below matters as a contrast to PKCS7 and the other length-explicit schemes. Null padding is the natural choice when the message format already encodes the length out-of-band, as in network protocols where a length field precedes the ciphertext, or when the message is known never to end in zeros, as in fixed-length fields packed into a fixed-width record. The scheme is also the conceptual ancestor of ISO 7816-4 bit padding, which uses a 0x80 marker to disambiguate the trailing zeros.

This tutorial implements null padding from scratch with AES as the block cipher, shows the ambiguity that arises when the message ends in zeros, and explains when the scheme is acceptable (length carried out-of-band) and when it is not (length implicit in the ciphertext).

What is Null Padding?

null padding java is a byte-level padding scheme for block ciphers. The scheme belongs to the family of length-implicit padding schemes, in which the pad length is not encoded in the padding bytes themselves. Other schemes in this family are ISO 7816-4 bit padding (which uses a 0x80 marker to disambiguate) and the no-padding mode of stream ciphers (which use no padding at all because the keystream is XORed with the message byte by byte).

For a block size B and a message length L, the pad length N is (B minus (L modulo B)) modulo B. If L is a multiple of B, then N equals zero; that is, no padding is appended. This is the key difference from PKCS7 and the length-explicit schemes, which always append at least one byte. Null padding may append zero bytes, which makes the unpadding ambiguous unless the original length is known.

The padding bytes are zero. The receiver reads the original length from a length field carried outside the ciphertext (for example, a TCP-like length header in a network protocol, or a fixed-length field in a record format) and strips the trailing zeros up to that length. If the original length is not known, the receiver cannot distinguish trailing message zeros from padding zeros, which is the fundamental ambiguity of the scheme.

How Null 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)) modulo B. If L modulo B is zero, then N equals zero. This is the rule that distinguishes null padding from the length-explicit schemes.

Step 2: Append N zero bytes. The padding is N zero bytes. If N is zero, no padding is appended.

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

Step 4: After decryption, the receiver knows the original length L from out-of-band information (a length field, a record header, a fixed-length field). The receiver strips the trailing zeros up to L.

Step 5: Verify the trailing bytes are zero. The receiver may check that the bytes between L and the end of the decrypted buffer are all zero, which is a sanity check on the decryption. If any of these bytes is non-zero, the decryption is corrupt or the key is wrong.

Step 6: Use the original-length L to recover the message. The original message is the first L bytes of the decrypted buffer.

Java Program for Null Padding When Message Is Block Aligned


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

    private static final int BLOCK = 16; // AES block size

    static byte[] nullPad(byte[] in) {
        int n = (BLOCK - (in.length % BLOCK)) % BLOCK;
        byte[] out = new byte[in.length + n];
        System.arraycopy(in, 0, out, 0, in.length);
        // The padding bytes are zero by default (Java zero-initializes arrays).
        return out;
    }

    static byte[] nullUnpad(byte[] in, int originalLength) {
        if (originalLength > in.length) {
            throw new IllegalArgumentException("Original length exceeds buffer");
        }
        // Verify the trailing bytes are zero (sanity check).
        for (int i = originalLength; i < in.length; i++) {
            if (in[i] != 0) {
                throw new IllegalArgumentException("Non-zero byte in null padding at offset " + i);
            }
        }
        return Arrays.copyOfRange(in, 0, originalLength);
    }

    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 = nullPad(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, int originalLength) 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 nullUnpad(out, originalLength);
    }

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

        // Case 1: block-aligned message (no padding).
        byte[] aligned = "0123456789abcdef".getBytes("UTF-8");
        byte[] alignedCipher = aesCbcEncrypt(key, iv, aligned);
        byte[] alignedRecovered = aesCbcDecrypt(key, iv, alignedCipher, aligned.length);
        System.out.println("Aligned length: " + aligned.length + ", padded length: " + nullPad(aligned).length);
        System.out.println("Aligned round trip ok: " + Arrays.equals(aligned, alignedRecovered));

        // Case 2: non-block-aligned message.
        byte[] message = "Null padding is simple but ambiguous.".getBytes("UTF-8");
        byte[] ciphertext = aesCbcEncrypt(key, iv, message);
        byte[] recovered = aesCbcDecrypt(key, iv, ciphertext, message.length);
        System.out.println("Message length: " + message.length + ", padded length: " + nullPad(message).length);
        System.out.println("Message round trip ok: " + Arrays.equals(message, recovered));
        System.out.println("Key        : " + Base64.getEncoder().encodeToString(key));
        System.out.println("IV         : " + Base64.getEncoder().encodeToString(iv));
        System.out.println("Plaintext  : " + new String(message, "UTF-8"));
        System.out.println("Ciphertext : " + Base64.getEncoder().encodeToString(ciphertext));

        // Case 3: message ends in zeros -- ambiguity demonstration.
        byte[] withZeros = new byte[] {0x01, 0x02, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00};
        byte[] withZerosCipher = aesCbcEncrypt(key, iv, withZeros);
        // Without the original length, the receiver might recover any of these.
        System.out.println("Original with-zeros length: " + withZeros.length);
        byte[] recovered3 = aesCbcDecrypt(key, iv, withZerosCipher, withZeros.length);
        System.out.println("Recovered length: " + recovered3.length + ", bytes: " + hex(recovered3));

        // Try recovering with a different (shorter) original length.
        byte[] shorter = aesCbcDecrypt(key, iv, withZerosCipher, 3);
        System.out.println("Shorter recovered length: " + shorter.length + ", bytes: " + hex(shorter));
        System.out.println("Ambiguity: receiver cannot tell which is correct without out-of-band length.");
    }

    private static String hex(byte[] b) {
        StringBuilder sb = new StringBuilder();
        for (byte v : b) sb.append(String.format("%02x", v & 0xFF));
        return sb.toString();
    }
}

Code Explanation Line by Line

The class NullPaddingDemo declares BLOCK = 16. The nullPad method computes N = (16 minus (in.length modulo 16)) modulo 16. The modulo operation makes N = 0 when the message is block-aligned, which is the rule that distinguishes null padding from the length-explicit schemes. The method allocates a new byte array of length in.length + N and copies the message into it; the padding bytes are zero by default because Java zero-initializes arrays.

The nullUnpad method takes an additional parameter originalLength, which is the original message length known out-of-band. The method verifies the trailing bytes between originalLength and the end of the buffer are all zero (a sanity check on the decryption), and then strips them by returning a copy of the first originalLength bytes. The sanity check is not a security feature; an attacker who controls the ciphertext can flip bits to make the trailing bytes non-zero, and the check will fail, but the failure only signals a corrupted decryption, not a specific attack.

The aesCbcEncrypt and aesCbcDecrypt methods implement AES in CBC mode manually. The decrypt method takes the originalLength parameter, which is passed to nullUnpad. The CBC chain is identical to the standard construction.

The main method runs three test cases. The aligned case (16 bytes) shows that null padding appends nothing when the message is block-aligned, which is the rule that distinguishes it from PKCS7. The non-aligned case (35 bytes) shows the round trip succeeds when the original length is provided. The with-zeros case (8 bytes ending in five zeros) demonstrates the ambiguity: the receiver can recover any of the lengths 3, 4, 5, 6, 7, or 8 from the same ciphertext, and the choice depends on the out-of-band length.

Sample Input and Output

Aligned length: 16, padded length: 16
Aligned round trip ok: true
Message length: 36, padded length: 48
Message round trip ok: true
Key        : q1w...your-base64-key-here...
IV         : e2r...your-base64-iv-here...
Plaintext  : Null padding is simple but ambiguous.
Ciphertext : aB3...your-base64-ciphertext-here...
Original with-zeros length: 8
Recovered length: 8, bytes: 0102030000000000
Shorter recovered length: 3, bytes: 010203
Ambiguity: receiver cannot tell which is correct without out-of-band length.

The aligned 16-byte message becomes 16 bytes after null padding (no padding appended). The 36-byte message becomes 48 bytes after null padding (12 trailing zeros appended). The with-zeros case shows the ambiguity: the same ciphertext can be unpadded to length 8 (the original) or to length 3 (a shorter message that happens to end before the zeros), and the receiver cannot tell which is correct without out-of-band information.

Common Mistakes to Avoid

The first mistake is using null padding when the message length is implicit in the ciphertext. The fundamental ambiguity of the scheme means the receiver cannot tell where the message ends. Always carry the original length in a length field outside the ciphertext, or use a length-explicit scheme such as PKCS7.

The second mistake is using null padding when the message can end in zeros. Even if the length is carried out-of-band, the trailing zeros in the message look identical to the trailing zeros in the padding, which makes debugging difficult. If the message format can end in zeros, use ISO 7816-4 bit padding (which uses a 0x80 marker) or PKCS7.

The third mistake is skipping the sanity check on the trailing bytes. The check verifies the trailing bytes between originalLength and the end of the buffer are all zero. A non-zero byte indicates a corrupted decryption or a wrong key. Skipping the check means the receiver accepts corrupt ciphertexts without warning.

The fourth mistake is using null padding in a network protocol. Network protocols should use AEAD ciphers such as AES-GCM or ChaCha20-Poly1305, which need no padding and provide authentication. Null padding with AES-CBC is acceptable for local storage of fixed-length records where the length is known from the record header, but not for network protocols.

Real-World Applications

Null padding is the default behavior of the OpenSSL command-line tool with the -nopad option, which is used to encrypt fixed-length files where the length is known from the filesystem metadata. The scheme is also used in some legacy mainframe record formats where the message length is fixed by the record descriptor word and the trailing zeros are pure padding.

The Kerberos v5 "aes256-cts-hmac-sha1-96" enctype uses a variant of null padding called ciphertext stealing, which avoids the ambiguity by using the last partial block to store the tail of the second-to-last full block. Ciphertext stealing is covered in a separate tutorial.

In modern systems, null padding is rare. The OpenSSL enc command defaults to PKCS7 padding for AES-CBC; the -nopad option is provided for users who know what they are doing. The JDK SunJCE provider does not expose null padding by name; the "AES/CBC/NoPadding" string means no padding at all, and the caller is responsible for ensuring the plaintext is a multiple of the block size, which is effectively the same as null padding when the caller appends zeros manually.

The pedagogical value of null padding is the contrast with PKCS7 and the length-explicit schemes. The fundamental ambiguity of the scheme is the reason the cryptographic community developed the length-explicit schemes: PKCS7 encodes the pad length in every padding byte, ISO 10126 and ANSI X9.23 encode it in the last byte, and ISO 7816-4 uses a 0x80 marker. The null padding java tutorial in this post is therefore best read as a lesson in why the length-explicit schemes exist.

Conclusion

In this null padding java tutorial we built null padding from scratch, demonstrated the ambiguity that arises when the message can end in zeros, and explained when the scheme is acceptable (length carried out-of-band, message known not to end in zeros) and when it is not (length implicit in the ciphertext, message can end in zeros). For new designs, prefer AEAD ciphers that need no padding. Next, study the PKCS7 and ISO 7816-4 length-explicit schemes, ciphertext stealing (which avoids the ambiguity), 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