I Heard, You Like Classic Stuff?

I had the classic encryption algorithm as follows:

import string

alphabet = list(string.ascii_uppercase)

def generate_codeword(k):
	k = list(k)
	matrix = []
	for h in range(0, len(k), 1):
		for i in range(0, len(alphabet), 1):
			prematrix = []
			if k[h] == alphabet[i]:
				for j in range(0, len(k), 1):
					if i+j > 25:
						x = i+j - 26
						prematrix.append(alphabet[x])
					else:
						prematrix.append(alphabet[i+j])
				matrix.append(prematrix)
	return matrix

def encrypt(codeword, message):
	message = list(message)
	cipher = []
	for m in message:
		for i in xrange(len(k)):
			for j in xrange(len(k)):
				if m == codeword[i][j]:
					cipher.append((i, j))
					if len(cipher) == len(message):
						return cipher

def decrypt(codeword, cipher):
	message = []
	for i in xrange(len(cipher)):
		for j in xrange(len(cipher)-1):
			try:
				x, y = cipher[i][j], cipher[i][j+1]
				message.append(codeword[x][y])
			except:
				pass
	return ''.join(message)

if __name__ == '__main__':
	k = 'MARY'
	codeword = generate_codeword(k)
	message = 'CRYPTO'

	cipher =  encrypt(codeword, message)
	print cipher

	message2 = decrypt(codeword, cipher)
	print message2

	assert message2 == message

Try reading for a moment..

Easy right?

Try decryption cipher below.

(8,1), (7,8), (1,1), (2,6),
(5,5), (7,5), (11, 7), (7,8), (5,7), (8,11),
(9,1),(3,1)
(6,1), (7,5), (7,6), (7,5), (1,10), (2,5), (7,5), (7,4),
(2,7), (11,2)
(3,9), (1,11)
(6,3), (7,8), (7,5)
(11,6), (7,9), (1,5), (9,8), (1,4), (7,5)
(3,1), (5,9), (6,4), (8,8), (5,10), (7,5)
(3,11), (9,1), (1,8), (7,8), (7,5), (9,10)

Don’t forget the classics!

Advertisements

2 thoughts on “I Heard, You Like Classic Stuff?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s