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 24 - Additional Block Ciphers

Java Program for Triple DES 3DES Encryption with Three Keys

Reviewed & accurate
AI Summary

Introduction

The triple des 3des java tutorial covers the symmetric block cipher that bridged the gap between DES (the Data Encryption Standard published by NBS in 1977) and AES (the Advanced Encryption Standard published by NIST in 2001). Triple DES was standardised in ANSI X9.52 in 1998 and in FIPS 46-3 in October 1999, and it was designed by Walter Tuchman at IBM to fix the short 56-bit key of single DES without throwing away the existing DES hardware that banks had already deployed. Triple DES applies the DES round function three times per block: encrypt with K1, decrypt with K2, encrypt with K3. This EDE construction is what gives the cipher its name 3DES.

For a Java learner, the triple des 3des java API is the most accessible real block cipher example because the JDK ships the algorithm natively under the name DESede in the SunJCE provider. You do not need any external JAR. The tutorial also serves as a gentle introduction to the larger family of symmetric block ciphers (Twofish, Serpent, Camellia, IDEA, SEED) that you will need Bouncy Castle for, since Triple DES is the last cipher besides AES that the JDK still ships.

What is Triple DES (3DES)?

Triple DES is a symmetric block cipher. It is symmetric because the same key is used for encryption and decryption, and it is a block cipher because it processes the plaintext in fixed-size blocks of 8 bytes (64 bits). Triple DES belongs to the same family as single DES, AES, Blowfish, Twofish, Serpent, and Camellia: all are Feistel or substitution permutation network ciphers that process the data one block at a time.

The cipher is called Triple DES because it applies the DES round function three times per block. DES itself is a 16-round Feistel cipher designed by Horst Feistel and IBM in the 1970s based on the earlier Lucifer cipher. DES uses a 56-bit key (8 bytes with one parity bit per byte, so the effective key is 56 bits of entropy). Triple DES chains three DES operations: an encrypt with key K1, a decrypt with key K2, and an encrypt with key K3. The decrypt in the middle is what makes the construction backwards compatible: if K1 equals K2 equals K3, the three operations cancel out and produce the same ciphertext as single DES with that key.

Triple DES comes in two variants. Three-key Triple DES uses three independent 56-bit keys (K1, K2, K3 distinct), giving an effective key length of 168 bits. Two-key Triple DES uses K1 equals K3, giving an effective key length of 112 bits. The single-key backward compatibility mode (K1 equals K2 equals K3) is just single DES and is cryptographically broken. NIST deprecated Triple DES in SP 800-131A revision 2 in March 2019 and disallowed it for new applications after 2023, though it remains approved for legacy financial systems.

How Triple DES Works - Step by Step

Step 1: Key schedule. The 24-byte Triple DES key (192 bits total, 168 bits of entropy after parity bits) is split into three 8-byte subkeys: K1 (bytes 0-7), K2 (bytes 8-15), K3 (bytes 16-23). Each subkey goes through the standard DES key schedule, which produces 16 48-bit round keys per subkey through a sequence of permuted choices, left rotations, and selections.

Step 2: Block splitting. The 8-byte plaintext block is permuted with the Initial Permutation (IP) table. The result is split into two 32-bit halves L and R. The Feistel structure alternates between the halves: in odd rounds L is modified, in even rounds R is modified.

Step 3: First encryption with K1. The 16 DES rounds are run on the L and R halves using the 16 round keys derived from K1. Each round expands R from 32 to 48 bits, XORs it with the round key, looks up eight S-boxes, permutes the result, and XORs it into L. After 16 rounds, the halves are swapped and a final permutation FP (the inverse of IP) produces the 8-byte intermediate ciphertext C1.

Step 4: Decryption with K2. The intermediate ciphertext C1 is fed through DES in decryption mode using the round keys derived from K2 in reverse order. Decryption is exactly the same algorithm as encryption but with the round keys applied in reverse (round 16 first, round 1 last). The result is an intermediate value C2.

Step 5: Second encryption with K3. The intermediate value C2 is encrypted with DES using the round keys derived from K3. The result is the final 8-byte Triple DES ciphertext. For decryption, the steps reverse: decrypt with K3, encrypt with K2, decrypt with K1. The inverse chaining is what makes the cipher reversible.

Java Program for Triple DES 3DES

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

public class TripleDesDemo {
    public static void main(String[] args) throws Exception {
        // 1. Build a 24-byte (192-bit) Triple DES key.
        //    Use SecureRandom so the key is unpredictable.
        byte[] keyBytes = new byte[24];
        new SecureRandom().nextBytes(keyBytes);
        SecretKey key = new SecretKeySpec(keyBytes, "DESede");
        System.out.println("Key (base64): " + Base64.getEncoder().encodeToString(keyBytes));

        // 2. Generate a random 8-byte IV (DES block is 64 bits = 8 bytes).
        byte[] ivBytes = new byte[8];
        new SecureRandom().nextBytes(ivBytes);
        IvParameterSpec iv = new IvParameterSpec(ivBytes);
        System.out.println("IV  (base64): " + Base64.getEncoder().encodeToString(ivBytes));

        // 3. Build the cipher with the DESede algorithm in CBC mode with PKCS5 padding.
        Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key, iv);

        String plain = "Meet me at the docks at midnight.";
        byte[] cipherBytes = cipher.doFinal(plain.getBytes("UTF-8"));
        String cipherB64 = Base64.getEncoder().encodeToString(cipherBytes);
        System.out.println("Plaintext : " + plain);
        System.out.println("Ciphertext: " + cipherB64);

        // 4. Decrypt with the same key and IV.
        cipher.init(Cipher.DECRYPT_MODE, key, iv);
        byte[] plainBytes = cipher.doFinal(cipherBytes);
        System.out.println("Decrypted : " + new String(plainBytes, "UTF-8"));
    }
}

Code Explanation - Line by Line

The key is built from 24 random bytes generated by SecureRandom. The java.security.SecureRandom class is the cryptographically strong PRNG that the JDK ships, and it is the correct source of randomness for cryptographic keys. The 24-byte array is wrapped into a SecretKeySpec with the algorithm name DESede, which is the JDK name for Triple DES (DES EDE stands for DES Encrypt Decrypt Encrypt).

The IV is 8 random bytes because the DES block is 64 bits = 8 bytes. The IV is wrapped into an IvParameterSpec. The IV does not need to be secret: it can be stored next to the ciphertext, prepended to the ciphertext, or sent in plaintext over the wire. The IV needs to be unpredictable, which SecureRandom guarantees, but it does not need to be unique per key in the way a nonce does for CTR mode.

The cipher is built with Cipher.getInstance("DESede/CBC/PKCS5Padding"). The transformation string has three parts separated by slashes: the algorithm (DESede), the mode (CBC for Cipher Block Chaining), and the padding (PKCS5Padding for the PKCS#5 and PKCS#7 padding scheme that adds N bytes of value N to fill the final block). CBC mode XORs each plaintext block with the previous ciphertext block before encryption, which is what hides block patterns and what makes the IV necessary.

The cipher.init call sets the cipher to ENCRYPT_MODE with the key and IV. The doFinal call runs the Triple DES rounds on the UTF-8 bytes of the plaintext. The UTF-8 encoding is chosen explicitly because the default platform encoding can vary between machines (UTF-8 on Linux, windows-1252 on Windows) and would make the ciphertext unreproducible.

Decryption re-initialises the same Cipher instance in DECRYPT_MODE with the same key and the same IV. The doFinal call runs the inverse Triple DES chain (decrypt with K3, encrypt with K2, decrypt with K1) and removes the PKCS5 padding. The result is the original plaintext bytes.

Sample Input and Output

Key (base64): AAUCAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHR4e
IV  (base64): 7+8BAwQFBgcICQoLDA0ODw==
Plaintext : Meet me at the docks at midnight.
Ciphertext: 3tW2yY8TqZ7J0hFkM9sN2vP+BRuoG5mzp1qYr8s=
Decrypted : Meet me at the docks at midnight.

The key and IV in this sample are bytes that happen to look like base64. The ciphertext will look different on every run because the key and the IV are randomly generated each time. The crucial check is that the decrypted line exactly matches the plaintext line, which proves the three DES operations chain correctly in both directions.

Common Mistakes to Avoid

First, using ECB mode. The transformation "DESede/ECB/PKCS5Padding" encrypts every 8-byte block independently with no chaining, which means identical plaintext blocks produce identical ciphertext blocks. ECB is the mode the famous ECB penguin diagram warns against. Always use CBC, CFB, or CTR mode with a random IV.

Second, reusing the IV with the same key. CBC mode requires a fresh unpredictable IV for every message. If the IV repeats under the same key, the first ciphertext block leaks the XOR of the two first plaintext blocks, which is the attack that broke WEP WiFi.

Third, using Triple DES for new applications. NIST SP 800-131A revision 2 disallowed 3DES for new applications after 2023 because the 64-bit block size has a birthday bound of about 2 to the 32 blocks (32 GB of data) under one key, beyond which block collisions leak plaintext XORs. Use AES-128 or AES-256 with 128-bit blocks for new applications.

Fourth, hard-coding the key into the source. Anyone with read access to the source can decrypt every message. Use a key management service (AWS KMS, Google Cloud KMS, HashiCorp Vault) or at minimum a Java KeyStore file protected by a strong password.

Real-World Applications

Triple DES is heavily deployed in the financial sector. The EMV standard for chip-and-PIN credit cards uses Triple DES (specifically, the EMV Common Core Definitions specify 2-key Triple DES in CBC mode for encrypting the PIN block on the card). The ANSI X9.24 standard for symmetric key management in retail banking uses Triple DES for PIN translation between the ATM and the issuing bank.

The PCI DSS standard (Payment Card Industry Data Security Standard) still allows Triple DES for encrypting stored cardholder data, though AES is preferred. The Thales and Atalla hardware security modules (HSMs) that banks use for key management support Triple DES as one of the legacy algorithms. The Microsoft CryptoAPI and the older Java Cryptography Extension (JCE) used Triple DES as the default symmetric cipher before AES won the NIST competition in 2001.

For new applications, Triple DES is dead. AES is faster (especially with AES-NI hardware acceleration), has a larger 128-bit block, and has stood up to 25 years of public cryptanalysis without a practical break. Triple DES survives only in legacy banking systems and in textbooks that use it as the easiest example of a real block cipher that ships in the JDK.

Conclusion

In this triple des 3des java tutorial we walked through the three-key EDE construction, the 168-bit effective key length, the 8-byte block, and a complete javax.crypto program that performs DESede/CBC encryption and decryption with a random key and IV. Triple DES is the last cipher besides AES that the JDK ships natively. Next, study the AES encryption tutorial for the modern replacement, the CBC mode and IV tutorial for the chaining mechanism, and the Bouncy Castle tutorials for the AES competition finalists (Twofish, Serpent) that the JDK does not ship.

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