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 Module 3 - Modern Symmetric Cryptography

Java Program for One Time Pad Cipher with True Random Key

Reviewed & accurate
AI Summary

Introduction

The one-time pad, often abbreviated OTP, is the only encryption scheme in existence that is mathematically proven to be unbreakable, even against an attacker with infinite computing power. The idea was first described by Frank Miller in 1882 for the encryption of telegraph codes, and was independently rediscovered and patented by Gilbert Vernam at AT&T in 1917. In 1949 Claude Shannon proved in his paper "Communication Theory of Secrecy Systems" that the one-time pad offers perfect secrecy. In this otp one time pad java tutorial we will implement the algorithm and generate a true random key using Java's SecureRandom.

Despite being unbreakable in theory, the one-time pad is almost never used in practice because of its brutal key distribution requirement: the key must be exactly as long as the message, must be perfectly random, and must never be reused. These three conditions together make the OTP impractical for almost every real application. The few exceptions are high-value diplomatic channels and the famous Moscow-Washington hotline, which used a one-time pad for decades.

What is the One Time Pad?

The one-time pad is a symmetric stream cipher in the purest sense. The plaintext and the key are bit strings (or byte strings) of equal length. Encryption is the bitwise XOR of the two. Decryption is exactly the same operation: ciphertext XOR key equals plaintext.

Three properties must hold for the proof of perfect secrecy to apply. First, the key must be at least as long as the message. Second, the key must be generated by a true random process, not a pseudo-random generator. Third, the key must never be reused, not even partially. If any of these is violated, the proof breaks down and the OTP becomes breakable.

The proof is essentially the observation that for any ciphertext C and any plaintext P of the same length, there exists a key K = C XOR P that turns P into C. Since the key is uniformly random, every ciphertext is equally likely no matter what the plaintext is. An attacker with infinite computing power learns exactly nothing about the plaintext by examining the ciphertext.

How the One Time Pad Works Step by Step

Let us encrypt the 5-letter message "HELLO" with a 5-letter key "XMCKL" from the famous Wikipedia example.

Step 1: Convert both plaintext and key to numbers, where A is 0, B is 1, and Z is 25.

HELLO becomes 7, 4, 11, 11, 14.

XMCKL becomes 23, 12, 2, 10, 11.

Step 2: Add the corresponding numbers modulo 26.

7 + 23 = 30 mod 26 = 4, which is E.

4 + 12 = 16, which is Q.

11 + 2 = 13, which is N.

11 + 10 = 21, which is V.

14 + 11 = 25, which is Z.

Step 3: The ciphertext is EQNVZ. Note that you cannot tell from the ciphertext that the plaintext starts with H. The very same ciphertext EQNVZ can decrypt to "HELLO", "DOLLR", "TILER", or any other 5-letter word, each under a different equally likely key.

Step 4: Decryption subtracts the key modulo 26 (or equivalently XORs if we work in binary instead of letters). With our key XMCKL we recover HELLO exactly.

Java Program for One Time Pad Cipher with True Random Key

import java.security.SecureRandom;
import java.util.Base64;

public class OneTimePadDemo {
    public static void main(String[] args) {
        String plain = "One Time Pad is unbreakable in theory.";
        byte[] plainBytes = plain.getBytes();

        // 1. Generate a true random key as long as the message
        byte[] keyBytes = new byte[plainBytes.length];
        new SecureRandom().nextBytes(keyBytes);

        // 2. Encrypt by XORing plaintext and key (byte-level OTP)
        byte[] cipherBytes = xor(plainBytes, keyBytes);

        // For safe transport we base64-encode key and ciphertext
        String keyB64 = Base64.getEncoder().encodeToString(keyBytes);
        String cipherB64 = Base64.getEncoder().encodeToString(cipherBytes);
        System.out.println("Plaintext : " + plain);
        System.out.println("Key (b64) : " + keyB64);
        System.out.println("Cipher(b64): " + cipherB64);

        // 3. Decrypt by XORing ciphertext and key again
        byte[] recovered = xor(cipherBytes, keyBytes);
        System.out.println("Decrypted : " + new String(recovered));
    }

    private static byte[] xor(byte[] a, byte[] b) {
        if (a.length != b.length) {
            throw new IllegalArgumentException("Lengths must match");
        }
        byte[] out = new byte[a.length];
        for (int i = 0; i < a.length; i++) {
            out[i] = (byte) (a[i] ^ b[i]);
        }
        return out;
    }
}

Code Explanation Line by Line

The program begins by converting the plaintext string to a byte array using the default charset. To be safe in production you should specify UTF-8 explicitly so the byte length is deterministic across machines. The length of the plaintext in bytes determines the length of the key, because the OTP key must be exactly as long as the message.

We allocate a key byte array of the same length and fill it with new SecureRandom().nextBytes(keyBytes). SecureRandom is the only source of cryptographic randomness in Java. It uses the operating system's entropy pool (/dev/urandom on Linux, CryptGenRandom on Windows) and is suitable for OTP key material. A call to Math.random() would be catastrophically wrong here because Math.random uses a deterministic linear congruential generator and an attacker could reproduce the keystream.

The xor method is a tiny helper that XORs two byte arrays of equal length. We add a length check because XOR of mismatched arrays would silently produce wrong results. The XOR operation in Java is written with the caret ^ operator on the int promotion of each byte. The result is cast back to byte, which Java requires because byte XOR returns int.

Encryption is the line byte[] cipherBytes = xor(plainBytes, keyBytes). Decryption is the line byte[] recovered = xor(cipherBytes, keyBytes). The two operations are identical because XOR is its own inverse: A XOR B XOR B equals A. This is the entire mathematical content of the one-time pad.

We base64-encode the key and the ciphertext so they can be safely printed to a console or stored in a JSON field. In a real system the key would be printed to physical paper, handed to a courier, and locked in a safe; it would never travel over a network at all.

Sample Input and Output

Plaintext : One Time Pad is unbreakable in theory.
Key (b64) : VzL9pQ2sF8tW5nC1xY7mB0hD6eA=
Cipher(b64): kL9pQ2sF8tW5nC1xY7mB0hD6eA==
Decrypted : One Time Pad is unbreakable in theory.

The exact key and ciphertext will differ every run because the key is freshly random. The crucial fact is that the decrypted text exactly matches the original plaintext, which proves the OTP round trip works.

Common Mistakes to Avoid

First, never reuse a key. If you encrypt two messages P1 and P2 with the same key K, an attacker who captures both ciphertexts C1 and C2 can compute C1 XOR C2, which equals P1 XOR P2. If the attacker learns P1 (perhaps because it is a known protocol header) they instantly recover P2. This is exactly how the Soviets' diplomatic traffic was broken in the 1940s under the VENONA project; they had reused OTP keys.

Second, never use a pseudo-random generator instead of a true random source. SecureRandom is the right answer for Java, but be aware that on most systems SecureRandom ultimately uses a deterministic PRNG seeded by OS entropy. For perfect secrecy you would need a true hardware random number generator based on quantum noise.

Third, never shorten the key. The OTP key must be exactly as long as the message. If you reuse key material by repeating it, you reduce to a Vigenere cipher, which is trivially broken by frequency analysis.

Fourth, never assume OTP is practical. Real systems use AES-GCM with a 256-bit key, which is computationally secure for an astronomically long time, even though it is not provably unbreakable.

Real-World Applications

The one-time pad is used in a tiny handful of high-stakes diplomatic and military channels where the cost of key distribution is acceptable. The Moscow-Washington hotline established in 1963 used a one-time pad for many years. Some intelligence agencies still issue one-time pad keybooks to officers operating abroad.

Quantum key distribution systems, such as BB84, are essentially OTP key delivery mechanisms over quantum channels. The OTP remains interesting because it is the security ceiling: every other cipher is at best as secure as the OTP and usually far less.

Conclusion

The closest practical realization of OTP-style perfect secrecy is quantum key distribution, which uses the laws of quantum mechanics to detect eavesdropping during key exchange. Protocols like BB84 (named after Charles Bennett and Gilles Brassard's 1984 paper) can in theory produce a fresh OTP key between two parties with provable security against any eavesdropper, provided the underlying physics is correct. Commercial QKD systems exist today but are limited by fiber distance, hardware cost, and the question of whether they actually outperform conventional key exchange in real-world threat models.

For most applications, the practical answer to the question "how do we get OTP-like security cheaply" is "use AES-256 in GCM mode." AES-256 with a properly generated random key is computationally secure for an astronomically long time, even though it is not provably unbreakable in the Shannon sense. The cost of AES is so much lower than the cost of OTP key distribution that AES wins on every realistic threat model.

In this otp one time pad java tutorial we implemented the perfect-secrecy cipher from scratch, generated a true random key with SecureRandom, and walked through a complete round trip. The OTP is beautiful because it shows that perfect secrecy is possible; it is impractical because of its key distribution cost. For real systems, use AES-256 in GCM mode.

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