Skip to content

Instantly share code, notes, and snippets.

@vaibhavsingh97
Created September 6, 2017 06:31
Show Gist options
  • Save vaibhavsingh97/461f7138ccf4c0b2841bf3e2cedd0cdc to your computer and use it in GitHub Desktop.
Save vaibhavsingh97/461f7138ccf4c0b2841bf3e2cedd0cdc to your computer and use it in GitHub Desktop.
import sys
import numpy as np
from math import sqrt
import string
from clint.textui import colored, puts
class HillCipher():
"""docstring for Hillcypher"""
def __init__(self):
self.alpha = ' ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]_~"#$%&()*+,-./0123456789:;<=>?'
self.pattern = []
self.dictionary = dict([self.alpha[i], i * 1]
for i in range(len(self.alpha)))
self.pattern = []
self.dictionary = dict([self.alpha[i], i * 1]
for i in range(len(self.alpha)))
self.key_list = []
n = int(sqrt(len(key)))
for i in key:
self.key_list.append(self.dictionary[i])
self.key_matrix = []
for i in range(n):
self.key_matrix.append(self.key_list[i * n: i * n + n])
def encrypt(self, message, key):
n = int(sqrt(len(key)))
if n * n != len(key):
puts(colored.red("Invalid key length, Must be square-root\nExiting ..."))
sys.exit(0)
message_list = []
for i in message:
message_list.append(self.dictionary[i])
message_matrix = []
for i in range(round(len(message) / n)):
message_matrix.append(message_list[i * n: i * n + n])
for i in message_matrix:
self.pattern.append(len(i))
if len(i) < n:
i.append(0)
encrypted_matrix = np.matmul(message_matrix, self.key_matrix) % 26
encrypted_message = ''
inv_dictionary = {v: k for k, v in self.dictionary.items()}
for i in encrypted_matrix:
for value in i:
encrypted_message += inv_dictionary.get(value)
return encrypted_message
def decrypt(self, message, key):
n = int(sqrt(len(key)))
message_list = []
for i in message:
message_list.append(self.dictionary[i])
message_matrix = []
for i in range(round(len(message) / n)):
message_matrix.append(message_list[i * n: i * n + n])
determinant = np.linalg.det(self.key_matrix).round() % 26
transpose = transpose = np.transpose(self.key_matrix)
decrypted_matrix = np.matmul(
message_matrix, (transpose * determinant) % 26) % 26
decrypted_message = ''
inv_dictionary = {v: k for k, v in self.dictionary.items()}
for i in decrypted_matrix:
for value in i:
decrypted_message += inv_dictionary.get(value)
return decrypted_message
if __name__ == '__main__':
key = "GYBNQKURPGYBNQKU"
raw_message = "A QUICK BROWN FOX JUMPS OVER A LAZY DOG"
puts(colored.blue("Encrypted Message: " +
HillCipher().encrypt(raw_message, key)))
puts(colored.blue("Decrypted Message: " +
HillCipher().decrypt(HillCipher().encrypt(raw_message, key), key)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment