Created
December 16, 2018 07:21
-
-
Save WangYihang/cff3e87f530eb543343607268bafeca8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# encoding: utf-8 | |
import numpy as np | |
def twist(data, size): | |
matrix = [] | |
for i in range(0, len(data), size): | |
d = [] | |
for j in range(size): | |
d.append(ord(data[i + j]) - ord('a')) | |
matrix.append(d) | |
return np.asarray(matrix).T | |
def untwist(data, size): | |
result = "" | |
for line in data.T: | |
for i in line: | |
result += chr(int(round(i)) % 26 + ord('a')) | |
return result | |
def encrypt(plain, key): | |
print "Enc: " | |
print "Key: %s" % (key) | |
matrix = twist(plain, len(key)) | |
print "Plain: %s" % (matrix) | |
cipher = np.dot(key, matrix) | |
print "Cipher: %s" % (cipher) | |
return cipher | |
return untwist(cipher, len(key)) | |
def Encrypt(plain, key): | |
print "Enc: " | |
print "Key: %s" % (key) | |
# matrix = twist(plain, len(key)) | |
matrix = plain | |
print "Plain: %s" % (matrix) | |
cipher = np.dot(key, matrix) | |
print "Cipher: %s" % (cipher) | |
return cipher | |
# return untwist(cipher, len(key)) | |
def decrypt(cipher, key): | |
print "Dec: " | |
yek = np.linalg.inv(key) | |
print "Key: %s" % (yek) | |
matrix = twist(cipher, len(key)) | |
print "Cipher: %s" % (matrix) | |
plain = np.dot(yek, matrix) | |
print "Plain: %s" % (plain) | |
return untwist(plain, len(key)) | |
def Decrypt(cipher, key): | |
print "Dec: " | |
yek = np.linalg.inv(key) | |
print "Key: %s" % (yek) | |
# matrix = twist(cipher, len(key)) | |
matrix = cipher | |
print "Cipher: %s" % (matrix) | |
plain = np.dot(yek, matrix) | |
print "Plain: %s" % (plain) | |
return plain | |
# return untwist(plain, len(key)) | |
key = np.asarray([[6, 24, 17], [13, 15, 10], [20, 16, 1]]) | |
key = np.asarray([[5, 23, 16], [12, 14, 9], [19, 15, 0]]) | |
''' | |
qbuquagnmfzbtbtaambub | |
fxqmojtpa | |
''' | |
plain = [ | |
[0, 3, 5, 8], | |
[0, 8, 1, 3], | |
[0, 24, 2, 3], | |
] | |
cipher = Encrypt(plain, key) | |
print cipher | |
plain = Decrypt(cipher, key) | |
print plain |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment