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 PKCS5 Padding for 8 Byte Block Ciphers

Reviewed & accurate
AI Summary

Introduction

The pkcs5 padding java tutorial walks through the padding scheme defined in Public Key Cryptography Standard 5 (PKCS5), published by RSA Laboratories in 1993 as part of the PKCS family. PKCS5 specifies password-based encryption (PBE) for the 8-byte DES block and defines the padding rule that bears its name. The rule is simple: to pad a message to a multiple of 8 bytes, append N bytes each with the value N, where N is between 1 and 8. If the message is already a multiple of 8, append a full extra block of eight 0x08 bytes.

For a Java learner the pkcs5 padding java example below matters because the JDK provider "DES/CBC/PKCS5Padding" and the historical "AES/CBC/PKCS5Padding" both implement the PKCS7 rule (the generalization of PKCS5 to any block size). The JDK kept the PKCS5 name for historical compatibility even after AES made 16-byte blocks the default, which is why the symbol "PKCS5Padding" appears in Java code that processes AES.

This tutorial implements PKCS5 from scratch with DES as the block cipher, matches it against the JDK DES/CBC/PKCS5Padding provider, and shows the always-pad-a-full-block rule that makes PKCS5 unambiguous.

What is PKCS5 Padding?

pkcs5 padding java is a byte-level padding scheme for block ciphers with an 8-byte block size. The scheme belongs to the family of length-explicit padding schemes that encode the pad length in every padding byte. Other schemes in the family are PKCS7 (generalized to any block size), ISO 10126 (random bytes plus length), and ANSI X9.23 (zero bytes plus length). The common ancestor is ISO/IEC 9797-1 Padding Method 1.

In PKCS5 the pad length N is computed as 8 minus (message length modulo 8). If the message length modulo 8 is zero, then N equals 8; that is, a full block of padding is appended. The padding bytes are N copies of the value N. The receiver reads the last byte as N, verifies that the last N bytes all equal N, and strips them.

The always-pad-a-full-block rule is the defining property of PKCS5 and PKCS7. Without it, a message that ends in a byte equal to the pad length would be ambiguous; the receiver could not tell whether that byte was data or padding. By always appending at least one byte, PKCS5 makes the padding byte mandatory and the unpadding unambiguous.

PKCS5 is identical to PKCS7 when the block size is 8. The difference is only the block size constraint: PKCS5 is defined only for 8-byte blocks; PKCS7 is defined for any block size up to 256 bytes. With AES (16-byte block) the correct term is PKCS7, although the JDK uses the name PKCS5Padding for historical reasons.

How PKCS5 Padding Works Step by Step

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

Step 2: Build the padding bytes. The padding is N copies of the byte N. For N=5 the padding is the byte sequence 0x05, 0x05, 0x05, 0x05, 0x05. For N=8 (block-aligned message) the padding is eight 0x08 bytes.

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

Step 4: Encrypt with the block cipher (DES, 3DES, or any 8-byte cipher in CBC or ECB mode). The cipher processes the padded message in 8-byte blocks.

Step 5: After decryption, unpad. Read the last byte as N. Verify N is between 1 and 8. Verify the last N bytes all equal N. Strip the last N bytes.

Step 6: Detect tampering. If the padding is malformed (N out of range or the last N bytes do not all equal N), the receiver must reject the message. The check must be constant-time; leaking the difference between "bad N value" and "bad Nth byte" enables the Vaudenay padding oracle attack.

Java Program for PKCS5 Padding for 8 Byte Block Ciphers


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

    private static final int BLOCK = 8; // PKCS5 is defined for 8-byte blocks

    static byte[] pkcs5Pad(byte[] in) {
        int n = BLOCK - (in.length % BLOCK);
        byte[] out = new byte[in.length + n];
        System.arraycopy(in, 0, out, 0, in.length);
        for (int i = in.length; i < out.length; i++) {
            out[i] = (byte) n;
        }
        return out;
    }

    static byte[] pkcs5Unpad(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) {
            throw new IllegalArgumentException("Invalid pad value " + n);
        }
        for (int i = in.length - n; i < in.length; i++) {
            if ((in[i] & 0xFF) != n) {
                throw new IllegalArgumentException("Malformed PKCS5 padding");
            }
        }
        return Arrays.copyOfRange(in, 0, in.length - n);
    }

    // Manual DES/CBC implementation using DES/ECB/NoPadding as the primitive.
    static byte[] desCbcEncrypt(byte[] key, byte[] iv, byte[] plaintext) throws Exception {
        Cipher des = Cipher.getInstance("DES/ECB/NoPadding");
        des.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "DES"));

        byte[] padded = pkcs5Pad(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 = des.doFinal(t);
            System.arraycopy(c, 0, out, off, BLOCK);
            prev = c;
        }
        return out;
    }

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

        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 = des.doFinal(c);
            for (int i = 0; i < BLOCK; i++) {
                out[off + i] = (byte) (t[i] ^ prev[i]);
            }
            prev = c;
        }
        return pkcs5Unpad(out);
    }

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

        String message = "DES still appears in legacy payment systems.";
        byte[] plaintext = message.getBytes("UTF-8");

        byte[] ciphertext = desCbcEncrypt(key, iv, plaintext);
        byte[] recovered = desCbcDecrypt(key, iv, ciphertext);

        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);
        System.out.println("Padded len : " + pkcs5Pad(plaintext).length);
        System.out.println("Ciphertext : " + Base64.getEncoder().encodeToString(ciphertext));
        System.out.println("Recovered  : " + new String(recovered, "UTF-8"));
        System.out.println("Round trip ok: " + Arrays.equals(plaintext, recovered));

        // Cross-check against the JDK DES/CBC/PKCS5Padding provider.
        Cipher jdk = Cipher.getInstance("DES/CBC/PKCS5Padding");
        jdk.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "DES"), new IvParameterSpec(iv));
        byte[] jdkCiphertext = jdk.doFinal(plaintext);
        System.out.println("JDK match  : " + Arrays.equals(ciphertext, jdkCiphertext));

        // Block-aligned case: PKCS5 must add a full extra block of 0x08.
        byte[] aligned = "12345678".getBytes("UTF-8");
        byte[] alignedPadded = pkcs5Pad(aligned);
        System.out.println("Aligned len: " + aligned.length + ", padded len: " + alignedPadded.length);
        System.out.println("Last pad byte: 0x" + Integer.toHexString(alignedPadded[alignedPadded.length - 1] & 0xFF));
    }
}

Code Explanation Line by Line

The class Pkcs5PaddingDemo declares a single constant BLOCK = 8. The pkcs5Pad method computes N = 8 minus (in.length modulo 8) and appends N copies of the byte N. The pkcs5Unpad method reads the last byte as N, validates N is between 1 and 8 (the only legal values for an 8-byte block), and verifies every one of the last N bytes equals N before stripping them. The validation step is critical for security.

The desCbcEncrypt and desCbcDecrypt methods implement DES in CBC mode manually, using DES/ECB/NoPadding as the block primitive. The CBC chain XORs the previous ciphertext block with the current plaintext block before encryption. The decrypt routine mirrors the encrypt routine with the order of encrypt and XOR reversed.

The main method performs the round trip and cross-checks against the JDK DES/CBC/PKCS5Padding provider, confirming that the manual implementation produces byte-identical ciphertext. The cross-check is the strongest test: if our manual padding and CBC implementation were wrong in any byte, the comparison would fail.

The block-aligned case ("12345678", 8 bytes) is the test that distinguishes PKCS5 from naive trailing-zero padding. A naive scheme would add nothing and become ambiguous; PKCS5 always adds a full block of 0x08 bytes. The test prints the last padding byte as 0x8, confirming the always-pad rule.

Sample Input and Output

Key        : abc...your-base64-key-here...
IV         : def...your-base64-iv-here...
Plaintext  : DES still appears in legacy payment systems.
Plaintext len: 42
Padded len : 48
Ciphertext : gH4...your-base64-ciphertext-here...
Recovered  : DES still appears in legacy payment systems.
Round trip ok: true
JDK match  : true
Aligned len: 8, padded len: 16
Last pad byte: 0x8

The 42-byte plaintext becomes 48 bytes after PKCS5 padding, with six trailing 0x06 bytes. The 8-byte block-aligned plaintext becomes 16 bytes after PKCS5 padding, with a full extra block of 0x08 bytes. The JDK match line confirms that the manual PKCS5 and DES/CBC implementation is byte-identical to the JDK provider.

Common Mistakes to Avoid

The first mistake is using PKCS5 with AES. PKCS5 is defined for 8-byte blocks; using it with AES (16-byte block) is technically incorrect, although the JDK "AES/CBC/PKCS5Padding" provider applies the PKCS7 rule and so works correctly. The correct term for AES is PKCS7. Always use "PKCS5Padding" with DES or 3DES, and prefer "PKCS7Padding" (or, more pragmatically, an AEAD cipher that needs no padding at all) with AES.

The second mistake is skipping the always-pad-a-full-block rule. If the pad length is zero (message length is a multiple of 8) and you skip the padding, the receiver cannot tell whether the last byte is data or a pad-length byte. Always compute N = 8 minus (L modulo 8), which gives N = 8 when L is a multiple of 8.

The third mistake is a non-constant-time unpad check. The Vaudenay padding oracle attack (2002) exploits any timing or error-message difference between a valid and invalid padding. The check must iterate over every padding byte even if one byte is wrong; the error must be the same for every failure mode. The Encrypt-then-MAC construction (verify the MAC before checking the padding) eliminates the attack entirely.

The fourth mistake is shipping DES in 2024. DES has a 56-bit key and is brute-forceable in hours on commodity hardware. 3DES is better but slow and deprecated for new designs. For new systems, use AES-128 or AES-256 in GCM mode, which needs no padding and provides authentication.

Real-World Applications

PKCS5 padding was the standard padding for DES-based systems throughout the 1990s and 2000s. It appears in legacy Kerberos v5 (with AES, under the name "aes256-cts-hmac-sha1-96"), in legacy S/MIME email (with 3DES), in legacy Java keystores (JKS files), and in legacy financial messaging standards such as ISO 8583 over leased lines. The padding is also the default for OpenSSL's enc -des-cbc command and for the BouncyCastle DES/CBC/PKCS5Padding provider.

The Java PKCS5Padding name survives in the JDK provider strings "DES/CBC/PKCS5Padding", "DESede/CBC/PKCS5Padding", and "AES/CBC/PKCS5Padding". The AES provider uses the PKCS5 name for historical compatibility even though the rule is PKCS7. The BouncyCastle provider accepts both "PKCS5Padding" and "PKCS7Padding" as aliases.

In modern systems PKCS5 padding is mostly a historical artifact. New designs use AES-GCM or ChaCha20-Poly1305, which need no padding. The padding-oracle class of attacks (Vaudenay 2002, POODLE 2014, Lucky 13 2013) makes CBC with PKCS5/PKCS7 padding a poor choice for network protocols; TLS 1.3 therefore removed CBC entirely. The pkcs5 padding java tutorial in this post is best read as educational background for legacy maintenance and as a contrast to the AEAD default.

The PKCS5 standard also defined password-based key derivation (PBKDF1) and the PBES1 encryption scheme, both of which are obsolete. The successor, PBKDF2, is still widely used for password hashing and is the default KDF in WPA2, Wi-Fi Protected Setup, and the JWT encryption header. PBKDF2 is covered in a separate tutorial.

Conclusion

In this pkcs5 padding java tutorial we built PKCS5 from scratch, matched it against the JDK provider, and explained the always-pad-a-full-block rule that makes PKCS5 unambiguous. PKCS5 is the historical padding for DES and 3DES; for AES the correct term is PKCS7. For new designs, prefer AEAD ciphers that need no padding. Next, study the PKCS7 generalization, the ISO 10126 and ANSI X9.23 alternatives, 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