One-Time Pad Cipher - Problem

Implement a one-time pad cipher system that provides perfect secrecy through cryptographically secure encryption and decryption.

A one-time pad cipher uses a random key that is:

  • At least as long as the plaintext
  • Used only once
  • Kept completely secret
  • Truly random

The cipher works by performing XOR operations between the plaintext and the key for encryption, and between the ciphertext and the same key for decryption.

Your task is to implement three functions:

  1. generateKey(length) - Generate a cryptographically secure random key
  2. encrypt(plaintext, key) - Encrypt plaintext using the key
  3. decrypt(ciphertext, key) - Decrypt ciphertext using the key

Input Format:

  • Operation type: "generate", "encrypt", or "decrypt"
  • For generate: length of key needed
  • For encrypt: plaintext string and key
  • For decrypt: ciphertext (as hex string) and key

Output Format:

  • For generate: random key as hex string
  • For encrypt: ciphertext as hex string
  • For decrypt: original plaintext string

Input & Output

Example 1 — Key Generation
$ Input: operation = "generate", data1 = "5", data2 = ""
Output: "a3f7c9b2d8"
💡 Note: Generate a 5-byte random key, output as hex string (10 characters). Each byte becomes 2 hex digits.
Example 2 — Encryption
$ Input: operation = "encrypt", data1 = "HI", data2 = "a3f7"
Output: "ebda"
💡 Note: Encrypt 'HI': H(0x48) XOR 0xa3 = 0xeb, I(0x49) XOR 0xf7 = 0xbe. Wait, let me recalculate: H(72) XOR 163 = 235 = 0xeb, I(73) XOR 247 = 182 = 0xb6. So output should be 'ebb6'.
Example 3 — Decryption
$ Input: operation = "decrypt", data1 = "ebb6", data2 = "a3f7"
Output: "HI"
💡 Note: Decrypt 'ebb6': 0xeb XOR 0xa3 = 0x48 (H), 0xb6 XOR 0xf7 = 0x49 (I). Original plaintext restored.

Constraints

  • 1 ≤ key length ≤ 1000
  • 1 ≤ message length ≤ 1000
  • Key must be at least as long as message
  • All hex inputs must be valid hexadecimal strings

Visualization

Tap to expand
One-Time Pad Cipher ImplementationINPUT: Key GenerationLength: 5Cryptographic RNGSecure Random BytesA3F7C9B2D8Generated Key (Hex)ALGORITHM: XOR Operations1Parse input operation type2Validate key length ≥ message3XOR each byte: text ⊕ key4Convert result to hex formatXOR OperationH (0x48) ⊕ 0xA3 = 0xEBI (0x49) ⊕ 0xF7 = 0xBERESULTPlaintext: HIKey: A3F7EBBEEncrypted OutputPerfect Secrecy:Unbreakablewithout keyKey Insight:XOR with truly random keys creates mathematically perfect encryption - the ciphertextreveals zero information about the plaintext without the exact key.TutorialsPoint - One-Time Pad Cipher | Cryptographically Secure Implementation
Asked in
Palantir 15 Northrop Grumman 12 Raytheon 10 Lockheed Martin 8
28.5K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen