Classic Encryption: Four Square

Simple encryption based on classic four square


import random

chars = range(65,91)
chars.pop(16)

def make_array(input):
        arr = []
        li = []
        for i in range(0, len(input)):
                if i % 5 == 0 and i:
                        arr.append(li)
                        li = []
                li.append(chr(input[i]))
        arr.append(li)
        return arr

random.shuffle(chars)
b1 = make_array(chars)
random.shuffle(chars)
b2 = make_array(chars)
random.shuffle(chars)
b3 = make_array(chars)
random.shuffle(chars)
b4 = make_array(chars)

def tokenize(input):
        for i in range(0, len(input), 2):
                yield "%s%s" %(input[i], input[i+1])

def find(ch, block):
        for i in range(0, len(block)):
                for j in range(0, len(block[i])):
                        if ch == block[i][j]:
                                return i, j
def encrypt(input):
        first = find(input[0], b1)
        second = find(input[1], b4)
        return "%s%s" %(b2[first[0]][second[1]], b3[second[0]][first[1]])
        return first, second

def decrypt(input):
        first = find(input[0], b2)
        second = find(input[1], b3)
        return "%s%s" %(b1[first[0]][second[1]], b4[second[0]][first[1]])
        return first, second

def print_block():
        for i in range(0, len(b1)):
                print " ".join(b1[i]), "   ", " ".join(b2[i])

        print "\n"
        for i in range(0, len(b1)):
                print " ".join(b3[i]), "   ", " ".join(b4[i])

input = raw_input("Input: ")
input = input.upper()

if len(input) % 2 != 0:
        input = input[:-1]

print_block()

encrypted = "".join([encrypt(i) for i in tokenize(input)])
print "Encrypted: ", encrypted

decrypted = "".join([decrypt(i) for i in tokenize(encrypted)])
print "Decrypted: ", decrypted

fs3 fs2 fs1

Advertisements

Published by

Chandan Dutta Chowdhury

Software Engineer

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