def InvMixColumn(state): inv_special_matrix = [ ["0E", "0B", "0D", "09"], ["09", "0E", "0B", "0D"], ["0D", "09", "0E", "0B"], ["0B", "0D", "09", "0E"], ] state_new = [['xy' for x in range(4)] for y in range(4)] for index in range(4): for row in range(4): tempint = 0 for column in range(4): numbertoxor = Encrypt.hextoint2dig(state[column][index]) ansx = xtime(numbertoxor) ansx2 = xtime(ansx) ansx3 = xtime(ansx2) if inv_special_matrix[row][column] is "0E": tempint = tempint ^ ansx ^ ansx2 ^ ansx3 elif inv_special_matrix[row][column] is "0B": tempint = tempint ^ numbertoxor ^ ansx ^ ansx3 elif inv_special_matrix[row][column] is "0D": tempint = tempint ^ numbertoxor ^ ansx3 ^ ansx2 else: tempint = tempint ^ numbertoxor ^ ansx3 state_new[row][index] = Encrypt.digtohex2dig(tempint) return state_new
def doThings(text, layers): unecryptedCoords = TextToCoords.convertTextIntoCoords(text) numberOfBytes = len(unecryptedCoords[0]) * layers key = Config.generateKey(str(numberOfBytes)) key = key.replace("\n", "") funcKey = TextToKey.getTransformedKeys(key) encrypted = Encrypt.encrypt(copy.deepcopy(unecryptedCoords[0]), copy.deepcopy(unecryptedCoords[1]), funcKey) decryptedData = Encrypt.decrypt(copy.deepcopy(encrypted[0]), copy.deepcopy(encrypted[1]), funcKey) x = [round(list(decryptedData[0])[i]) for i in range(0, len(decryptedData[0]))] y = [round(list(decryptedData[1])[i]) for i in range(0, len(decryptedData[1]))] decrypted = [x, y] decryptedText = TextToCoords.convertCoordsIntoText(decrypted[0], decrypted[1]) dict = { "origX": unecryptedCoords[0], "origY": unecryptedCoords[1], "original": unecryptedCoords, "hexKey": key, "encrypted": encrypted, "encryptedX": encrypted[0], "encryptedY": encrypted[1], "decrypted": decrypted, "decryptedX": decrypted[0], "decryptedY": decrypted[1], "decryptedText": decryptedText } return dict
def decrypt(input, key, Nr): state = list() for i in range(4): temp = list() for j in range(4): temp.append(input[8 * j + 2 * i:8 * j + 2 * (i + 1)]) state.append(temp) state = Encrypt.AddRoundKey(state, key[4 * Nr:4 * (Nr + 1)]) for i in range(Nr - 1): state = InvShiftRow(state) state = InvSubBytes(state) state = Encrypt.AddRoundKey(state, key[4 * (Nr - i - 1):4 * (Nr - i)]) state = InvMixColumn(state) state = InvShiftRow(state) state = InvSubBytes(state) state = Encrypt.AddRoundKey(state, key[0:4]) out = "" for i in range(4): for j in range(4): out += state[j][i] return out
def main(): # Input format if len(sys.argv) != 2: print("[Warning]") print(" Input format: python3 <filename> <Mode>") print(" <Mode>: ECB CBC Cool") return else: Mode = sys.argv[1].upper() pass # Initial open_file = enc.output_filename imgByteArr, Header, Ciphertext = enc.Preprocess(open_file) # Call Mode if Mode == "ECB": Plaintext = ECB_Mode(enc.Key, Ciphertext) elif Mode == "CBC": Plaintext = CBC_Mode(enc.Key, Ciphertext, enc.IV) pass elif Mode == "PCBC": Plaintext = Cool_PCBC_Mode(enc.Key, Ciphertext, enc.IV) pass else: print("[Warning] Undefined Mode") print("Mode: ECB CBC Cool") return # Ciphertext to output image enc.Output_image(Header, Plaintext, "./decrypt_reslut.gif")
def main(): while (True): user_login = get_user_login() account = user_login['account'] pwd = user_login['pwd'] #provinceCode根据学校来改 res = HttpReq.send_req( '/api/f/v6/login', { 'username': account, 'password': Encrypt.get_enc_pwd(pwd), 'provinceCode': 35, 'randomCode': 34 }, 'POST', '') if 'message' in res: msg = res['message'] if msg == 'OK': global uid, token, secret name = res['data']['info']['xm'] #uid = res['data']['info']['uid'] uid = account auth = res['data']['token'] auths = auth.split('.') token = '%s.%s.%s' % (auths[0], auths[1], auths[2]) secret = auths[3] print(u'登录成功,欢迎您:' + name + u'同学!') print('token:' + token) print('secret:' + secret) break else: print(u'登录失败!' + msg) else: print(u'登录失败!' + str(res))
def send_req(interface,data,post_type,token): #sorted_data = {} data = dict(sorted(data.items(),key=lambda d:d[1],reverse=True)) data_str = urllib.urlencode(data) url = main_url + interface up = urlparse.urlparse(url) timestamp = str(int(round(time.time() * 1000))) org_headers = { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Accept-Language": "zh-Hans-CN;q=1", "Connection": "close", "Content-Length":str(len(data_str)), "Content-Type": "application/x-www-form-urlencoded", "Host": up.netloc, "User-Agent": "ChingoItemCGTY(Linux; iOS 12.1;iPhone HUUID/13FDADFB-0EF7-4BDE-9631-65F08BA6BC31)", "app-key": "azk3t4jrcfm5772t", "sign":Encrypt.get_sign(interface,data,timestamp), "timestamp":timestamp } if len(token): org_headers.update({'cgAuthorization':token}) if post_type.upper() == 'POST': res = requests.post(url,data=data_str,headers=org_headers) elif post_type.upper() == 'PUT': res = requests.put(url,data=data_str,headers=org_headers) elif post_type.upper() == 'GET': res = requests.get(url,data=data_str,headers=org_headers) else: print('TypeErr') #if res.status_code != requests.codes.ok: return json_dic(res.text)
def test_FRDB2_2(self): database.Insert("First", "", "", Encrypt.cryptEncode(self.keys[0], "First123"), self.keys[0]) database.Insert("Second", "", "First", Encrypt.cryptEncode(self.keys[1], "Second1"), self.keys[1]) database.Insert("Third", "Type", "Username", Encrypt.cryptEncode(self.keys[2], "Third123"), self.keys[2]) oldQuery = database.GetN("First") database.UpdateU(1, "ChangedFirst") newQuery = database.GetN("First") self.assertEqual(oldQuery.ID, newQuery.ID) self.assertNotEqual(oldQuery.UserName, newQuery.UserName)
def test_FRDB3(self): database.Insert("First", "", "", Encrypt.cryptEncode(self.keys[0], "First123"), self.keys[0]) database.Insert("Second", "", "First", Encrypt.cryptEncode(self.keys[1], "Second1"), self.keys[1]) database.Insert("Third", "Type", "Username", Encrypt.cryptEncode(self.keys[2], "Third123"), self.keys[2]) databaseLengthBefore = len(database.GetAll()) oldQuery = database.GetId(1) database.Delete(1) databaseLengthAfter = len(database.GetAll()) self.assertEqual(oldQuery.AccName, "First") with self.assertRaises(IndexError): database.GetId(1)
def test_FRDB1(self): database.Insert("First", "", "", Encrypt.cryptEncode(self.keys[0], "First123"), self.keys[0]) First = database.GetN("First") self.assertEqual(First.AccName, "First") # if master password has "First" as Name self.assertNotEqual( First.HashVal, "First123") # if master password is directly in database self.assertEqual(First.ID, 1) # if master password has 1 as ID.
def saveKeys(data): # save the keys after encrypting them try: path = getThePath() makeDirRev(path) name = Helper.getDateTimeString('_') with open(os.path.join(path,name+'.txt'),'w') as f: encrypted = Encrypt.encrypt(data) f.write(encrypted+'\n') return (name,path) except Exception: logEvent(f"{Helper.getDateTimeString()}: <Problem in Io.SaveKeys>") return(1,1)
def test_against_pycrypto(self): input = b'123456789aBcDeF_' key = b'!!deadBEEFcabEA3' pycrypto = AES.new(key, AES.MODE_ECB) amateur = Encrypt.AmateurEncrypt(key) expected = [int(b) for b in pycrypto.encrypt(input)] actual = amateur.encryptBlock(input) self.assertEqual(expected, actual, "The test against pycrypto failed") input = b'!@#$%^&*()_+{}|<' expected = [int(b) for b in pycrypto.encrypt(input)] actual = amateur.encryptBlock(input) self.assertEqual(expected, actual, "The test against pycrypto failed")
def Cool_PCBC_Mode(key, ciphertext, IV): cipher = AES.new(key, AES.MODE_ECB) plaintext = bytes() decrypted = IV iv = IV for i in range(0, len(ciphertext), AES.block_size): # take one block size block = ciphertext[i:i + AES.block_size] # padding if len of the last temp not enough if (len(block) != AES.block_size): padding = AES.block_size - len( block) # used number of empty bytes to padding for p in range(padding): block += bytes([padding]) # decrypt decrypted = enc.byte_xor(cipher.decrypt(block), iv) iv = enc.byte_xor(decrypted, block) plaintext += decrypted return plaintext
def test_cbc(self): key = b'dsainvfopinpo389' iv = b'initial vector__' input = [ b'0123456789abcdef', b'0123456789abcdef', b'fedcba9876543210', b'0123456789abcdef' ] pycrypto = AES.new(key, AES.MODE_CBC, iv) amateur = Encrypt.AmateurEncrypt(key) expected = [bytes(pycrypto.encrypt(i)) for i in input] actual = [bytes(a) for a in amateur.cbc(input, iv)] self.assertEqual(expected, actual, "CBC mode encryption failed")
def test_FRDB4(self): database.Insert("First", "Test", "", Encrypt.cryptEncode(self.keys[0], "First123"), self.keys[0]) database.Insert("Second", "Test", "First", Encrypt.cryptEncode(self.keys[1], "Second1"), self.keys[1]) database.Insert("Third", "Test", "Username", Encrypt.cryptEncode(self.keys[2], "Third123"), self.keys[2]) All = database.GetAll() Types = database.GetT("Test") First_id = database.GetId(1) First_Name = database.GetN("First") self.assertEqual(len(All), 3) self.assertEqual(len(Types), 3) self.assertEqual(All[0], First_id) self.assertEqual(All[0], First_Name) self.assertEqual(Types[0], First_id) self.assertEqual(Types[0], First_Name) [self.assertEqual(x.AccType, "Test") for x in Types]
def test_cbc(self): key = b'dsai13874*npo389' iv = b'initial-vector__' input = [ b'0123dsaf89abcdef', b'0123456789abcdef', b'fedcb!!!!6543210', b'0123456789abcdef' ] decrypter = Decrypt.AmateurDecrypt(key) encrypter = Encrypt.AmateurEncrypt(key) cipherText = encrypter.cbc(input, iv) roundTrip = [bytes(rt) for rt in decrypter.cbc(cipherText, iv)] self.assertEqual(input, roundTrip, "CBC-mode decryption failed")
def submitPassword(): input = passwordField.get() if enc.saltAndHash(input) == enc.user_password: isVerified = True print "Correct password entered." authWin.destroy() runWin() else: isVerified = False print "Password entered is incorrect." passwordField.delete(0, 'end') # TD: Implement without creating new Tk() instance FadeOutNotification.present(root, "The password you entered is incorrect. Try again.", 300)
def submitPassword(): input = passwordField.get() if enc.saltAndHash(input) == enc.user_password: isVerified = True print "Correct password entered." authWin.destroy() runWin() else: isVerified = False print "Password entered is incorrect." passwordField.delete(0, 'end') # TD: Implement without creating new Tk() instance FadeOutNotification.present( root, "The password you entered is incorrect. Try again.", 300)
def main(): choice = input( "Pleae select one of the following options:\n1) Encrypt\n2)Decrypt") if str(choice) == '1': inputFile = input( "Type in the full path of the file you wish to encrypt:\n") key = input( "Please type in key. Must be a minimum of 16 characters.")[:16] encrypt = en.Encrypt() encrypt.encrypt(inputFile, key) elif str(choice) == '2': inputFile = input( "Type in the full path of the file you wish to encrypt:\n") key = input("Please type in the key to decrypt the chosen file.\n") decrypt = de.Decrypt() decrypt.decrypt(inputFile, key)
def setUp(self): self.p1 = "password" self.p2 = "" self.p3 = GenPassword.genPassCrypt() #self.p4 = 12345 --> does not pass test but test isn't needed as any entry into GUI is a string anyways self.k1 = Encrypt.generKey() self.k2 = Encrypt.generKey() self.k3 = Encrypt.generKey() #self.k4 = Encrypt.generKey() self.e1 = Encrypt.cryptEncode(self.k1, self.p1) self.e2 = Encrypt.cryptEncode(self.k2, self.p2) self.e3 = Encrypt.cryptEncode(self.k3, self.p3)
def getTestCaseListBySheetName(self, sheetname): if (self.__casecount__ <= 0): self.getCaseCount(sheetname) if (len(self.__argsNameList__) <= 0): self.getArgsName(sheetname) if (self.__argscount__ <= 0): self.getArgsCount(sheetname) list = [] for i in range(0, self.__casecount__): c = TestCase.TestCase(i, self.__argsNameList__, self.getIsEncrypt(sheetname)) #list.append(case) #添加参数名称和参数值 #从第6行(row=5)开始是用例 rowcontenlist = self.__getRowContent__(sheetname, 5 + i) s = '' for j in range(0, self.__argscount__): #第5行(row=4)为参数名称 #第3列(col=2)开始为参数名称 argName = self.__getCellContent__(sheetname=sheetname, row=4, col=2 + j) argVal = self.__getCellContent__(sheetname=sheetname, row=5 + i, col=2 + j) c.rowNo = 5 + i ####直接将参数名称和参数值转为字符串 e.g. name=xxl*passwd=1123 if (len(argVal) > 0): s += argName s += '=' s += argVal s += '&' #### if (self.getIsEncrypt(sheetname) == FrameStrings.sEncrypt): c.setRequestString(Encrypt.Encrypt(s[0:-1])) else: c.setRequestString(s[0:-1]) list.append(c) self.__caselist__ = list return self.__caselist__
def test_roundTrip(self): input = [ 0x32, 0x43, 0xf6, 0xa8, 0x88, 0x5a, 0x30, 0x8d, 0x31, 0x31, 0x98, 0xa2, 0xe0, 0x37, 0x07, 0x34 ] cipherKey = 0x2b7e151628aed2a6abf7158809cf4f3c cipherKeyBytes = bytes([ 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c ]) decrypter = Decrypt.AmateurDecrypt(cipherKeyBytes) encrypter = Encrypt.AmateurEncrypt(cipherKeyBytes) roundTrip = decrypter.decryptBlock(encrypter.encryptBlock(input)) self.assertEqual(input, roundTrip, "Decryption round-trip failed") input.reverse() roundTrip = decrypter.decryptBlock(encrypter.encryptBlock(input)) self.assertEqual(input, roundTrip, "Decryption round-trip failed")
def test_against_standard(self): # Appendix B example input = [ 0x32, 0x43, 0xf6, 0xa8, 0x88, 0x5a, 0x30, 0x8d, 0x31, 0x31, 0x98, 0xa2, 0xe0, 0x37, 0x07, 0x34 ] cipherKey = 0x2b7e151628aed2a6abf7158809cf4f3c cipherKeyBytes = bytes([ 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c ]) expectedOutput = [ 0x39, 0x25, 0x84, 0x1d, 0x2, 0xdc, 0x9, 0xfb, 0xdc, 0x11, 0x85, 0x97, 0x19, 0x6a, 0xb, 0x32 ] encrypter = Encrypt.AmateurEncrypt(cipherKeyBytes) actualOutput = encrypter.encryptBlock(input) self.assertEqual(expectedOutput, actualOutput, "The test against the example in Appendix B failed")
def test_FRDB2_1(self): database.Insert("First", "", "", Encrypt.cryptEncode(self.keys[0], "First123"), self.keys[0]) database.Insert("Second", "", "First", Encrypt.cryptEncode(self.keys[1], "Second1"), self.keys[1]) database.Insert("Third", "Type", "Username", Encrypt.cryptEncode(self.keys[2], "Third123"), self.keys[2]) oldQuery = database.GetN("First") database.UpdateP(1, Encrypt.cryptEncode(self.keys[0], "First321")) newQuery = database.GetN("First") self.assertEqual(oldQuery.ID, newQuery.ID) self.assertNotEqual( Encrypt.cryptDecode(self.keys[0], oldQuery.HashVal.encode('utf-8')), Encrypt.cryptDecode(self.keys[0], newQuery.HashVal.encode('utf-8')))
key = "0100101011110101" stream = convert_sentence_to_16_bit_stream(text_1) #print(stream) #print(len(stream)) Key0, Key1, Key2 = generate_key(key=key) ciphertext = [] print() print('*' * 20 + 'Encryption phase' + '*' * 20) print() for block in stream: encrypt = Encrypt(text=block, Key0=Key0, Key1=Key1, Key2=Key2) ciphertext.append(encrypt.encrypt_text()) print('Ciphertext==') print(''.join(ciphertext)) print() print('*' * 20 + 'Decryption phase' + '*' * 20) print() final_text = [] for block in ciphertext: decrypt = Decrypt(ciphertext=block, Key0=Key0, Key1=Key1, Key2=Key2) final_text.append(decrypt.decrypt_text()) #print(final_text) ans = convert_16_bit_stream_to_sentence(final_text)
def test_cryptDecode3(self): self.assertEqual(Encrypt.cryptDecode(self.k3, self.e3), self.p3)
from flask import Flask, request, redirect, jsonify, render_template, url_for from flask_login import LoginManager, current_user, login_required, login_user, logout_user from Login import * from Encrypt import * # ========= Initialise app ===================================================== app = flask.Flask('__main__') # Generate a key to encrypt cookies for client app.secret_key = os.urandom(16) loginManager = LoginManager() loginManager.setup_app(app) # Create Account object to perform operations on encrypt = Encrypt() # Create log of logged in users loggedUsers = LoggedUsers() # ============================================================================== # Load the current user's details, whoever the user is in this current session @loginManager.user_loader def load_user(user_id): return loggedUsers.get_user(user_id) @app.route('/login', methods=['GET','POST']) def login(): if current_user.is_anonymous: if request.method == 'POST': # Grab post request data
def test_cryptDecode2(self): self.assertEqual(Encrypt.cryptDecode(self.k2, self.e2), self.p2)
def main(): for count in range(256): pt = BitVector(intVal=count, size=8) # print('Processing pt : ', pt) ptdash = pt ^ deltapInp # print("pt ",pt) # print("ptdash ",ptdash) ptfilename = "tempptfile.txt" ptfile = open(ptfilename, 'w', encoding="utf-8") ptfile.write(str(chr(int(str(pt), 2))) + str(chr(int(str(ptdash), 2)))) ptfile.close() ctfilename = "tempctfile.txt" Encrypt.startenc(ptfilename, ctfilename, None) ctfile = open(ctfilename, "r") ct = BitVector(bitstring=ctfile.read(8)) ctfile.close() ctfile = open(ctfilename, "r") ctdash = BitVector(bitstring=ctfile.read(16)[8:]) ctfile.close() ctXorCtdash = ct ^ ctdash # print("pt^ptdash = ", pt^ptdash) # print("ct^ctdash = ", ct^ctdash) lastRndOutpCt = BitVector(bitstring="00000000") lastRndOutpCtdash = BitVector(bitstring="00000000") for k in range(8): lastRndOutpCt[k] = ct[iptable[k]] lastRndOutpCtdash[k] = ctdash[iptable[k]] # print(lastRndOutp) # l2xor = lastRndOutp[0:4] # r2xor = lastRndOutp[4:] # r1xor = l2xor l2ct = lastRndOutpCt[0:4] l2ctdash = lastRndOutpCtdash[0:4] r2ct = lastRndOutpCt[4:] r2ctdash = lastRndOutpCtdash[4:] r1ct = l2ct r1ctdash = l2ctdash #Now do exhaustive search on subkey k2 for k in range(256): k2 = BitVector(intVal=k, size=8) # print("trying key : ",k," : ",k2) l1ct = r2ct ^ fkey(r1ct, k2) l1ctdash = r2ctdash ^ fkey(r1ctdash, k2) l1xor = l1ct ^ l1ctdash r1xor = r1ct ^ r1ctdash # print('l1+r1 xors : ',str(l1xor)+str(r1xor)) if (BitVector(bitstring=str(l1xor) + str(r1xor)) == deltavRnd1): keycount[k] = keycount[k] + 1 print("Match Found..") # print("key : ",k," : ",k2) maxFreq = 0 bestkey = -1 for i in range(256): if (keycount[i] > maxFreq): maxFreq = keycount[i] bestkey = i if (bestkey >= 0): bs = BitVector(intVal=bestkey, size=8) print("Best found key : ", bs) else: print("Best found key : ", bestkey)
import Encrypt Encrypt.decrypt(Encrypt.hash_key('hello'), 'lpp.java') # password then name of file will go above # if a directory use the following # for(dirpath, dirnames, filenames) in os.walk(dir_path): # for file in filenames: # Encrypt.encrypt(hashed_password, dirpath + "/" + file)
def setUp(self): self.keys = [Encrypt.generKey() for i in range(3)] database.CreateTables()
from Encrypt import * from Decrypt import * from Keygenerator import * e=Encrypt() k=Keygenerator() d=Decrypt() string_to_be_encoded = "Hello!! This is my cryptography program." print("Original : ",string_to_be_encoded) key=k.generatekey(string_to_be_encoded) encrypted_string = e.encrypt(string_to_be_encoded,key) print("Encrypted : ",encrypted_string) decrypted_string = d.decrypt(encrypted_string,key) print("Decrypted : ",decrypted_string)
def test_cryptDecode1(self): self.assertEqual(Encrypt.cryptDecode(self.k1, self.e1), self.p1)