Skip to content

Instantly share code, notes, and snippets.

@pbexe
Last active November 2, 2016 20:42
Show Gist options
  • Save pbexe/a654630766a102e22b84268381b040d9 to your computer and use it in GitHub Desktop.
Save pbexe/a654630766a102e22b84268381b040d9 to your computer and use it in GitHub Desktop.
Example of Caesar and Vernam cipher encoders and decoders
import math
def encode(string, rot):
phrase = string.lower().replace(" ", "")
out = ""
a = "abcdefghijklmnopqrstuvwxyz"
for char in phrase:
out += a[(a.index(char)+rot) % 26]
return out
def decode(string):
d = {"a":8.167, "b":1.492, "c":2.782, "d":4.253, "e":12.70, "f":2.228, "g":2.015, "h":6.094, "i":6.966, "j":0.153, "k":0.772, "l":4.025, "m":2.406, "n":6.749, "o":7.507, "p":1.929, "q":0.095, "r":5.987, "s":6.327, "t":9.056, "u":2.758, "v":0.978, "w":2.360, "x":0.150, "y":1.974, "z":0.074}
a = "abcdefghijklmnopqrstuvwxyz"
entropies = []
for i in range(1, 27):
total = 0
out = ""
for char in string:
out += a[(a.index(char)+i) % 26]
for char in out:
total += - math.log(d[char]) / math.log(2)
entropies.append([total, i])
lowest = [0,0]
for x in entropies:
if x[0] < lowest[0]:
lowest = x
lowest.append(encode(string, - lowest[1]))
return lowest
def vernam(string, key):
key = key[:len(string)]
x=""
for char, pos in zip(string, key):
x+= chr(ord(char) ^ ord(pos))
return x
encoded = encode(raw_input("Caesar Cyper text >>> "), int(raw_input("ROT >>> ")))
print "Encoded:", encoded
decoded = decode(encoded)
print "Decoded:", decoded[2],"\nROT:", decoded[1],"\nEntropy:", decoded[0]
key = raw_input("Vernam key >>> ")
encoded = vernam(raw_input("Message >>> "), key)
print "Encoded:", encoded
decoded = vernam(encoded, key)
print "Decoded:", decoded
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment