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:
generateKey(length)- Generate a cryptographically secure random keyencrypt(plaintext, key)- Encrypt plaintext using the keydecrypt(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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code