Skip to content

Instantly share code, notes, and snippets.

@JoeBlakeB
Last active October 8, 2022 19:40
Show Gist options
  • Select an option

  • Save JoeBlakeB/54324f9b6fc55ba79a6fc5de5158c62d to your computer and use it in GitHub Desktop.

Select an option

Save JoeBlakeB/54324f9b6fc55ba79a6fc5de5158c62d to your computer and use it in GitHub Desktop.
A basic Vernam Cipher to demonstrate using XOR to encode a message.
#!/usr/bin/env python3
#
# A basic cipher using XOR to encode a message using a password of the same
# length. The script takes two arguments, the message and the password.
# Decoding works exactly the same way except the message is replaced with
# the encoded message, and the same password must be used
#
# Usage:
# ./VernamCipher.py {message} {password}
#
# Examples:
# ./VernamCipher.py "Hello World" HFEFHYDEFGD
# ABPOJEVKUNA
# ./VernamCipher.py ABPOJEVKUNA HFEFHYDEFGD
# HELLO WORLD
#
# Copyright (C) 2020 Joe Baker (JoeBlakeB)
# This program is free software under the GPLv3 license.
#
import sys
if len(sys.argv) > 1:
input1 = sys.argv[1].upper()
else:
print("You didn't specify an input")
exit()
if len(sys.argv) > 2:
input2 = sys.argv[2].upper()
else:
print("You did't specify an OPT")
exit()
if len(input1) != len(input2):
print("The OTP is not the same length as the message")
exit()
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ,. '?!"
for inputs in [input1, input2]:
for letter in inputs:
if letter not in alphabet:
print(letter, "is not a valid character.")
exit()
output = ""
def xor(a, b):
a = int(a)
b = int(b)
if a + b == 1:
return 1
else:
return 0
def xorDecimal(a, b):
a = format(a, "05b")
b = format(b, "05b")
c = ""
for i in range(5):
c += str(xor(a[i], b[i]))
return int(c, 2)
for i in range(len(input1)):
input1Letter = input1[i]
input2Letter = input2[i]
input1Number = alphabet.index(input1Letter)
input2Number = alphabet.index(input2Letter)
outputNumber = xorDecimal(input1Number, input2Number)
outputLetter = alphabet[outputNumber]
output += outputLetter
print(output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment