diff --git a/01_visual.py b/01_visual.py index 59f6781..da13e5d 100644 --- a/01_visual.py +++ b/01_visual.py @@ -6,10 +6,10 @@ m = np.matrix([ [0,1,1,0] ],dtype=int) -print "Message Text:\t",m +print("Message Text:\t",m) tPriv = privateKeyH84() tPub = publicKeyH84(tPriv.makeGPrime()) ct = tPub.encrypt(m) -print "Cipher Text:\t",ct +print("Cipher Text:\t",ct) mt = tPriv.decrypt(ct) -print "Decoded Text:\t",mt +print("Decoded Text:\t",mt) diff --git a/02_file_encrypt_decrypt.py b/02_file_encrypt_decrypt.py index d69f8a1..51a2469 100644 --- a/02_file_encrypt_decrypt.py +++ b/02_file_encrypt_decrypt.py @@ -4,7 +4,7 @@ tPriv = privateKeyH84() tPub = publicKeyH84(tPriv.makeGPrime()) -print "Encrypting..." +print("Encrypting...") tPub.encryptFile("caesar_letter.txt") -print "Decrypting..." +print("Decrypting...") tPriv.decryptFile("caesar_letter.txt.ctxt") diff --git a/03_private_key_crack.py b/03_private_key_crack.py index c6c7597..ba5d381 100644 --- a/03_private_key_crack.py +++ b/03_private_key_crack.py @@ -5,6 +5,6 @@ tPriv = privateKeyH84() tPriv.printCode() brute = bruteForcerH84(tPriv.makeGPrime()) -print "Attempting to Crack..." +print("Attempting to Crack...") brute.attemptKey() brute.printCode() diff --git a/04_file_encrypt_crack_decrypt.py b/04_file_encrypt_crack_decrypt.py index 40a7e5a..9ee133c 100644 --- a/04_file_encrypt_crack_decrypt.py +++ b/04_file_encrypt_crack_decrypt.py @@ -6,12 +6,12 @@ tPriv = privateKeyH84() tPub = publicKeyH84(tPriv.makeGPrime()) -print "Encrypting..." +print("Encrypting...") tPub.encryptFile("caesar_letter.txt") -print "Attempting to Crack..." +print("Attempting to Crack...") brute = bruteForcerH84(tPub.GPrime) brute.attemptKey() -print "Found key in: " + str(brute.attempts) + " attempts.\n" +print("Found key in: " + str(brute.attempts) + " attempts.\n") crackedPriv = privateKeyH84(brute.sConsider,brute.pConsider) -print "Decrypting with Cracked Key..." +print("Decrypting with Cracked Key...") crackedPriv.decryptFile("caesar_letter.txt.ctxt") diff --git a/05_H16_11_private_key_crack.py b/05_H16_11_private_key_crack.py index bd79e3c..de81778 100644 --- a/05_H16_11_private_key_crack.py +++ b/05_H16_11_private_key_crack.py @@ -6,6 +6,6 @@ tPriv = privateKeyH1611() tPriv.printCode() brute = bruteForcerH1611(tPriv.makeGPrime()) -print "Attempting to Crack..." +print("Attempting to Crack...") brute.attemptKey() brute.printCode() diff --git a/__pycache__/mc_core.cpython-39.pyc b/__pycache__/mc_core.cpython-39.pyc new file mode 100644 index 0000000..880ad1b Binary files /dev/null and b/__pycache__/mc_core.cpython-39.pyc differ diff --git a/caesar_letter.txt b/caesar_letter.txt index 237d181..d3b2ce4 100644 --- a/caesar_letter.txt +++ b/caesar_letter.txt @@ -1,3 +1,3 @@ “Caesar, beware of Brutus. Take heed of Cassius. Come not near Casca. Have an eye to Cinna. Trust not Trebonius. Mark well Metellus Cimber. Decius Brutus loves thee not. Thou hast wronged Caius Ligarius. There is but one mind in all these men, and it is bent against Caesar. If thou beest not immortal, look about you. Security gives way to conspiracy. The mighty gods defend thee!      Thy lover, -     Artemidorus” +     Artemidorus” \ No newline at end of file diff --git a/caesar_letter.txt.ctxt b/caesar_letter.txt.ctxt index 9475904..2a5e306 100644 --- a/caesar_letter.txt.ctxt +++ b/caesar_letter.txt.ctxt @@ -1 +1 @@ -,8/dzkd)ڼTXmܤ4¹,@],d=4ռpyv*|=򳳨kXQXռ, ͹F|] d阮=1X1m  *yڑa@TW|@ܝ@]E1C1m, p ,|E d=ڌp,1 WXd弫 Fy ڵd/1#Α|X1|1%gd,E1J1v,d1ՑdXE,p,XTڅ,]1>v1pX Tz1|@8k X11 )dXͤCyX1|XˌTz1d,4,CX,|=1T C1sI7/ >d^ 7@mˡ=W [Ed˘ 쀳yX =͑y|dzI,=s]1>d4p=,bsLڌXa,/@g@1I11bT v˼ 4E1XTCȝX[ȹpǼXڡC=,@͹൉XI[,@4 *@Fz C@1³]X@1T4=ȝTva 2 >8E>2ǫ* 8ͫ4sڵ1X%ˤ*lj,*古z ͛z@>Տ2*͝)T^ӳ1ܤd˨>Qn \ No newline at end of file +>@ ]QzuߨpWp]J]X E]]Шp*R%ڮ/pvp],Eڰ]kWJ%puQ]%]/OW^v%]E1Q^p]4*Q&EE % OE aQuW Q]4@]Xuz]/WWEvW&J*^* Qͨ^W^]p]]>܊z >%;W|p]X )]QEĺ^ @/W]Q]p>EzQRp%pz굺RpQ]ٺW]J ]kQzuXuvW&%uW*p]CEpEE&]*z QuXEWW*J* p2J%Ek]J zEuQEEEv]E&uՆQgu^*ERW)WJvppW>E@W*]*EX4QQE&/%]Q^]߮Q]g˨WWXW^*%]u*՞1;EIWFuuQIEhWE]˺JpEX4 z/uz]/zQ@]*WWQ%ՉQ&/QQ/2^EERyQEEg% @WRQuREW WgEEX14pC a4a#pga/>Cs pk#ڵ]uy v#@kOvpCg pkg vsO4pa# *%EQyE%u** vgܹ \ No newline at end of file diff --git a/caesar_letter.txt.ctxt.decoded b/caesar_letter.txt.ctxt.decoded index 237d181..d3b2ce4 100644 --- a/caesar_letter.txt.ctxt.decoded +++ b/caesar_letter.txt.ctxt.decoded @@ -1,3 +1,3 @@ “Caesar, beware of Brutus. Take heed of Cassius. Come not near Casca. Have an eye to Cinna. Trust not Trebonius. Mark well Metellus Cimber. Decius Brutus loves thee not. Thou hast wronged Caius Ligarius. There is but one mind in all these men, and it is bent against Caesar. If thou beest not immortal, look about you. Security gives way to conspiracy. The mighty gods defend thee!      Thy lover, -     Artemidorus” +     Artemidorus” \ No newline at end of file diff --git a/mc_core.py b/mc_core.py index 8e4035c..899f7a4 100644 --- a/mc_core.py +++ b/mc_core.py @@ -7,349 +7,364 @@ import csv ###### Helper Functions ####### + + def genSMatrix(k): - """Generates an invertable matrix k * k""" - sMaybe = np.matrix(np.random.randint(0,2,k*k).reshape(k,k).astype(int)) - while True: - try: - sMaybe.getI() - return sMaybe - except: - sMaybe = np.matrix(np.random.randint(0,2,k*k).reshape(k,k).astype(int)) - -def genPMatrix(n,keep=False): - """Generates a permutation matrix n x n using the given sequence""" - p = np.identity(n, dtype=int) - if keep: - return np.matrix(p).reshape(n,n) - else: - return np.matrix(np.random.permutation(p)) + """Generates an invertable matrix k * k""" + sMaybe = np.matrix(np.random.randint(0, 2, k*k).reshape(k, k).astype(int)) + while True: + try: + sMaybe.getI() + return sMaybe + except: + sMaybe = np.matrix(np.random.randint( + 0, 2, k*k).reshape(k, k).astype(int)) + + +def genPMatrix(n, keep=False): + """Generates a permutation matrix n x n using the given sequence""" + p = np.identity(n, dtype=int) + if keep: + return np.matrix(p).reshape(n, n) + else: + return np.matrix(np.random.permutation(p)) + def modTwo(C): - """Q & D way to Mod 2 all results""" - D = C.copy() - D.fill(2) - return np.remainder(C,D) - -def bitFlip(C,n): - """Flips the bit you tell it, -1 for random bit flip, 0 for no flip""" - if n == 0: - return C - if n == -1: - index = random.randint(1,C.size -1) - else: - index = n - - if C[0,index-1] == 1: - C[0,index-1] = 0 - else: - C[0,index-1] = 1 - return C + """Q & D way to Mod 2 all results""" + D = C.copy() + D.fill(2) + return np.remainder(C, D) + + +def bitFlip(C, n): + """Flips the bit you tell it, -1 for random bit flip, 0 for no flip""" + if n == 0: + return C + if n == -1: + index = random.randint(1, C.size - 1) + else: + index = n + + if C[0, index-1] == 1: + C[0, index-1] = 0 + else: + C[0, index-1] = 1 + return C + def all_zeros(d): - """Used when looking up a Syndrome, all zeros mean no error""" - zc = 0 - for x in d: - if x == 0: - zc += 1 - if zc == len(d): - return True - else: - return False - -def syndromeLookup(H,d): - """Looks up where in the syndrome table, if not found must be codeword, in that case returns 0""" - t = H.T.tolist() - s = d.T.tolist()[0] - - #print "s s\t",s - - if all_zeros(s): - #print "s i\t 0" - return 0 - try: - #print "s i\t ",t.index(s) + 1 - return t.index(s) + 1 - except: - #print "s i\t 0" - return 0 - -def checkOldGuesses(oG,newGuess): - """Helper function to see if a guessed matrix has been used before""" - - for s in oG: - if np.array_equal(newGuess.A1,s.A1): - return False - else: - return True + """Used when looking up a Syndrome, all zeros mean no error""" + zc = 0 + for x in d: + if x == 0: + zc += 1 + if zc == len(d): + return True + else: + return False -def makeString(matrix): - """Used in DNA file encoding, will make Numpy Matrix into text strings for easier manipulation""" - message = "" - for m in matrix.A1: - if m == "[": - pass - elif m == "]": - pass - elif m == " ": - pass - else: - message += str(m) - return message - -#### Hamming 8,4 Encryption Data Structures ###### +def syndromeLookup(H, d): + """Looks up where in the syndrome table, if not found must be codeword, in that case returns 0""" + t = H.T.tolist() + s = d.T.tolist()[0] -#### Private Key H84 #### -class privateKeyH84: - """Datastructure to represent our Private Key""" - def __init__(self,S=None,P=None): - """Initalizer that will set S & P matricies to random if not given values""" - #Hamming 8,4 in standard - self.G = np.matrix([ - [1,0,0,0,0,1,1,1], - [0,1,0,0,1,0,1,1], - [0,0,1,0,1,1,0,1], - [0,0,0,1,1,1,1,0] - ], dtype=int) - self.H = np.matrix([ - [0,1,1,1,1,0,0,0], - [1,0,1,1,0,1,0,0], - [1,1,0,1,0,0,1,0], - [1,1,1,0,0,0,0,1] - ], dtype=int) + # print "s s\t",s - #Can create these from known values, otherwise random - if S == None: - self.S = modTwo(genSMatrix(4)) - else: - self.S = S + if all_zeros(s): + # print "s i\t 0" + return 0 + try: + # print "s i\t ",t.index(s) + 1 + return t.index(s) + 1 + except: + # print "s i\t 0" + return 0 - if P == None: - self.P = modTwo(genPMatrix(8)) - else: - self.P = P - def printCode(self): - """Canonical print to screen function""" - print "S: \n" + str(self.S) + "\n" - print "P: \n" + str(self.P) + "\n" - print "GPrime: \n" + str(self.makeGPrime()) + "\n" - - def writeKeyToFile(self, keyFile): - """Saves key to a pickle file""" - try: - pickle.dump(self, open(keyFile,"wb")) - except: - print "Could not save key file to: ",keyFile - exit(1) - - def readKeyFromFile(self,keyFile): - """Reads key from a pickle file""" - try: - newPriv = pickle.load( open(keyFile,"rb")) - self.S = newPriv.S - self.P = newPriv.P - except: - print "Could not load key file from: ",keyFile - exit(1) - - def makeGPrime(self): - """Creates the GPrime encrytion Matrix""" - return modTwo(self.S*self.G*self.P) - - def decrypt(self,c): - """When given cipher text will decode to message""" - cHat = c * modTwo(self.P.I.astype(int)) - m = bitFlip(cHat,syndromeLookup(self.H,modTwo(self.H*cHat.T))) - return modTwo(m[0,0:4] * modTwo(self.S.I.astype(int))) - - def decryptFile(self,f): - """Will decrypt whole file""" - cf = open(f,"rb") - cb1 = cf.read(1) - cb2 = cf.read(1) - - mf = open(f+".decoded","wb") - - while cb1 and cb2: - - #First Byte of Cipher Text - c_1 = '{0:08b}'.format(ord(cb1))[0:8] - c1_l = [] - m1 = "" - for s in c_1: - c1_l.append(s) - c_1_m = np.matrix(c1_l,dtype=int) - - d1 = self.decrypt(c_1_m) - - for d in range(0,d1.size): - m1 += str(d1.item(d)) - - #Second Byte of Cipher Text - c_2 = '{0:08b}'.format(ord(cb2))[0:8] - c2_l = [] - m2 = "" - for s in c_2: - c2_l.append(s) - c_2_m = np.matrix(c2_l,dtype=int) - - d2 = self.decrypt(c_2_m) - - for d in range(0,d2.size): - m2 += str(d2.item(d)) +def checkOldGuesses(oG, newGuess): + """Helper function to see if a guessed matrix has been used before""" - #print m1+m2 - mf.write(chr(int(m1+m2,2))) - cb1 = cf.read(1) - cb2 = cf.read(1) + for s in oG: + if np.array_equal(newGuess.A1, s.A1): + return False + else: + return True - mf.close() - cf.close() - - def dnaFileDecrypt(self,f,dlu): - """Decrypts a file that has been turned into a DNA representation""" - cf = open(f,"r") - c1 = cf.readline().strip("\n") - c2 = cf.readline().strip("\n") - - mf = open(f+".decoded","w") - - while c1 and c2: - m1 = "" - m2 = "" - mat1 = np.matrix(" ".join(dlu.lookDNADecrypt(c1)),dtype=int) - mat2 = np.matrix(" ".join(dlu.lookDNADecrypt(c2)),dtype=int) - d1 = self.decrypt(mat1) - d2 = self.decrypt(mat2) - for d in range(0,d1.size): - m1 += str(d1.item(d)) - - for d in range(0,d2.size): - m2 += str(d2.item(d)) - - mf.write(chr(int(m1+m2,2))) - c1 = cf.readline().strip("\n") - c2 = cf.readline().strip("\n") - - mf.close() - cf.close() + +def makeString(matrix): + """Used in DNA file encoding, will make Numpy Matrix into text strings for easier manipulation""" + message = "" + for m in matrix.A1: + if m == "[": + pass + elif m == "]": + pass + elif m == " ": + pass + else: + message += str(m) + return message + + +#### Hamming 8,4 Encryption Data Structures ###### + +#### Private Key H84 #### +class privateKeyH84: + """Datastructure to represent our Private Key""" + + def __init__(self, S=None, P=None): + """Initalizer that will set S & P matricies to random if not given values""" + # Hamming 8,4 in standard + self.G = np.matrix([ + [1, 0, 0, 0, 0, 1, 1, 1], + [0, 1, 0, 0, 1, 0, 1, 1], + [0, 0, 1, 0, 1, 1, 0, 1], + [0, 0, 0, 1, 1, 1, 1, 0] + ], dtype=int) + self.H = np.matrix([ + [0, 1, 1, 1, 1, 0, 0, 0], + [1, 0, 1, 1, 0, 1, 0, 0], + [1, 1, 0, 1, 0, 0, 1, 0], + [1, 1, 1, 0, 0, 0, 0, 1] + ], dtype=int) + + # Can create these from known values, otherwise random + if S == None: + self.S = modTwo(genSMatrix(4)) + else: + self.S = S + + if P == None: + self.P = modTwo(genPMatrix(8)) + else: + self.P = P + + def printCode(self): + """Canonical print to screen function""" + print("S: \n" + str(self.S) + "\n") + print("P: \n" + str(self.P) + "\n") + print("GPrime: \n" + str(self.makeGPrime()) + "\n") + + def writeKeyToFile(self, keyFile): + """Saves key to a pickle file""" + try: + pickle.dump(self, open(keyFile, "wb")) + except: + print("Could not save key file to: ", keyFile) + exit(1) + + def readKeyFromFile(self, keyFile): + """Reads key from a pickle file""" + try: + newPriv = pickle.load(open(keyFile, "rb")) + self.S = newPriv.S + self.P = newPriv.P + except: + print("Could not load key file from: ", keyFile) + exit(1) + + def makeGPrime(self): + """Creates the GPrime encrytion Matrix""" + return modTwo(self.S*self.G*self.P) + + def decrypt(self, c): + """When given cipher text will decode to message""" + cHat = c * modTwo(self.P.I.astype(int)) + m = bitFlip(cHat, syndromeLookup(self.H, modTwo(self.H*cHat.T))) + return modTwo(m[0, 0:4] * modTwo(self.S.I.astype(int))) + + def decryptFile(self, f): + """Will decrypt whole file""" + cf = open(f, "rb") + cb1 = cf.read(1) + cb2 = cf.read(1) + print(cb1) + print(cb2) + mf = open(f+".decoded", "wb") + + while cb1 and cb2: + # First Byte of Cipher Text + c_1 = '{0:08b}'.format(ord(cb1))[0:8] + c1_l = [] + m1 = "" + for s in c_1: + c1_l.append(s) + c_1_m = np.matrix(c1_l, dtype=int) + + d1 = self.decrypt(c_1_m) + #print(d1) + for d in range(0, d1.size): + m1 += str(d1.item(d)) + # Second Byte of Cipher Text + c_2 = '{0:08b}'.format(ord(cb2))[0:8] + c2_l = [] + m2 = "" + for s in c_2: + c2_l.append(s) + c_2_m = np.matrix(c2_l, dtype=int) + + d2 = self.decrypt(c_2_m) + + for d in range(0, d2.size): + m2 += str(d2.item(d)) + #print(m1+m2) + #print(chr(int(m1+m2,2))) + mf.write(bytes([ord(chr(int(m1+m2, 2)))])) + cb1 = cf.read(1) + cb2 = cf.read(1) + + mf.close() + cf.close() + + def dnaFileDecrypt(self, f, dlu): + """Decrypts a file that has been turned into a DNA representation""" + cf = open(f, "r") + c1 = cf.readline().strip("\n") + c2 = cf.readline().strip("\n") + + mf = open(f+".decoded", "w") + + while c1 and c2: + m1 = "" + m2 = "" + mat1 = np.matrix(" ".join(dlu.lookDNADecrypt(c1)), dtype=int) + mat2 = np.matrix(" ".join(dlu.lookDNADecrypt(c2)), dtype=int) + d1 = self.decrypt(mat1) + d2 = self.decrypt(mat2) + for d in range(0, d1.size): + m1 += str(d1.item(d)) + + for d in range(0, d2.size): + m2 += str(d2.item(d)) + + mf.write(bytes(chr(int(m1+m2, 2)), 'utf-8')) + c1 = cf.readline().strip("\n") + c2 = cf.readline().strip("\n") + + mf.close() + cf.close() #### Public Key H84 #### -class publicKeyH84: - """Public Key Data Structure""" - def __init__(self,GPrime): - self.GPrime = GPrime - def printCode(self): - """Canonical print to screen""" - print "GPrime: \n" + str(self.GPrime) + "\n" - - def writeKeyToFile(self, keyFile): - """Saves key to a pickle file""" - try: - pickle.dump(self, open(keyFile,"wb")) - except: - print "Could not save key file to: ",keyFile - exit(1) - - def readKeyFromFile(self,keyFile): - """Reads key from a pickle file""" - try: - newPub = pickle.load( open(keyFile,"rb")) - self.GPrime = newPub.GPrime - except: - print "Could not load key file from: ",keyFile - exit(1) - - def encrypt(self,m): - """When given a message will encode""" - #Error vector will be random - z = random.randint(1,7) - c = bitFlip(modTwo(m*self.GPrime),z) - return c - - def encryptFile(self,f): - """Encrypts a whole file""" - - mf = open(f,"rb") - m = mf.read(1) - - cf = open(f+".ctxt","wb") - - while m: - #First half byte of message text - m_1 = '{0:08b}'.format(ord(m))[0:4] - m1_l = [] - c1 = "" - for s in m_1: - m1_l.append(s) - m_1_m = np.matrix(m1_l,dtype=int) - - d1 = self.encrypt(m_1_m) - for d in range(0,d1.size): - c1 += str(d1.item(d)) - cf.write(chr(int(c1,2))) - - #Second half byte of message text - m_2 = '{0:08b}'.format(ord(m))[4:] - m2_l = [] - c2 = "" - for s in m_2: - m2_l.append(s) - m_2_m = np.matrix(m2_l,dtype=int) - - d2 = self.encrypt(m_2_m) - for d in range(0,d2.size): - c2 += str(d2.item(d)) - cf.write(chr(int(c2,2))) - - m = mf.read(1) - - cf.close() - mf.close() - - def dnaFileEncrypt(self,f,dlu): - """Takes a files, encypts it and represents it as a DNA codeword""" - cipherString = "" - - mf = open(f,"rb") - m = mf.read(1) - - cf = open(f+".dna.ctxt","wb") - - while m: - - #First half byte of message text - m_1 = '{0:08b}'.format(ord(m))[0:4] - m1_l = [] - c1 = "" - for s in m_1: - m1_l.append(s) - m_1_m = np.matrix(m1_l,dtype=int) - - d1 = self.encrypt(m_1_m) - - #Second half byte of message text - m_2 = '{0:08b}'.format(ord(m))[4:] - m2_l = [] - c2 = "" - for s in m_2: - m2_l.append(s) - m_2_m = np.matrix(m2_l,dtype=int) - d2 = self.encrypt(m_2_m) - - message = makeString(m_1_m) + makeString(m_2_m) - cipherMessage = makeString(d1) + makeString(d2) - cf.write(dlu.lookDNAEncrypt(cipherMessage[0:8])+"\n") - cf.write(dlu.lookDNAEncrypt(cipherMessage[8:])+"\n") - m = mf.read(1) - - cf.close() - mf.close() + +class publicKeyH84: + """Public Key Data Structure""" + + def __init__(self, GPrime): + self.GPrime = GPrime + + def printCode(self): + """Canonical print to screen""" + print("GPrime: \n" + str(self.GPrime) + "\n") + + def writeKeyToFile(self, keyFile): + """Saves key to a pickle file""" + try: + pickle.dump(self, open(keyFile, "wb")) + except: + print("Could not save key file to: ", keyFile) + exit(1) + + def readKeyFromFile(self, keyFile): + """Reads key from a pickle file""" + try: + newPub = pickle.load(open(keyFile, "rb")) + self.GPrime = newPub.GPrime + except: + print("Could not load key file from: ", keyFile) + exit(1) + + def encrypt(self, m): + """When given a message will encode""" + # Error vector will be random + z = random.randint(1, 7) + c = bitFlip(modTwo(m*self.GPrime), z) + return c + + def encryptFile(self, f): + """Encrypts a whole file""" + + mf = open(f, "rb") + m = mf.read(1) + + cf = open(f+".ctxt", "wb") + + while m: + # First half byte of message text + m_1 = '{0:08b}'.format(ord(m))[0:4] + m1_l = [] + c1 = "" + for s in m_1: + m1_l.append(s) + m_1_m = np.matrix(m1_l, dtype=int) + + d1 = self.encrypt(m_1_m) + for d in range(0, d1.size): + c1 += str(d1.item(d)) + cf.write(bytes([ord(chr(int(c1, 2)))])) + + # Second half byte of message text + m_2 = '{0:08b}'.format(ord(m))[4:] + m2_l = [] + c2 = "" + for s in m_2: + m2_l.append(s) + m_2_m = np.matrix(m2_l, dtype=int) + + d2 = self.encrypt(m_2_m) + for d in range(0, d2.size): + c2 += str(d2.item(d)) + cf.write(bytes([ord(chr(int(c2, 2)))])) + + + m = mf.read(1) + + cf.close() + mf.close() + + def dnaFileEncrypt(self, f, dlu): + """Takes a files, encypts it and represents it as a DNA codeword""" + cipherString = "" + + mf = open(f, "rb") + m = mf.read(1) + + cf = open(f+".dna.ctxt", "wb") + + while m: + + # First half byte of message text + m_1 = '{0:08b}'.format(ord(m))[0:4] + m1_l = [] + c1 = "" + for s in m_1: + m1_l.append(s) + m_1_m = np.matrix(m1_l, dtype=int) + + d1 = self.encrypt(m_1_m) + + # Second half byte of message text + m_2 = '{0:08b}'.format(ord(m))[4:] + m2_l = [] + c2 = "" + for s in m_2: + m2_l.append(s) + m_2_m = np.matrix(m2_l, dtype=int) + d2 = self.encrypt(m_2_m) + + message = makeString(m_1_m) + makeString(m_2_m) + cipherMessage = makeString(d1) + makeString(d2) + cf.write(dlu.lookDNAEncrypt(cipherMessage[0:8])+"\n") + cf.write(dlu.lookDNAEncrypt(cipherMessage[8:])+"\n") + m = mf.read(1) + + cf.close() + mf.close() #### Brute Forcer #### + class bruteForcerH84(): """Data structure that attempts to create Private Key from Given Public Key""" def __init__(self,GPrime): @@ -374,10 +389,10 @@ def __init__(self,GPrime): def printCode(self): """Canonical Print self function""" - print "Calculated GPrime:\n" + str(self.GPrimeConsider) + "\n" - print "sM:\n" + str(self.sConsider) + "\n" - print "pM:\n" + str(self.pConsider) + "\n" - print "Attempts: " + str(self.attempts) + "\n" + print("Calculated GPrime:\n" + str(self.GPrimeConsider) + "\n") + print("sM:\n" + str(self.sConsider) + "\n") + print("pM:\n" + str(self.pConsider) + "\n") + print("Attempts: " + str(self.attempts) + "\n") def attemptKey(self): """Attempts to reconstitute S,P given GPrime (G is already known)""" @@ -410,67 +425,72 @@ def attemptKey(self): self.GPrimeConsider = modTwo(self.sConsider*self.G*self.pConsider) return True - + #### Hamming 16,11 Version ###### #### Created to test security of Key Cracking #### #### Private Key H1611 #### -class privateKeyH1611: - """Datastructure to represent our Private Key""" - def __init__(self,S=None,P=None): - """Initalizer that will set S,P, random if not given values""" - #Hamming 16,11 in standard - self.G = np.matrix([ - [1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1], - [0,1,0,0,0,0,0,0,0,0,0,0,1,0,1,1], - [0,0,1,0,0,0,0,0,0,0,0,0,1,1,0,1], - [0,0,0,1,0,0,0,0,0,0,1,0,0,0,1,1], - [0,0,0,0,1,0,0,0,0,0,1,0,0,1,0,1], - [0,0,0,0,0,1,0,0,0,0,1,0,1,0,0,1], - [0,0,0,0,0,0,1,0,0,0,1,0,1,1,1,1], - [0,0,0,0,0,0,0,1,0,0,1,0,1,1,0,0], - [0,0,0,0,0,0,0,0,1,0,1,0,1,0,1,0], - [0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0], - [0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0] - ], dtype=int) - self.H = np.matrix([ - [1,0,0,0,0,1,1,0,0,1,1,1,1,0,0,1], - [0,1,0,0,1,0,1,0,1,0,1,1,0,1,0,1], - [0,0,1,0,1,1,0,0,1,1,0,1,0,0,1,1], - [0,0,0,1,1,1,1,0,0,0,0,1,1,1,1,0], - [0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0] - ], dtype=int) - - #Can create these from known values, otherwise random - if S == None: - self.S = modTwo(genSMatrix(11)) - else: - self.S = S - - if P == None: - self.P = modTwo(genPMatrix(16)) - else: - self.P = P - def printCode(self): - """Canonical print to screen function""" - print "S: \n" + str(self.S) + "\n" - print "P: \n" + str(self.P) + "\n" - print "GPrime: \n" + str(self.makeGPrime()) + "\n" - def makeGPrime(self): - """Returns a version of GPrime usable for calculations""" - return modTwo(self.S*self.G*self.P) +class privateKeyH1611: + """Datastructure to represent our Private Key""" + + def __init__(self, S=None, P=None): + """Initalizer that will set S,P, random if not given values""" + # Hamming 16,11 in standard + self.G = np.matrix([ + [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1], + [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1], + [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1], + [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1], + [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1], + [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1], + [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1], + [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0] + ], dtype=int) + self.H = np.matrix([ + [1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1], + [0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1], + [0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1], + [0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0] + ], dtype=int) + + # Can create these from known values, otherwise random + if S == None: + self.S = modTwo(genSMatrix(11)) + else: + self.S = S + + if P == None: + self.P = modTwo(genPMatrix(16)) + else: + self.P = P + + def printCode(self): + """Canonical print to screen function""" + print("S: \n" + str(self.S) + "\n") + print("P: \n" + str(self.P) + "\n") + print("GPrime: \n" + str(self.makeGPrime()) + "\n") + + def makeGPrime(self): + """Returns a version of GPrime usable for calculations""" + return modTwo(self.S*self.G*self.P) #### Public Key H1611 #### class publicKeyH1611: - """Public Key Data Structure, much simplified then H8,4""" - def __init__(self,GPrime): - self.GPrime = GPrime - def printCode(self): - """Canonical print to screen""" - print "GPrime: \n" + str(self.GPrime) + "\n" + """Public Key Data Structure, much simplified then H8,4""" + + def __init__(self, GPrime): + self.GPrime = GPrime + + def printCode(self): + """Canonical print to screen""" + print("GPrime: \n" + str(self.GPrime) + "\n") ##### Brute Forcer Based on H16,11 #### class bruteForcerH1611(): @@ -504,10 +524,10 @@ def __init__(self,GPrime): def printCode(self): """Canonical Print self function""" - print "Calculated GPrime:\n" + str(self.GPrimeConsider) + "\n" - print "sM:\n" + str(self.sConsider) + "\n" - print "pM:\n" + str(self.pConsider) + "\n" - print "Attempts: " + str(self.attempts) + "\n" + print("Calculated GPrime:\n" + str(self.GPrimeConsider) + "\n") + print("sM:\n" + str(self.sConsider) + "\n") + print("pM:\n" + str(self.pConsider) + "\n") + print("Attempts: " + str(self.attempts) + "\n") def attemptKey(self): """Attempts to reconstitute S,P given GPrime (G is already known)""" @@ -539,37 +559,39 @@ def attemptKey(self): return True ##### DNA Lookup Datastructure ### + + class lookupDNA(): - """Data structure that keeps a table of DNA mappings""" - def __init__(self,encryptFile,decryptFile): - self.encLU = dict() - self.decLU = dict() - - dreader = csv.reader(open(decryptFile,'r')) - for row in dreader: - k,v = row - self.decLU[k] = str(v) - - ereader = csv.reader(open(encryptFile,'r')) - for row in ereader: - k,v = row - self.encLU[k] = str(v) - - def lookDNAEncrypt(self, bstring): - """Finds DNA sequence from 8 bits""" - try: - return str(self.encLU[bstring]) - except: - return "?" - def lookDNADecrypt(self,bstring): - """Finds 8 bits from 8 characters of DNA""" - try: - return str(self.decLU[bstring]) - except: - return "?" - -if __name__ == "__main__": - pass + """Data structure that keeps a table of DNA mappings""" + def __init__(self, encryptFile, decryptFile): + self.encLU = dict() + self.decLU = dict() + dreader = csv.reader(open(decryptFile, 'r')) + for row in dreader: + k, v = row + self.decLU[k] = str(v) + ereader = csv.reader(open(encryptFile, 'r')) + for row in ereader: + k, v = row + self.encLU[k] = str(v) + + def lookDNAEncrypt(self, bstring): + """Finds DNA sequence from 8 bits""" + try: + return str(self.encLU[bstring]) + except: + return "?" + + def lookDNADecrypt(self, bstring): + """Finds 8 bits from 8 characters of DNA""" + try: + return str(self.decLU[bstring]) + except: + return "?" + + +if __name__ == "__main__": + pass