Skip to content

Instantly share code, notes, and snippets.

@scottjacksonx
Created March 22, 2010 18:06
Show Gist options
  • Save scottjacksonx/340333 to your computer and use it in GitHub Desktop.
Save scottjacksonx/340333 to your computer and use it in GitHub Desktop.
# Globals
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
### Basic Conversion Functions
def letterToNumber(letter):
"""
Returns the number (0-25) equivalent of a letter.
"""
return alphabet.index(letter)
def numberToLetter(num):
"""
Returns the letter (a-z) equivalent of a number.
"""
return alphabet[num%26]
def textAsNumbers(string):
"""
Converts a string into a list of numbers, one for each letter.
"""
nums = []
for char in string:
nums.append(letterToNumber(char))
return nums
def numbersAsText(list):
"""
Converts a list of numbers into a string.
"""
string = ""
for n in list:
string += numberToLetter(n)
return string
def shiftDecrypt(ciphertext, key):
"""
Uses key to decrypt ciphertext with a shift cipher.
"""
numbers = textAsNumbers(ciphertext)
plainNumbers = []
for n in numbers:
n = (n - key) % 26
plainNumbers.append(n)
plaintext = numbersAsText(plainNumbers)
return plaintext
ciphertext = "uqslziolqnmirijtsoagqulkmxwkmhvfkzjbqhvmagqzdysmyckyallnzyvr"
keys = textAsNumbers("must")
groups = ["","","",""]
# Sort the ciphertext into the four groups.
for i in range(0, len(ciphertext)):
groups[i%4] += ciphertext[i]
# Decrypt each group with a key of one letter of the keyword.
for i in range(0,4):
groups[i] = shiftDecrypt(groups[i], keys[i])
#Put the four groups back together to form the plaintext.
plaintext = ""
for i in range(0,15):
plaintext += groups[0][i] + groups[1][i] + groups[2][i] + groups[3][i]
print plaintext
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment