def encrypt_oracle(data): """ 随机选择 CBC 模式或者 ECB 模式进行加密, 返回加密所使用的模式以及加密后的结果 :param data: 待加密明文, "plaintext" :return: 模式以及加密结果, ("CBC", b"cipher_text") """ size = 16 key = generate_random_bytes(size) encrypt_mode = random.choice([AES.MODE_CBC, AES.MODE_ECB]) # 随机选择一种加密模式 mode_dict = {AES.MODE_CBC: "CBC", AES.MODE_ECB: "ECB"} data = codecs.encode(data, "ascii") # 将 str 转成 bytes # 对数据进行随机化处理 data = generate_random_bytes(random.randint(5, 10)) + data + generate_random_bytes(random.randint(5, 10)) data = pad(data, size) # 填充操作 if encrypt_mode == AES.MODE_CBC: iv = generate_random_bytes(size) encrypt_tool = AES.new(key, AES.MODE_CBC, IV=iv) elif encrypt_mode == AES.MODE_ECB: encrypt_tool = AES.new(key, AES.MODE_ECB) else: raise RuntimeError("Encrypt_mode is wrong!") after_encrypt_data = encrypt_tool.encrypt(data) return mode_dict[encrypt_mode], after_encrypt_data
def test3(self): for keylen, taglen, result in self.tv3: key = bchr(0) * (keylen // 8 - 1) + bchr(taglen) C = b("") for i in range(128): S = bchr(0) * i N = long_to_bytes(3 * i + 1, 12) cipher = AES.new(key, AES.MODE_OCB, nonce=N, mac_len=taglen // 8) cipher.update(S) C += cipher.encrypt(S) + cipher.encrypt() + cipher.digest() N = long_to_bytes(3 * i + 2, 12) cipher = AES.new(key, AES.MODE_OCB, nonce=N, mac_len=taglen // 8) C += cipher.encrypt(S) + cipher.encrypt() + cipher.digest() N = long_to_bytes(3 * i + 3, 12) cipher = AES.new(key, AES.MODE_OCB, nonce=N, mac_len=taglen // 8) cipher.update(S) C += cipher.encrypt() + cipher.digest() N = long_to_bytes(385, 12) cipher = AES.new(key, AES.MODE_OCB, nonce=N, mac_len=taglen // 8) cipher.update(C) result2 = cipher.encrypt() + cipher.digest() self.assertEqual(unhexlify(b(result)), result2)
def WriteZipFile(filename): """ 保存所有kvdb数据,压缩成zip然后aes cbc加密 """ FileBuffer = io.BytesIO() datalist = FindKVDBKeys() if datalist: zfile = zipfile.ZipFile(FileBuffer,mode='w') for data in datalist: # bytedata = (data + "tttttttt").encode(encoding="utf-8") bytedata = kv.get(str(data)) if bytedata: # print(bytedata) zfile.writestr(str(data),bytedata) zfile.close() key = config.keyDataBackUp iv = Random.new().read(AES.block_size) cipher = AES.new(key, AES.MODE_ECB) CryptIV = cipher.encrypt(iv) cipher = AES.new(key, AES.MODE_CBC, iv) bytebuffer = FileBuffer.getvalue() lendata = 16 - len(bytebuffer)%16 bytebuffer = bytebuffer + chr(lendata)*lendata #print(bytebuffer) CryptData = CryptIV + cipher.encrypt(bytebuffer) bucket = Bucket('backup') # print(FileBuffer.getvalue()) bucket.put_object(filename,CryptData) FileBuffer.close()
def ReadZipFile(filename): """ 从storage中读取数据,还原到kvdb中 参数 filename 要还原数据的文件名 """ bucket = Bucket('backup') # print(filename) CryptData = bucket.get_object_contents(filename) # print(CryptData) # -FileBuffer.close() key = config.keyDataBackUp cipher = AES.new(key, AES.MODE_ECB) iv = cipher.decrypt(CryptData[:16]) # print(str(iv)) cipher = AES.new(key, AES.MODE_CBC, iv) bytebuffer = cipher.decrypt(CryptData[16:]) lendata = ord(bytebuffer[-1]) FileBuffer = io.BytesIO(bytebuffer[:-lendata]) zfile = zipfile.ZipFile(FileBuffer,mode='r') namelist = zfile.namelist() for name in namelist: bytedata = zfile.read(name) kv.set(name,bytedata.decode("utf-8")) return u"数据已还原"
def chunk_read(response, outfname, intitlekey, first_iv, chunk_size=0x200000, report_hook=None): fh = open(outfname,'wb') total_size = int(response.getheader('Content-Length')) total_size = int(total_size) bytes_so_far = 0 data = [] first_chunk_read = 0 while 1: if report_hook: report_hook(bytes_so_far, chunk_size, total_size) chunk = response.read(chunk_size) bytes_so_far += len(chunk) if not chunk: break # IV of first chunk should be the Content ID + 28 0s like with the entire file, but each subsequent chunk should be the last 16 bytes of the previous still ciphered chunk if first_chunk_read == 0: decryptor = AES.new(intitlekey, AES.MODE_CBC, unhexlify(first_iv)) first_chunk_read = 1 else: decryptor = AES.new(intitlekey, AES.MODE_CBC, prev_chunk[(0x200000 - 16):0x200000]) dec_chunk = decryptor.decrypt(chunk) prev_chunk = chunk fh.write(dec_chunk) fh.close()
def export_data(self, entrystore, password): "Exports data from an entrystore" # check and pad password if password is None: raise base.PasswordError password = util.pad_right(password[:32], 32, "\0") # generate XML data = RevelationXML.export_data(self, entrystore) # compress data, and right-pad with the repeated ascii # value of the pad length data = zlib.compress(data) padlen = 16 - (len(data) % 16) if padlen == 0: padlen = 16 data += chr(padlen) * padlen # generate an initial vector for the CBC encryption iv = util.random_string(16) # encrypt data AES.block_size = 16 AES.key_size = 32 data = AES.new(password, AES.MODE_CBC, iv).encrypt(data) # encrypt the iv, and prepend it to the data with a header data = self.__generate_header() + AES.new(password).encrypt(iv) + data return data
def test_unknown_parameters(self): self.assertRaises(TypeError, AES.new, self.key_128, AES.MODE_CTR, 7, counter=self.ctr_128) self.assertRaises(TypeError, AES.new, self.key_128, AES.MODE_CTR, counter=self.ctr_128, unknown=7) # But some are only known by the base cipher (e.g. use_aesni consumed by the AES module) AES.new(self.key_128, AES.MODE_CTR, counter=self.ctr_128, use_aesni=False)
def test_bytearray(self): data = b"1" * 16 iv = b"\x00" * 6 + b"\xFF\xFF" # Encrypt cipher1 = AES.new(self.key_128, AES.MODE_CTR, nonce=self.nonce_64, initial_value=iv) ref1 = cipher1.encrypt(data) cipher2 = AES.new(self.key_128, AES.MODE_CTR, nonce=bytearray(self.nonce_64), initial_value=bytearray(iv)) ref2 = cipher2.encrypt(bytearray(data)) self.assertEqual(ref1, ref2) self.assertEqual(cipher1.nonce, cipher2.nonce) # Decrypt cipher3 = AES.new(self.key_128, AES.MODE_CTR, nonce=self.nonce_64, initial_value=iv) ref3 = cipher3.decrypt(data) cipher4 = AES.new(self.key_128, AES.MODE_CTR, nonce=bytearray(self.nonce_64), initial_value=bytearray(iv)) ref4 = cipher4.decrypt(bytearray(data)) self.assertEqual(ref3, ref4)
def test_valid_init_verify(self): # Verify path INIT->VERIFY cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96) mac = cipher.digest() cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96) cipher.verify(mac)
def test_invalid_multiple_decrypt_and_verify(self): cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96) ct, tag = cipher.encrypt_and_digest(self.data_128) cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96) cipher.decrypt_and_verify(ct, tag) self.assertRaises(TypeError, cipher.decrypt_and_verify, ct, tag)
def test_data_must_be_bytes(self): cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96) self.assertRaises(TypeError, cipher.encrypt, 'test1234567890-*') cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96) self.assertRaises(TypeError, cipher.decrypt_and_verify, 'test1234567890-*', b("xxxx"))
def test_hex_mac(self): cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96) mac_hex = cipher.hexdigest() self.assertEqual(cipher.digest(), unhexlify(mac_hex)) cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96) cipher.hexverify(mac_hex)
def decryptFile(self, content): from Crypto.Cipher import AES Key = binascii.unhexlify('8C35192D964DC3182C6F84F3252239EB4A320D2500000000') IV = binascii.unhexlify('FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF') IV_Cipher = AES.new(Key, AES.MODE_ECB) IV = IV_Cipher.encrypt(IV) obj = AES.new(Key, AES.MODE_CFB, IV) data = content if re.search(r"<title>404 - Not Found</title>", data) is None: data = binascii.unhexlify(''.join(data.split())) data = data.split("\xda") links = [] for link in data: if link == '': continue link = base64.b64decode(link + "\xda") link = obj.decrypt(link) decryptedUrl = link.replace('CCF: ', '') links.append(decryptedUrl) self.log.debug("%s: adding rsdf-package with %d links" % (self.__name__, len(links))) return links
def decrypt_body(self, password, data): import time key = sha256(password).digest() hdr = self.header then = time.time() # sha256 the password, encrypt it upon itself 50000 times, sha256 it again, and sha256 it again concatenated with a random number :| cipher = AES.new(hdr['seed_key'], AES.MODE_ECB) for x in range(hdr['seed_rot_n']): key = cipher.encrypt(key) key = sha256(key).digest() key = sha256(hdr['seed_rand'] + key).digest() cipher = AES.new(key, AES.MODE_CBC, hdr['enc_iv']) body = cipher.decrypt(data) # remove some padding padding = unpack("b", body[-1])[0] body = body[:-padding] now = time.time() print 'spent %.3fms on decryption' % ((now - then) * 1000) if sha256(body).digest() != hdr['checksum']: raise KdbReaderDecodeFailError() return body
def test_aes_192(self): plaintext = '6bc1bee22e409f96e93d7e117393172a' +\ 'ae2d8a571e03ac9c9eb76fac45af8e51' +\ '30c81c46a35ce411e5fbc1191a0a52ef' +\ 'f69f2445df4f9b17ad2b417be66c3710' ciphertext = 'cdc80d6fddf18cab34c25909c99a4174' +\ 'fcc28b8d4c63837c09e81700c1100401' +\ '8d9a9aeac0f6596f559c6d4daf59a5f2' +\ '6d9f200857ca6c3e9cac524bd9acc92a' key = '8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b' iv = '000102030405060708090a0b0c0d0e0f' key = unhexlify(key) iv = unhexlify(iv) plaintext = unhexlify(plaintext) ciphertext = unhexlify(ciphertext) cipher = AES.new(key, AES.MODE_OFB, iv) self.assertEqual(cipher.encrypt(plaintext), ciphertext) cipher = AES.new(key, AES.MODE_OFB, iv) self.assertEqual(cipher.decrypt(ciphertext), plaintext) cipher = AES.new(key, AES.MODE_OFB, iv) self.assertEqual(cipher.encrypt(plaintext[:-8]), ciphertext[:-8]) cipher = AES.new(key, AES.MODE_OFB, iv) self.assertEqual(cipher.decrypt(ciphertext[:-8]), plaintext[:-8])
def decrypt_username(encrypted_record,key,mode): """ This functions is used to decrypt usernames. """ # WE DECRYPT THE PASSWORD ACCORDING TO THE MODE IT WAS SAVED # WE RETURN USERNAME:PASSWORD # decrypted_pass[5:] IS USED TO RETURN THE PASSWORD ONLY (WITHOUT SALT) if mode == "1": mode = AES.MODE_ECB pair = encrypted_record.split(":") aes = AES.new(key, mode) decrypted_username = aes.decrypt(base64.b64decode(pair[0])) return decrypted_username elif mode =="2": mode = AES.MODE_CBC pair = encrypted_record.split(":") aes = AES.new(key, mode,base64.b64decode(pair[2])) decrypted_username = aes.decrypt(base64.b64decode(pair[0])) return decrypted_username elif mode =="3": mode = AES.MODE_CTR pair = encrypted_record.split(":") IV = base64.b64decode(pair[2]) ctr = Crypto.Util.Counter.new(128, initial_value=long(IV.encode("hex"), 16)) aes = Crypto.Cipher.AES.new(key, mode, counter=ctr) decrypted_username = aes.decrypt(base64.b64decode(pair[0])) return decrypted_username else: print ""
def test_aes_256(self): plaintext = '6bc1bee22e409f96e93d7e117393172a' +\ 'ae2d8a571e03ac9c9eb76fac45af8e51' +\ '30c81c46a35ce411e5fbc1191a0a52ef' +\ 'f69f2445df4f9b17ad2b417be66c3710' ciphertext = 'dc7e84bfda79164b7ecd8486985d3860' +\ '4febdc6740d20b3ac88f6ad82a4fb08d' +\ '71ab47a086e86eedf39d1c5bba97c408' +\ '0126141d67f37be8538f5a8be740e484' key = '603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4' iv = '000102030405060708090a0b0c0d0e0f' key = unhexlify(key) iv = unhexlify(iv) plaintext = unhexlify(plaintext) ciphertext = unhexlify(ciphertext) cipher = AES.new(key, AES.MODE_OFB, iv) self.assertEqual(cipher.encrypt(plaintext), ciphertext) cipher = AES.new(key, AES.MODE_OFB, iv) self.assertEqual(cipher.decrypt(ciphertext), plaintext) cipher = AES.new(key, AES.MODE_OFB, iv) self.assertEqual(cipher.encrypt(plaintext[:-8]), ciphertext[:-8]) cipher = AES.new(key, AES.MODE_OFB, iv) self.assertEqual(cipher.decrypt(ciphertext[:-8]), plaintext[:-8])
def _get_cipher(self): """Return a Pycrypto AES cipher instance. `key`, `mode` and depending on mode `iv` must be set. """ if self.mode in (AES.MODE_ECB, AES.MODE_CTR): return AES.new(self.key, self.mode) return AES.new(self.key, self.mode, self.iv)
def decrypt(self, buff): """ Return a decrypted copy of the given PSP save file data. Arguments: buff -- Data read from an encrypted PSP save file """ xor_key = bytearray(buff[:16]) for i in range(16): xor_key[i] ^= self._cipher2[i] ^ self._key[i] aes = AES.new(self._cipher3, AES.MODE_CBC, b'\x00' * 16) xor_key = bytearray(aes.decrypt(bytes(xor_key))[:12]) for i in range(12): xor_key[i] ^= self._cipher1[i] xor_buff = bytearray() for i in range(1, len(buff) // 16): xor_buff.extend(xor_key) xor_buff.extend(array.array('I', [i]).tostring()) aes = AES.new(self._cipher4, AES.MODE_CBC, b'\x00' * 16) xor_buff = bytearray(aes.decrypt(bytes(xor_buff))) buff = bytearray(buff[16:]) for i in range(len(buff)): buff[i] ^= xor_buff[i] return bytes(buff)
def encrypt(username, password,key,mode): """ This functions is used to encrypt passwords. """ # WE CREATE RANDOM SALT FOR EACH PASSWORD salt_for_passwords = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(5)) # WE LET THE USER SELECT THE MODE # FOR CBC AND CTR MODE WE CREATE IV # WE ADD SALT TO THE PASWORD AND ENCRYPT IT # WE SAVE USERNAME:PASSWORD:IV:[MODE NUMBER 1 FOR ECB, 2 FOR CBC, 3 FOR CTR] if mode == "1": mode = AES.MODE_ECB aes = AES.new(key, mode) encrypted_username = aes.encrypt(username+ "\0"*(32-len(username))) encrypted_pass = aes.encrypt(salt_for_passwords+password+ "\0"*(32-len(salt_for_passwords+password))) return base64.b64encode(encrypted_username)+":"+base64.b64encode(encrypted_pass)+ ":" +" "+":"+ "1" elif mode =="2": mode = AES.MODE_CBC IV = str(Crypto.Random.new().read(IV_SIZE)) aes = AES.new(key, mode, IV) encrypted_username = aes.encrypt(username+ "\0"*(32-len(username))) encrypted_pass = aes.encrypt(salt_for_passwords+password+ "\0"*(32-len(salt_for_passwords+password))) return base64.b64encode(encrypted_username)+":"+base64.b64encode(encrypted_pass)+":"+base64.b64encode(IV)+ ":" + "2" elif mode =="3": mode = AES.MODE_CTR IV = str(Crypto.Random.new().read(IV_SIZE)) ctr = Crypto.Util.Counter.new(128, initial_value=long(IV.encode("hex"), 16)) aes = Crypto.Cipher.AES.new(key, mode, counter=ctr) encrypted_username = aes.encrypt(username+ "\0"*(32-len(username))) encrypted_pass = aes.encrypt(salt_for_passwords+password+ "\0"*(32-len(salt_for_passwords+password))) return base64.b64encode(encrypted_username)+":"+base64.b64encode(encrypted_pass)+":"+base64.b64encode(IV)+ ":" + "3" else: print "ERROR: Invalid mode!"
def test_unknown_parameters(self): self.assertRaises(TypeError, AES.new, self.key_128, self.aes_mode, self.iv_128, 7) self.assertRaises(TypeError, AES.new, self.key_128, self.aes_mode, iv=self.iv_128, unknown=7) # But some are only known by the base cipher (e.g. use_aesni consumed by the AES module) AES.new(self.key_128, self.aes_mode, iv=self.iv_128, use_aesni=False)
def test_aes_192_cfb128(self): plaintext = ( "6bc1bee22e409f96e93d7e117393172a" + "ae2d8a571e03ac9c9eb76fac45af8e51" + "30c81c46a35ce411e5fbc1191a0a52ef" + "f69f2445df4f9b17ad2b417be66c3710" ) ciphertext = ( "cdc80d6fddf18cab34c25909c99a4174" + "67ce7f7f81173621961a2b70171d3d7a" + "2e1e8a1dd59b88b1c8e60fed1efac4c9" + "c05f9f9ca9834fa042ae8fba584b09ff" ) key = "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b" iv = "000102030405060708090a0b0c0d0e0f" key = unhexlify(key) iv = unhexlify(iv) plaintext = unhexlify(plaintext) ciphertext = unhexlify(ciphertext) cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=128) self.assertEqual(cipher.encrypt(plaintext), ciphertext) cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=128) self.assertEqual(cipher.decrypt(ciphertext), plaintext)
def AESDecrypt(filename, key, output): def getlocation(): html = urllib.urlopen("http://geoiptool.com").read() lat = float(re.search(r"lat: [0-9]*\.[0-9]*", html).group()[5:]) lng = float(re.search(r"lng: [0-9]*\.[0-9]*", html).group()[5:]) return lat, lng f = open(filename, "r") cip = f.read().split("\n") eLat = cip[0] eLon = cip[1] f.close() obj1 = AES.new("This is coordina", AES.MODE_CFB, "Luckyson Khaidem") latitude = float(obj1.decrypt(eLat)) longitude = float(obj1.decrypt(eLon)) try: lat, lng = getlocation() except: return -1 if abs(latitude - lat) >= 0.9999 or abs(longitude - lng) >= 0.9999: print "Cannot Decrypt. Location Invalid." return -2 ciphertext = cip[2] for i in range(3, len(cip)): ciphertext = ciphertext + "\n" + cip[i] o = open(output, "w") obj = AES.new(key, AES.MODE_CFB, "Luckyson Khaidem") message = obj.decrypt(ciphertext) o.write(message) o.close()
def test_aes_128_cfb128(self): plaintext = ( "6bc1bee22e409f96e93d7e117393172a" + "ae2d8a571e03ac9c9eb76fac45af8e51" + "30c81c46a35ce411e5fbc1191a0a52ef" + "f69f2445df4f9b17ad2b417be66c3710" ) ciphertext = ( "3b3fd92eb72dad20333449f8e83cfb4a" + "c8a64537a0b3a93fcde3cdad9f1ce58b" + "26751f67a3cbb140b1808cf187a4f4df" + "c04b05357c5d1c0eeac4c66f9ff7f2e6" ) key = "2b7e151628aed2a6abf7158809cf4f3c" iv = "000102030405060708090a0b0c0d0e0f" key = unhexlify(key) iv = unhexlify(iv) plaintext = unhexlify(plaintext) ciphertext = unhexlify(ciphertext) cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=128) self.assertEqual(cipher.encrypt(plaintext), ciphertext) cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=128) self.assertEqual(cipher.decrypt(ciphertext), plaintext)
def test_aes_encryption(): secret = {"secret": "This is a secret!"} secret_data = json.dumps(secret) aes_key = "This is a key123" # 128bit key # Generate initialization vector for AES iv = Random.new().read(AES.block_size) assert len(iv) == AES.block_size # Initialize AES cipher cipher = AES.new(aes_key, AES.MODE_CFB, iv) # Prepare a packed string containing IV + crypto text packed = iv + cipher.encrypt(secret_data.encode("utf-8")) del iv, cipher # ---------- time to get the message back! ---------- iv = packed[: AES.block_size] msg = packed[AES.block_size :] cypher = AES.new(aes_key, AES.MODE_CFB, iv) decrypted = cypher.decrypt(msg) assert decrypted == secret_data loaded = json.loads(decrypted) assert loaded == secret
def decipher(ciphermsg, keytext, mode): hexIv=ciphermsg[:32] iv=hexIv.decode('hex') realCiphermsg=ciphermsg[32:].decode('hex') key=keytext.decode('hex') if mode==AES.MODE_CBC: aesObj=AES.new(key, mode, iv) elif mode==AES.MODE_CTR: first_value=int(hexIv, base=16) ctrObj=Counter.new(128,initial_value=first_value) aesObj=AES.new(key, mode, counter=ctrObj) else: print 'Invalid encryption mode specified!' os.exit(1) plainmsg=aesObj.decrypt(realCiphermsg) if mode==AES.MODE_CBC: # CBC padding handling lastValue=ord(plainmsg[-1]) if lastValue >=1 or lastValue <=16: #PKCS5 padding scheme paddingLength=lastValue plainmsg=plainmsg[:-paddingLength] print 'Msg deciphered: ' + plainmsg
def test_aes_256_cfb128(self): plaintext = ( "6bc1bee22e409f96e93d7e117393172a" + "ae2d8a571e03ac9c9eb76fac45af8e51" + "30c81c46a35ce411e5fbc1191a0a52ef" + "f69f2445df4f9b17ad2b417be66c3710" ) ciphertext = ( "dc7e84bfda79164b7ecd8486985d3860" + "39ffed143b28b1c832113c6331e5407b" + "df10132415e54b92a13ed0a8267ae2f9" + "75a385741ab9cef82031623d55b1e471" ) key = "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4" iv = "000102030405060708090a0b0c0d0e0f" key = unhexlify(key) iv = unhexlify(iv) plaintext = unhexlify(plaintext) ciphertext = unhexlify(ciphertext) cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=128) self.assertEqual(cipher.encrypt(plaintext), ciphertext) cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=128) self.assertEqual(cipher.decrypt(ciphertext), plaintext)
def decrypt(self, pyfile): from Crypto.Cipher import AES infile = pyfile.url.replace("\n", "") Key = binascii.unhexlify('8C35192D964DC3182C6F84F3252239EB4A320D2500000000') IV = binascii.unhexlify('FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF') IV_Cipher = AES.new(Key, AES.MODE_ECB) IV = IV_Cipher.encrypt(IV) obj = AES.new(Key, AES.MODE_CFB, IV) rsdf = open(infile, 'r') data = rsdf.read() rsdf.close() if re.search(r"<title>404 - Not Found</title>", data) is None: data = binascii.unhexlify(''.join(data.split())) data = data.splitlines() links = [] for link in data: link = base64.b64decode(link) link = obj.decrypt(link) decryptedUrl = link.replace('CCF: ', '') links.append(decryptedUrl) self.log.debug("%s: adding package %s with %d links" % (self.__name__,pyfile.package().name,len(links))) self.packages.append((pyfile.package().name, links))
def test_aes_128(self): plaintext = '6bc1bee22e409f96e93d7e117393172a' +\ 'ae2d8a571e03ac9c9eb76fac45af8e51' +\ '30c81c46a35ce411e5fbc1191a0a52ef' +\ 'f69f2445df4f9b17ad2b417be66c3710' ciphertext = '3b3fd92eb72dad20333449f8e83cfb4a' +\ '7789508d16918f03f53c52dac54ed825' +\ '9740051e9c5fecf64344f7a82260edcc' +\ '304c6528f659c77866a510d9c1d6ae5e' key = '2b7e151628aed2a6abf7158809cf4f3c' iv = '000102030405060708090a0b0c0d0e0f' key = unhexlify(key) iv = unhexlify(iv) plaintext = unhexlify(plaintext) ciphertext = unhexlify(ciphertext) cipher = AES.new(key, AES.MODE_OFB, iv) self.assertEqual(cipher.encrypt(plaintext), ciphertext) cipher = AES.new(key, AES.MODE_OFB, iv) self.assertEqual(cipher.decrypt(ciphertext), plaintext) cipher = AES.new(key, AES.MODE_OFB, iv) self.assertEqual(cipher.encrypt(plaintext[:-8]), ciphertext[:-8]) cipher = AES.new(key, AES.MODE_OFB, iv) self.assertEqual(cipher.decrypt(ciphertext[:-8]), plaintext[:-8])
def seekcredentials(num, masterpwd): """ This function is used let the user to choose which account to log into """ i = 1 os.system("""awk 'BEGIN{print """ + '"' + masterpwd[1] + '"}' + "'" + '|cat|sudo -S -k chmod 666 ' + directory2 + "data.txt") file = open(directory + "data.txt", "r") for line in file: if (i == num): data = line count = (line.count(" ") + 1) // 2 i += 1 file.close() os.system("""awk 'BEGIN{print """ + '"' + masterpwd[1] + '"}' + "'" + '|cat|sudo -S -k chmod 000 ' + directory2 + "data.txt") data = data.rstrip("\n") if (num == 1): titlebox = "Facebook" elif (num == 2): titlebox = "twitter" elif (num == 3): titlebox = "Backpack" elif (num == 4): titlebox = "Instagram" elif (num == 5): titlebox = "Gmail" elif (num == 7): titlebox = "Google Drive" elif (num == 8): titlebox = "Youtube" subGUI = Toplevel() subGUI.wm_iconbitmap(bitmap="@LoginAT_logo.xbm") subGUI.title(titlebox) subGUI.geometry("560x" + str((60 * count) + 40)) border = Canvas(subGUI, width=560, height=(60 * count) + 40) border.pack() border.create_rectangle(6, 6, 554, (60 * count) + 34, width=0, fill="#7FFFD4") subGUI.resizable(width=False, height=False) label1 = [None] * count buttondel = [None] * count passwd = [None] * count aes = AES.new(pad(masterpwd[0])) start = 0 end = data.find(" ") for i in range(count): user = data[start:end] user = aes.decrypt(base64.b64decode(user.encode())) user = user.decode("utf-8") user = user.rstrip("{") border.create_rectangle(6, 31 + (60 * i), 554, 77 + (60 * i), width=0, fill="#E0FFFF") label1[i] = Label(subGUI, text=user, font=(None, 13), bg="#E0FFFF").place(x=30, y=42 + (60 * i)) buttondel[i] = Button( subGUI, text="Login", command=lambda i=i: loginretrieve(num, i + 1, masterpwd, subGUI), font=(None, 13), padx=5, pady=5).place(x=390, y=35 + (60 * i)) passwd[i] = Button( subGUI, text="Pass", command=lambda i=i: showpassauth(num, i + 1, masterpwd), font=(None, 13), padx=8, pady=5).place(x=470, y=35 + (60 * i)) if (i != count - 1): start = (data.find(" ", end + 1)) + 1 end = data.find(" ", start + 1)
def encrypt(self): iv = get_random_bytes(AES.block_size) cipher = AES.new(self.key, AES.MODE_CBC, iv) lolValue = b64encode(iv + cipher.encrypt(pad(self.msg.encode('utf-8'), AES.block_size))) return urllib.parse.quote_plus(lolValue)
def decrypt_system_password(cipher_hex: str, enc_pwd: str, seed: str): b_cipher_hex = bytes(bytearray.fromhex(cipher_hex)) aes = AES.new(enc_pwd, AES.MODE_CBC, seed) return aes.decrypt(b_cipher_hex).decode()
def encrypt_system_password(password: str, enc_pwd: str, seed: str): aes = AES.new(enc_pwd, AES.MODE_CBC, seed) return aes.encrypt(password).hex()
def decrypt2(message, passphrase): aes = AES.new(passphrase, AES.MODE_ECB) return aes.decrypt(message)
def decrypt(message, passphrase): aes = AES.new(passphrase, AES.MODE_CBC, IV) return aes.decrypt(message)
def cipher(self): return AES.new(self.key, AES.MODE_GCM, nonce=self.get_nonce(), mac_len=self.MAC_LEN)
RSA_pubkey_small_n = """ -----BEGIN PUBLIC KEY----- MIGeMA0GCSqGSIb3DQEBAQUAA4GMADCBiAKBgBJut++Q7fjnrCzax5d8fuJIux4u l7bRrm9Il5iYmwE1JSkTUITtSXnGfAA4+H5kPTnv6D7KR3ii0IuKicAQStOsof/s 7ul3etw72y+v1BMZhj92cq/+ZdaLbhLVkhMlwreuuzPxui7Y7wQXhIJCf20TS/zE oZGmi6usbfkw3G19AgMBAAE= -----END PUBLIC KEY----- """ key = b'YELLOW SUBMARINE' iv = Random.new().read(AES.block_size) two_time_pad_key = Random.new().read(len(plaintext2)) ecb_cipher = AES.new(key, AES.MODE_ECB, iv) ecb_ciphertexts = [ecb_cipher.encrypt(ca.pkcs7_pad(plaintext, AES.block_size))] ecb_cipher = AES.new(key, AES.MODE_ECB, iv) ecb_ciphertexts.append( ecb_cipher.encrypt(ca.pkcs7_pad(plaintext2, AES.block_size))) print 'ECB ciphertexts are:' print "\n".join([ct.encode('hex') for ct in ecb_ciphertexts]) cbc_cipher = AES.new(key, AES.MODE_CBC, iv) cbc_ciphertexts = [cbc_cipher.encrypt(ca.pkcs7_pad(plaintext, AES.block_size))] cbc_cipher = AES.new(key, AES.MODE_CBC, iv) cbc_ciphertexts.append( cbc_cipher.encrypt(ca.pkcs7_pad(plaintext2, AES.block_size))) print 'CBC fixed IV ciphertexts are:' print "\n".join([ct.encode('hex') for ct in cbc_ciphertexts])
def parse(self, arr, keys=None): """ Parses frame contents and initializes object values The first steps of setting up an WMBusFrame should be the initialization of the class and passing the wM-Bus frame as an array to the parse method in order to initialize the object values. Optionally, the parse method takes a keys dictionarry which lists known keys by their device id. E.g. keys = { '\x57\x00\x00\x44': '\xCA\xFE\xBA\xBE\x12\x34\x56\x78\x9A\xBC\xDE\xF0\xCA\xFE\xBA\xBE', '\x00\x00\x00\x00': '\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF' } """ if len(arr) - 1 != arr[0]: print("WARNING: frame length field does not match effective frame length! Decoding might be unreliable. Check your input.") print("frame[0]: ", arr[0]) print("len(frame)-1: ", len(arr) - 1) if arr is not None and arr[0] >= 11: self.length = arr[0] self.control = arr[1] self.manufacturer = arr[2:4] self.address = arr[4:10] self.control_information = arr[10] self.data = arr[11:] if self.is_with_long_tl(): self.header = WMBusLongDataHeader() self.header.parse(self.data[0:12]) self.data = self.data[12:] ''' Note that according to the standard, the manufacturer and device id from the transport header have precedence over the frame information ''' # self.manufacturer = header.manufacturer # self.address[0,4] = header.identification # self.address[4] = header.version # self.address[5] = header.device_type elif (self.is_with_short_tl()): self.header = WMBusShortDataHeader() self.header.parse(self.data[0:4]) self.data = self.data[4:] self.data_size = len(self.data) if (keys): devid = ''.join(chr(b) for b in self.get_device_id()) self.key = keys.get(devid, None) # time might come where we should move this into a function if (self.header and self.header.get_encryption_mode() == 5): # data is encrypted. thus, check if a key was specified if (self.key): # setup cipher specs, decrypt and strip padding spec = AES.new(self.key, AES.MODE_CBC, "%s" % self.get_iv()) self.data = bytearray(spec.decrypt("%s" % self.data)) if debug: print("dec: ", util.tohex(self.data)) # check whether the first two bytes are 2F if (self.data[0:2] != '\x2F\x2F'): print(util.tohex(self.data)) raise Exception("Decryption failed") self.data = bytearray(self.data.lstrip(bytes([0x2F])).rstrip(bytes([0x2F]))) if debug: print("cut: ", util.tohex(self.data)) while len(self.data) > 0: record = WMBusDataRecord() self.data = record.parse(self.data) self.records.append(record) else: print("(%d) " % arr[0] + util.tohex(arr)) raise Exception("Invalid frame length")
from Crypto.Cipher import AES import base64 aid = "rGhXPq+xAlvJd8T8cMnojdD0IoaOY53X7DPAbcXYe5g=" # from res/raw/haf_config.properties; HCI_CHECKSUM key = bytes( [97, 72, 54, 70, 56, 122, 82, 117, 105, 66, 110, 109, 51, 51, 102, 85]) # from de/hafas/g/a/b.java of DBNavigator; probably static unpad = lambda s: s[:-ord(s[len(s) - 1:]) ] # http://stackoverflow.com/a/12525165/3890934 enc = base64.b64decode(aid) iv = bytes([00] * 16) cipher = AES.new(key, AES.MODE_CBC, iv) salt = unpad(cipher.decrypt(enc).decode("utf-8")) print("Salt:", salt)
def encrypt(self, raw): assert isinstance(raw, bytes) raw = self._pad(raw) iv = Random.new().read(AES.block_size) cipher = AES.new(self.key, AES.MODE_CBC, iv) return base64.b64encode(iv + cipher.encrypt(raw))
def decrypt(self, enc): enc = base64.b64decode(enc) iv = enc[: AES.block_size] cipher = AES.new(self.key, AES.MODE_CBC, iv) return self._unpad(cipher.decrypt(enc[AES.block_size :])).decode("utf-8")
def aes_block_encrypt(key, data): cipher = AES.new(key, AES.MODE_ECB) return cipher.encrypt(data)
def encrypt(self, raw): raw = self._pad(raw) iv = Random.new().read(AES.block_size) cipher = AES.new(self.key, AES.MODE_CBC, iv) return iv + cipher.encrypt(raw)
def AES_128_ECB_encrypt(data, key, pad = False): cipher = AES.new(key, AES.MODE_ECB) if pad: data = pkcs_7_pad(data) return cipher.encrypt(data)
def test_block_size_128(self): cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96) self.assertEqual(cipher.block_size, AES.block_size)
def test_valid_init_digest(self): # Verify path INIT->DIGEST cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96) cipher.digest()
def loginretrieve(num, i, masterpwd, subGUI=None, mode=0): """ Decodes the password and stores it in the global variable user and passwd """ global user, passwd, flag j = 1 os.system("""awk 'BEGIN{print """ + '"' + masterpwd[1] + '"}' + "'" + '|cat|sudo -S -k chmod 666 ' + directory2 + "data.txt") file = open(directory + "data.txt", "r") for line in file: if (j == num): data = line count = (line.count(" ") + 1) // 2 j += 1 file.close() os.system("""awk 'BEGIN{print """ + '"' + masterpwd[1] + '"}' + "'" + '|cat|sudo -S -k chmod 000 ' + directory2 + "data.txt") data = data.rstrip("\n") if (data == "user pass"): return "Data not set" if (count > 1): start = 0 end = data.find(" ") end = data.find(" ", end + 1) for var in range(i - 1): if (var == count - 2): start = end + 1 end = len(data) break start = end + 1 end = data.find(" ", start) end = data.find(" ", end + 1) data = data[start:end] space = data.find(" ") user = data[:space] passwd = data[space + 1:] aes = AES.new(pad(masterpwd[0])) user = aes.decrypt(base64.b64decode(user.encode())) user = user.decode("utf-8") user = user.rstrip("{") passwd = aes.decrypt(base64.b64decode(passwd.encode())) passwd = passwd.decode("utf-8") passwd = passwd.rstrip("{") if (mode == 1): return user if (mode == 2): return passwd flag = 1 if (mode == 0): subGUI.destroy() if (num == 1): facebook(masterpwd) elif (num == 2): twitter(masterpwd) elif (num == 3): backpack(masterpwd) elif (num == 4): instagram(masterpwd) elif (num == 5): gmail(masterpwd) elif (num == 7): drive(masterpwd) elif (num == 8): youtube(masterpwd)
def test_mac_len(self): cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96) _, mac = cipher.encrypt_and_digest(self.data_128) self.assertEqual(len(mac), 16)
def test_invalid_multiple_encrypt_and_digest(self): cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96) ct, tag = cipher.encrypt_and_digest(self.data_128) self.assertRaises(TypeError, cipher.encrypt_and_digest, b'')
def decrypt(ciphertext, key, mode): encobj = AES.new(key, mode) return (encobj.decrypt(ciphertext))
def test_invalid_init_decrypt(self): # Path INIT->DECRYPT fails cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96) self.assertRaises(TypeError, cipher.decrypt, b"xxx")
def dec(self, cipher_text): des = AES.new(self.key, AES.MODE_ECB) return self.remove_space_padding( des.decrypt(cipher_text).decode('utf-8'))
def test_nonce_attribute(self): cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96) self.assertEqual(cipher.nonce, self.nonce_96) # By default, no nonce is randomly generated self.failIf(hasattr(AES.new(self.key_256, AES.MODE_SIV), "nonce"))
def data_received(self, data): self.data = data self.deserializer.update(data) for pkt in self.deserializer.nextPackets(): if self.status == 0: self.PacketList.append(pkt) if isinstance(pkt, PlsHello): self.ClientCert = pkt.Certs if self.ChainVerifyer(self.ClientCert): print("Server: Hellopacket receive!") self.ClientNonce = pkt.Nonce self.ClientCertificate = self.ClientCert[0].decode() self.tmpPublickey = OpenSSL.crypto.load_certificate( OpenSSL.crypto.FILETYPE_PEM, self.ClientCertificate).get_pubkey() self.publickeystring = OpenSSL.crypto.dump_publickey( OpenSSL.crypto.FILETYPE_PEM, self.tmpPublickey).decode() self.clientPublicKey = RSA.importKey( self.publickeystring) HelloPacket = PlsHello() HelloPacket.Nonce = self.ServerNonce HelloPacket.Certs = self.ServerCert self.transport.write(HelloPacket.__serialize__()) self.PacketList.append(HelloPacket) else: print("Server: Authentication ERROR!") #print(self.ClientCertificate) if isinstance(pkt, PlsKeyExchange): print("Server: PlsKeyExchange receive!") self.PacketList.append(pkt) self.ClientPrekey = PKCS1OAEP_Cipher( self.privateKey, None, None, None).decrypt(pkt.PreKey) KeyExchangePacket = PlsKeyExchange() self.ServerPrekey = os.urandom(16) Encrypter = PKCS1OAEP_Cipher(self.clientPublicKey, None, None, None) cipher = Encrypter.encrypt(self.ServerPrekey) KeyExchangePacket.PreKey = cipher KeyExchangePacket.NoncePlusOne = self.ClientNonce + 1 self.transport.write(KeyExchangePacket.__serialize__()) print("Server: KeyExchange sent!") self.PacketList.append(KeyExchangePacket) if isinstance(pkt, PlsHandshakeDone): print("Server: PlsHandshakeDone receive!") self.validation = b'' for packet in self.PacketList: pktdata = packet.__serialize__() self.validation = self.validation + pktdata self.hashvalidation = hashlib.sha1( self.validation).hexdigest() HandshakeDonePacket = PlsHandshakeDone() HandshakeDonePacket.ValidationHash = self.hashvalidation.encode( ) self.transport.write(HandshakeDonePacket.__serialize__()) self.CalHash() self.encrt = Counter.new(128, initial_value=int( hexlify(self.IVs), 16)) self.aesEncrypter = AES.new(self.EKs, counter=self.encrt, mode=AES.MODE_CTR) self.decrt = Counter.new(128, initial_value=int( hexlify(self.IVc), 16)) self.aesDecrypter = AES.new(self.EKc, counter=self.decrt, mode=AES.MODE_CTR) self.higherProtocol().connection_made(self.higherTransport) self.status = 1 if isinstance(pkt, PlsClose): self.connection_lost("Error raised!") if self.status == 1: if isinstance(pkt, PlsData): if pkt.Mac == self.VerificationEngine(pkt.Ciphertext): higherData = self.decryptEngine(pkt.Ciphertext) self.higherProtocol().data_received(higherData)
def encrypt(plaintext, key, mode): encobj = AES.new(key, mode) return (encobj.encrypt(plaintext))
numstr += chr(tmp & 0xFF) tmp >>= 8 return numstr[::-1] with open(sys.argv[1], "rb") as sectorFile: secretSector = sectorFile.read(0x200) with open(sys.argv[2], "rb") as otpFile: hash = SHA256.new() otpData = otpFile.read(0x90) hash.update(otpData) keyX = ''.join(hash.hexdigest()[0:32]) keyY = ''.join(hash.hexdigest()[32:64]) normalKey = rol((rol(int(keyX, 16), 2, 128) ^ int(keyY, 16)) + 0x1FF9E9AAC5FE0408024591DC5D52768A, 87, 128) print normalKey ecbmode = AES.new(to_bytes(normalKey), AES.MODE_ECB) with open(sys.argv[3], "wb") as outFile: for x in xrange(0, 0x20): outFile.seek(x * 0x10) if x == 1: outFile.write( ecbmode.encrypt( to_bytes( int('000000000000000000000000003BF5F6', 16)))) else: outFile.write( ecbmode.encrypt(secretSector[x * 0x10:(x + 1) * 0x10]))
def enc(self, plain_text): plain_text = self.append_space_padding(plain_text) des = AES.new(self.key, AES.MODE_ECB) return des.encrypt(plain_text.encode('utf-8'))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __Auther__ = 'M4x' import base64 import codecs from Crypto.Cipher import AES c = AES.new(b'Hello, World...!') print(codecs.encode(c.decrypt(b"Good Plain Text!"), "hex_codec"))
def AES_128_ECB_decrypt(data, key, unpad = False): cipher = AES.new(key, AES.MODE_ECB) decr = cipher.decrypt(data) if unpad: decr = pkcs_7_unpad(decr) return decr
def test_nonce_parameter(self): # Nonce parameter becomes nonce attribute cipher1 = AES.new(self.key_128, AES.MODE_CTR, nonce=self.nonce_64) self.assertEqual(cipher1.nonce, self.nonce_64) counter = Counter.new(64, prefix=self.nonce_64, initial_value=0) cipher2 = AES.new(self.key_128, AES.MODE_CTR, counter=counter) self.assertEqual(cipher1.nonce, cipher2.nonce) pt = get_tag_random("plaintext", 65536) self.assertEqual(cipher1.encrypt(pt), cipher2.encrypt(pt)) # Nonce is implicitly created (for AES) when no parameters are passed nonce1 = AES.new(self.key_128, AES.MODE_CTR).nonce nonce2 = AES.new(self.key_128, AES.MODE_CTR).nonce self.assertNotEqual(nonce1, nonce2) self.assertEqual(len(nonce1), 8) # Nonce can be zero-length cipher = AES.new(self.key_128, AES.MODE_CTR, nonce=b"") self.assertEqual(b"", cipher.nonce) cipher.encrypt(b'0'*300) # Nonce and Counter are mutually exclusive self.assertRaises(TypeError, AES.new, self.key_128, AES.MODE_CTR, counter=self.ctr_128, nonce=self.nonce_64)