The Vernam Cipher
The Vernam Cipher is based on the principle that each plaintext character from a message is ‘mixed’ with one character from a key stream. If a truly random key stream is used, the result will be a truly ‘random’ ciphertext which bears no relation to the original plaintext.
How does it work?
Let’s say we have a word “secret” and we want to encrypt with the key “key”. The length of the key (3) is obviously shorter than the length of the message (6). In this case, we repeat the key until it reaches the length of the plain message. The encryption key will be “keykey”.
Next, we have to convert both the plain text and the key to binary.
Plain text message in binary:
011100110110010101100011011100100110010101110100
The key in binary:
011010110110010101111001011010110110010101111001
Finally, we have to XOR these two binary values to get the encrypted message.
0 ⊕ 0 = 0
0 ⊕ 1 = 1
1 ⊕ 0 = 1
1 ⊕ 1 = 0
Encrypted message:
000110000000000000011010000110010000000000001101
Encryption
The encrypt method takes 2 parameters a key and a message, which are required for the encryption. I initialized an index variable with a value of 0. It’s used for keeping track of the key length. The loop goes through the message character by character. In the loop, I calculate the ASCII code for the current character both in the message and key, then perform a XOR operation on those values. I convert this back to a single char (might be a gibberish value) and append it to the encrypted_message
variable. After this, the index needs to be incremented. If the index equals with the length of the key, then I set the index back to 0 to prevent possible index out of range exceptions.
Decryption
As for the decryption, the procedure is almost exactly the same. The only thing that differs from the encryption is that I converted the encrypted message to binary, which is required for binary operations.
The full source code
I created a command line program to make the code more usable. Actually, I just added some command line arguments. Anyway, I hope you like it!
Feel free to download and experiment with the code!
Before you go
Thank you for taking the time to read my walkthrough. If you found it helpful, please hit the 👏 button 👏 (up to 50x) and share it to help others with similar interest find it! + Feedback is always welcome! 🙏