def handledata(): if pkt1.smsg.stepNumber == 0: sender = temp_known_users[addr]["name"] kAB = known_users[sender]["ssAB"] rcvdmsg = ast.literal_eval(pkt1.smsg.actMsg) aesgcm = AESGCM(kAB) try: rmsg = aesgcm.decrypt(rcvdmsg["nonceformsg"], rcvdmsg["msg"], None) print sender, ":", rmsg except cryptography.exceptions.InvalidTag: print "Decrypt not okay" elif pkt1.smsg.stepNumber == 1: rec = temp_known_users[addr]["name"] kAB = known_users[rec]["ssAB"] rcvdmsg = ast.literal_eval(pkt1.smsg.actMsg) aesgcm = AESGCM(kAB) try: rmsg = aesgcm.decrypt(rcvdmsg["nonceforct"], rcvdmsg["ct"], None) if rmsg == "Bye": del known_users[rec] del temp_known_users[addr] print rec, "terminated the session with you" except cryptography.exceptions.InvalidTag: print "Decrypt not okay" else: print "Invalid packet"
def test_aes_gcm_aead_api(backend, wycheproof): key = binascii.unhexlify(wycheproof.testcase["key"]) iv = binascii.unhexlify(wycheproof.testcase["iv"]) aad = binascii.unhexlify(wycheproof.testcase["aad"]) msg = binascii.unhexlify(wycheproof.testcase["msg"]) ct = binascii.unhexlify(wycheproof.testcase["ct"]) tag = binascii.unhexlify(wycheproof.testcase["tag"]) if len(iv) < 8 or len(iv) > 128: pytest.skip( "Less than 64-bit IVs (and greater than 1024-bit) are no longer " "supported") if backend._fips_enabled and len(iv) != 12: # Red Hat disables non-96-bit IV support as part of its FIPS # patches. pytest.skip("Non-96-bit IVs unsupported in FIPS mode.") aesgcm = AESGCM(key) if wycheproof.valid or wycheproof.acceptable: computed_ct = aesgcm.encrypt(iv, msg, aad) assert computed_ct == ct + tag computed_msg = aesgcm.decrypt(iv, ct + tag, aad) assert computed_msg == msg else: with pytest.raises(InvalidTag): aesgcm.decrypt(iv, ct + tag, aad)
def test_vectors(self, backend, subtests): vectors = _load_gcm_vectors() for vector in vectors: with subtests.test(): nonce = binascii.unhexlify(vector["iv"]) if backend._fips_enabled and len(nonce) != 12: # Red Hat disables non-96-bit IV support as part of its # FIPS patches. pytest.skip("Non-96-bit IVs unsupported in FIPS mode.") key = binascii.unhexlify(vector["key"]) aad = binascii.unhexlify(vector["aad"]) ct = binascii.unhexlify(vector["ct"]) pt = binascii.unhexlify(vector.get("pt", b"")) tag = binascii.unhexlify(vector["tag"]) aesgcm = AESGCM(key) if vector.get("fail") is True: with pytest.raises(InvalidTag): aesgcm.decrypt(nonce, ct + tag, aad) else: computed_ct = aesgcm.encrypt(nonce, pt, aad) assert computed_ct[:-16] == ct assert computed_ct[-16:] == tag computed_pt = aesgcm.decrypt(nonce, ct + tag, aad) assert computed_pt == pt
class AEAD(): '''Authenticated encryption with associated data (AEAD)''' def __init__(self, aad='0', key=None, nonce=os.urandom(12)): self.key = key self.nonce = nonce self.aad = aad.encode(encoding='utf-8') self.aead = AESGCM(self.key) if key != None else None #self.hash = hashes.Hash(hashes.SHA256(), backend=default_backend()) def _methodinit(self, key=None): '''initial for encrypt and decrypt''' if key != None: self.key = key if self.aead == None: self.aead = AESGCM(self.key) # encrypt data def encrypt(self, msg, nonce=None, *, key=None): self._methodinit(key=key) if nonce == None: self.NewNonce() return base64.b64encode( self.aead.encrypt( self.nonce, msg.encode(encoding='utf-8'), self.aad)).decode(encoding='utf-8'), base64.b64encode( self.nonce).decode(encoding='utf-8'), base64.b64encode( self.aad).decode(encoding='utf-8') else: return base64.b64encode( self.aead.encrypt( nonce, msg.encode(encoding='utf-8'), self.aad)).decode(encoding='utf-8'), base64.b64encode( self.nonce).decode(encoding='utf-8'), base64.b64encode( self.aad).decode(encoding='utf-8') # decrypt chiper text def decrypt(self, ct, nonce=None, aad='0', *, key=None): self._methodinit(key=key) if nonce == None: return self.aead.decrypt( self.nonce, base64.b64decode(ct), base64.b64decode(aad)).decode(encoding='utf-8') else: return self.aead.decrypt( base64.b64decode(nonce.encode(encoding='utf-8')), base64.b64decode(ct), base64.b64decode(aad.encode('utf-8'))).decode(encoding='utf-8') # don't reuse nonce def NewNonce(self): self.nonce = os.urandom(12) def NewKey(self, key): self.key = key def GetKey(self): return self.key def GetNonce(self): return self.nonce
def __decrypt(self, salt, nonce, name, encrypted_sumoregion, encrypted_accesskeyid, encrypted_accesskey): # generate a hash from the salt we were sent to be used in decryption # self.iterations is set in __init__ kdf = PBKDF2HMAC(algorithm=hashes.SHA3_512(), length=32, salt=salt, iterations=self.iterations, backend=default_backend()) # here's our encryption key key = kdf.derive(self.password) cipher = AESGCM(key) # these are returned as byte objects sumoregion = cipher.decrypt(nonce, encrypted_sumoregion, None) accesskeyid = cipher.decrypt(nonce, encrypted_accesskeyid, None) accesskey = cipher.decrypt(nonce, encrypted_accesskey, None) # This method should always return strings, so we have to decode the results from the cypher data = { 'name': name, 'sumoregion': base64.urlsafe_b64decode(sumoregion).decode(self.system_encoding), 'accesskeyid': base64.urlsafe_b64decode(accesskeyid).decode(self.system_encoding), 'accesskey': base64.urlsafe_b64decode(accesskey).decode(self.system_encoding) } return data
def test_params_not_bytes(self, nonce, data, associated_data, backend): key = AESGCM.generate_key(128) aesgcm = AESGCM(key) with pytest.raises(TypeError): aesgcm.encrypt(nonce, data, associated_data) with pytest.raises(TypeError): aesgcm.decrypt(nonce, data, associated_data)
def AES_GCM_ecnrypt(text): data = bytes(text,'utf-8') aad = bytes("Research",'utf-8') key = AESGCM.generate_key(bit_length=128) aesgcm = AESGCM(key) nonce = os.urandom(12) ct = aesgcm.encrypt(nonce, data, aad) aesgcm.decrypt(nonce, ct, aad) return True
def test_associated_data_none_equal_to_empty_bytestring(self, backend): key = AESGCM.generate_key(128) aesgcm = AESGCM(key) nonce = os.urandom(12) ct1 = aesgcm.encrypt(nonce, b"some_data", None) ct2 = aesgcm.encrypt(nonce, b"some_data", b"") assert ct1 == ct2 pt1 = aesgcm.decrypt(nonce, ct1, None) pt2 = aesgcm.decrypt(nonce, ct2, b"") assert pt1 == pt2
def eval(self, ct_sets): """Evaluates the ciphertexts for determining the cardinality of the set intersection Expects two dicts of ciphertexts.""" cardinality = 0 ct_intersection = ct_sets[0].keys() & ct_sets[1].keys() pt_intersection = set() cardinality = len(ct_intersection) if cardinality >= self.threshold: # we can determine the plaintext of the intersection def delta(S, i): prod = 1 for j in S: if i == j: continue prod *= j * (j - i)**(-1) return prod # first, recover co = f(0) xs, ys = [], [] for k in islice(ct_intersection, self.threshold): xs.append(self.group.deserialize(k)) ys.append( self.group.deserialize(ct_sets[0][k][0]) * self.group.deserialize(ct_sets[1][k][0])) c0 = sum([y * delta(xs, x) for x, y in zip(xs, ys)]) # now decrypt the intersection ae1_key = self._H(c0) ae1 = AESGCM(ae1_key) for k in ct_intersection: _, (ct1_k1_nonce, ct1_k1_sigma), (ct1_ae_nonce, ct1_ae_ct) = ct_sets[0][k] _, (ct2_k1_nonce, ct2_k1_sigma), _ = ct_sets[1][k] # recover k1 pt1_k1_sigma = ae1.decrypt(ct1_k1_nonce, ct1_k1_sigma, None) pt2_k1_sigma = ae1.decrypt(ct2_k1_nonce, ct2_k1_sigma, None) k1 = self.group.deserialize( pt1_k1_sigma) * self.group.deserialize(pt2_k1_sigma) # decrypt ct4 ae2_key = self._H(k1) ae2 = AESGCM(ae2_key) pt = ae2.decrypt(ct1_ae_nonce, ct1_ae_ct, None) pt_intersection.add(pt) return cardinality, pt_intersection
def data_received(self, data): self.buffer.update(data) for packet in self.buffer.nextPackets(): print("here") print(self.mode, "handsahek completete?", self.handshake.complete, "packet", packet) if isinstance(packet, ErrorPacket): print("Error packet:", packet.message) if not self.handshake.complete and isinstance( packet, HandshakePacket): print(self.mode, "crap received handshakepacket") self.process_handshake(packet) elif self.handshake.complete and isinstance(packet, DataPacket): print(self.mode, 'crap got data packet') aesgcm = AESGCM(self.higherProtocol().transport.decKey) print("Decrypting iv:", self.higherProtocol().transport.iv_other) print("Decrytping key:", self.higherProtocol().transport.decKey) try: print("Try decrypt") aesgcm = AESGCM(self.higherProtocol().transport.decKey) data = aesgcm.decrypt( nonce=self.higherProtocol().transport.iv_other, data=packet.data, associated_data=None) except Exception as e: print("Exception decrypt") aesgcm = AESGCM(self.higherProtocol().transport.encKey) data = aesgcm.decrypt( nonce=self.higherProtocol().transport.iv, data=packet.data, associated_data=None) print( int.from_bytes(self.higherProtocol().transport.iv_other, "big")) l = len(self.higherProtocol().transport.iv_other) temp = int.from_bytes(self.higherProtocol().transport.iv_other, "big") + 1 temp = temp.to_bytes(l, 'big') self.higherProtocol().transport.iv_other = temp[:16] print("passsint to higer..") self.higherProtocol().data_received(data) elif self.handshake.complete and isinstance( packet, ShutdownPacket): print(self.mode, "crap received shutdownpacket") self.process_shutdown_packet(packet)
def test_buffer_protocol(self, backend): key = AESGCM.generate_key(128) aesgcm = AESGCM(key) pt = b"encrypt me" ad = b"additional" nonce = os.urandom(12) ct = aesgcm.encrypt(nonce, pt, ad) computed_pt = aesgcm.decrypt(nonce, ct, ad) assert computed_pt == pt aesgcm2 = AESGCM(bytearray(key)) ct2 = aesgcm2.encrypt(bytearray(nonce), pt, ad) assert ct2 == ct computed_pt2 = aesgcm2.decrypt(bytearray(nonce), ct2, ad) assert computed_pt2 == pt
def transmitVote(vote, transactionId): keyExchange.completeExchange("Polling", "Audit") # Get shared key file = open("PollingToAuditSharedKey.txt", 'r') sharedKey = file.read() key = AESGCM.generate_key(bit_length=128) aesgcm = AESGCM(key) nonce = os.urandom(12) messageToSendBytes = aesgcm.encrypt( nonce, "{0},{1}".format(transactionId, vote).encode(), None) ctr = Counter.new(128) cipher = AES.new(sharedKey, AES.MODE_CTR, counter=ctr) keyToSend = cipher.encrypt(key) nonceToSend = cipher.encrypt(nonce) response = audit.transmitVote(messageToSendBytes, nonceToSend, keyToSend) responseCtr = Counter.new(128) receivedMessageCtr = Counter.new(128) receivedMessageCipher = AES.new(sharedKey, AES.MODE_CTR, counter=receivedMessageCtr) decryptedKey = receivedMessageCipher.decrypt(response[2]) decryptedNonce = receivedMessageCipher.decrypt(response[1]) aesgcm = AESGCM(decryptedKey) statusBytes = aesgcm.decrypt(decryptedNonce, response[0], None) status = eval(statusBytes.decode("utf-8")) return status
def isRegisteredVoter(voterId): keyExchange.completeExchange("Polling", "Registration") # Get shared key file = open("PollingToRegistrationSharedKey.txt", 'r') sharedKey = file.read() key = AESGCM.generate_key(bit_length=128) aesgcm = AESGCM(key) nonce = os.urandom(12) voterIdBytes = aesgcm.encrypt(nonce, voterId.encode(), None) ctr = Counter.new(128) cipher = AES.new(sharedKey, AES.MODE_CTR, counter=ctr) keyToSend = cipher.encrypt(key) nonceToSend = cipher.encrypt(nonce) response = registration.checkVoterStatus(voterIdBytes, nonceToSend, keyToSend) receivedMessageCtr = Counter.new(128) receivedMessageCipher = AES.new(sharedKey, AES.MODE_CTR, counter=receivedMessageCtr) decryptedKey = receivedMessageCipher.decrypt(response[2]) decryptedNonce = receivedMessageCipher.decrypt(response[1]) aesgcm = AESGCM(decryptedKey) statusBytes = aesgcm.decrypt(decryptedNonce, response[0], None) status = eval(statusBytes.decode("utf-8")) return status
def data_dec(self,data):#no print("dec") scheme = AESGCM(self.dec_key) plaintext = scheme.decrypt(self.peer_iv, data, None) self.peer_iv = (int.from_bytes(self.peer_iv, "big")+1).to_bytes(12,"big") print("fin dec") return plaintext
def keyeststep8(): received = ast.literal_eval(pkt1.smsg.actMsg) # otheruser = temp_known_users[addr]["name"] Session_AB = temp_known_users[addr]["Sab"] aesgcm = AESGCM(Session_AB) try: numbers = ast.literal_eval( aesgcm.decrypt(received["noncefornumbers"], received["encnumbers"], None)) # Verify the nonce returned if numbers["newN1"] == int(keyeststep6.N1) - 1: noncefordata = os.urandom(12) newN2 = int(numbers["N2"]) - 1 keyeststep8.s_g = 2 keyeststep8.s_p = int(random.getrandbits(32)) keyeststep8.u1_prikey = int(random.getrandbits(32)) u1_pubkey = pow(keyeststep8.s_g, keyeststep8.u1_prikey, keyeststep8.s_p) tobeenc = {"newn2": newN2, "dhA": u1_pubkey} enc_data = aesgcm.encrypt(noncefordata, bytes(tobeenc), None) step9output = { "noncefordata": noncefordata, "enc_data": enc_data, "g": keyeststep8.s_g, "p": keyeststep8.s_p } fillauthpacket(pkt1, "KEY_EST", 9, bytes(step9output)) sendpacket(pkt1.SerializeToString(), addr[0], addr[1]) else: print "Could not verify!" except cryptography.exceptions.InvalidTag: print "Decrypt not okay"
def keyeststep10(): received = ast.literal_eval(pkt1.smsg.actMsg) salt = received["salt"] aesgcm = AESGCM(temp_known_users[addr]["Sab"]) try: u2_pubkey = int( aesgcm.decrypt(received["nonceforu2pubkey"], received["enc_u2pubkey"], None)) ssAB = pow(u2_pubkey, keyeststep8.u1_prikey, keyeststep8.s_p) backend = default_backend() # derive kdf = Scrypt(salt=salt, length=32, n=2**14, r=8, p=1, backend=backend) kAB = kdf.derive(bytes(ssAB)) known_users[temp_known_users[addr]["name"]] = { "ssAB": kAB, "addr": addr } aesgcm = AESGCM(kAB) nonceformsg = os.urandom(12) message = aesgcm.encrypt(nonceformsg, keyestfunction.smsg, None) msgtosend = {"nonceformsg": nonceformsg, "msg": message} fillauthpacket(pkt1, "Data", 0, bytes(msgtosend)) sendpacket(pkt1.SerializeToString(), addr[0], addr[1]) except cryptography.exceptions.InvalidTag: print "Decrypt not okay"
def modify(packet): pkt = dpkt.ip6.IP6(packet.get_payload()) if is_icmp_neighbour_message(pkt): packet.accept() return aes_key_text = pkt.data[:256] aes_key_text = asymmetrickeyc.decrypt(aes_key_text) nonce = struct.unpack(">I", pkt.data[256:260])[0] ecdhe = pkt.data[260:292] ci = struct.unpack(">I", pkt.data[292:296])[0] aes_key = AESGCM(aes_key_text) decrypted_block = bytes(aes_key.decrypt(bytes(nonce), pkt.data[296:], '')) ip_a = decrypted_block[:16] pkt.data = decrypted_block[16:] pkt.plen = len(pkt.data) pkt.dst = ip_a sockfd.sendto(bytes(pkt), (socket.inet_ntop(socket.AF_INET6, ip_a), 0)) packet.drop()
def decrypt_message(msg): seq_no, op, o_id = unpack('!HBB', msg[0:BASE_HDR_LEN]) if op == OP_ADD_OVERLAY: inputVal = unpack( 'c' * BUFFER_LEN, msg[ADD_OVERLAY_HDR_LEN:ADD_OVERLAY_HDR_LEN + BUFFER_LEN]) aad = msg[:ADD_OVERLAY_HDR_LEN] ct = msg[ADD_OVERLAY_HDR_LEN + BUFFER_LEN:-IV_LEN] nonce = msg[-IV_LEN:] aesgcm = AESGCM(binascii.unhexlify(secret_key)) try: plaintext = aesgcm.decrypt(nonce, ct, None) buf = buffer(aad + bytearray(inputVal) + bytearray(plaintext)) logging.debug( 'Received packet: {:5}, decryption passed'.format(seq_no)) display_times.write('bm dec: {},%d\n'.format("".join(inputVal)) % (int(time.time() * 1000))) except: buf = None logging.debug( 'Received packet: {:5}, decryption failed'.format(seq_no)) GPIO.output(18, True) else: try: GPIO.output(18, False) except: print("caught gpio exception") buf = None return buf
def decrypt_record(record, key): # Combine the authenticated fields into an identical ad object as in the encryption function ad = '{0}\x1f{1}\x1f{2}\x1f{3}\x1f{4}'.format(record['ID'], record['Surname'], record['FirstName'], record['JoinDate'], record['LastLogin']) # Create an aead cipher and decrypt the ciphertext into the plaintext # Hints: You'll need to use the record["Nonce"] and record["Data"] fields # You'll also need to undo the string concatenation with a delimiter using .split('\x1f') for your delimiter aesgcm = AESGCM(key) plaintext = aesgcm.decrypt(record["Nonce"], record["Data"], ad).split('\x1f') # Re-populate the record with the decrypted fields, and set data / nonce back to None record.update({ "Address": plaintext[0], "Nationality": plaintext[1], "DOB": plaintext[2], "SSN": plaintext[3], "Phone": plaintext[4], "Data": None, "Nonce": None, })
def decrypt(data: bytes, password: bytes) -> bytes: aesgcm = AESGCM(password) nonce = data[0:12] ct = aesgcm.decrypt(nonce, data[12::], None) return ct
def decrypt(self): """Decrypt the private key.""" with open(self.filename, "rb") as f: joint_cipher_text = f.read().decode() # Turn bytes to str. salt, nonce, cipher_text = map(base64.b64decode, joint_cipher_text.split(".")) kdf = PBKDF2HMAC( algorithm=hashes.SHA512(), length=32, salt=salt, iterations=10000, backend=default_backend() ) key = kdf.derive(self.password) aesgcm = AESGCM(key) plain_text = aesgcm.decrypt( nonce=nonce, data=cipher_text, associated_data=None ) dec_filename = self.filename[:-4] + ".dec" with open(dec_filename, "wb") as df: df.write(plain_text) print("\033[1;32;40m[+] Decrypt Success! \033[0m \n[*] THe decrypted file stored as %s"%dec_filename) return None
def decryptFile(self): with open(self.file_path, 'rb') as file: cryptogram = file.read() if "AES" in self.algorithms: algorithm_name = algorithms.AES(self.key) if "CBC" in self.algorithms: cipher = Cipher(algorithm_name, modes.CBC(self.iv), backend=default_backend()) decryptor = cipher.decryptor() end = decryptor.update(cryptogram) + decryptor.finalize() p = end[-1] if len(end) < p: raise (Exception("Invalid padding. Larger than text")) if not 0 < p <= algorithm_name.block_size / 8: raise (Exception("Invalid padding. Larger than block size")) pa = -1 * p end = end[:pa] elif "GCM" in self.algorithms: aad = str.encode(''.join(self.algorithms)) aesgcm = AESGCM(self.key) end=aesgcm.decrypt(self.iv, cryptogram, aad) else: raise (Exception("Invalid mode")) elif "Salsa20" in self.algorithms: end = XSalsa20_xor(cryptogram,self.iv,self.key) else: raise (Exception("Invalid algorithm")) with open(self.file_name_decrypt,'w') as file: file.write(end.decode())
def decrypt_record(record, key): # Combine the authenticated fields into an identical ad object as in the encryption function ad = '\x1f'.join([ v for k, v in record.items() if k in ["ID", "Surname", "FirstName", "JoinDate", "Lastlogin"] ]).encode("UTF-8") # Create an aead cipher and decrypt the ciphertext into the plaintext # Hints: You'll need to use the record["Nonce"] and record["Data"] fields # You'll need to decode the bytes into a string using plaintext.decode("UTF-8") # You'll also need to undo the string concatenation with a delimiter using .split('\x1f') for your delimiter aesgcm = AESGCM(key) plaintext = aesgcm.decrypt(record["Nonce"], record["Data"], ad).decode("UTF-8").split('\x1f') # Re-populate the record with the decrypted fields, and set data / nonce back to None record.update({ "Address": plaintext[0], "Nationality": plaintext[1], "DOB": plaintext[2], "SSN": plaintext[3], "Phone": plaintext[4], "Data": None, "Nonce": None, })
def inviter_image(api_event): """Decrypt and respond with invite image""" # Get params from URL try: params = api_event['queryStringParameters'] user = params['user'] copy_id = params['copy'] secret = params['k'] except KeyError: raise Abort() # Incorrect params given # Retrieve and decrypt the image bucket_key = f'messages/{user}/invite_images/{copy_id}' try: obj = S3.get_object(Bucket=MSGS_BUCKET, Key=bucket_key) except: body = EXPIRED_IMAGE else: encrypted = obj['Body'].read() decryptor = AESGCM(_url64_to_bytes(secret)) decrypted = decryptor.decrypt(encrypted[:SYM_IV_BYTES], encrypted[SYM_IV_BYTES:], None) body = base64.b64encode(decrypted).decode() # Serve image return { 'statusCode': 200, 'headers': { 'content-type': 'image/jpeg', 'cache-control': 'no-store', }, 'isBase64Encoded': True, 'body': body, }
def modify(packet): pkt = dpkt.ip6.IP6(packet.get_payload()) if is_icmp_neighbour_message(pkt): packet.accept() return global client_id aes_key_text = pkt.data[:256] aes_key_text = asymmetrickeys.decrypt(aes_key_text) nonce = struct.unpack(">I", pkt.data[256:260])[0] public_ecdhe_key = pkt.data[260:292] ci = struct.unpack(">I", pkt.data[292:296])[0] aes_key = AESGCM(aes_key_text) decrypted_block = bytes( aes_key.decrypt(bytes(nonce), pkt.data[296:-288], '')) ip_b = decrypted_block[:16] # --- Header 2 header_2 = pkt.data[-288:] ecdhe = X25519PrivateKey.generate() shared_key = ecdhe.exchange( X25519PublicKey.from_public_bytes(public_ecdhe_key)) derived_key = HKDF(algorithm=hashes.SHA512(), length=32, info=None, salt=None, backend=default_backend()).derive(shared_key) key = AESGCM(derived_key) nonce = random.randint(0, 4294967295) encrypted_header = key.encrypt(bytes(nonce), header_2, '') signature = sign(ecdhe.public_key().public_bytes(), asymmetrickeys) header_2 = ecdhe.public_key().public_bytes() + signature + struct.pack( ">I", nonce) + encrypted_header + struct.pack(">I", client_id) client_id = client_id + 1 # Finalize packet pkt.data = decrypted_block[16:] + header_2 pkt.plen = len(pkt.data) pkt.dst = ip_b sockfd.sendto(bytes(pkt), (socket.inet_ntop(socket.AF_INET6, ip_b), 0)) packet.drop()
def get_cookies(cookies_db_path, host_key, aes_gcm_key): """Get the cookies for the specified host_key from Chrome Cookies sqlite database.""" cookies = [] with tempfile.TemporaryDirectory(prefix="twitchget_") as temp_dir: # Copy the cookies database to avoid hitting a lock and open cookies_db_copy_path = shutil.copy(cookies_db_path, temp_dir) db = sqlite3.connect(cookies_db_copy_path) query = "SELECT name, path, expires_utc, is_secure, encrypted_value "\ "FROM cookies WHERE host_key=?" cursor = db.cursor() cursor.execute(query, (host_key, )) for result in cursor.fetchall(): name, path, expiry, secure, ev = result # Skip cookies that are blacklisted by name or session-only if name in COOKIES_BLACKLIST or expiry == 0: continue # Decrypt the cookie value if ev.startswith(b"v10"): nonce, cipertext = ev[3:15], ev[15:] aes_gcm = AESGCM(aes_gcm_key) dv = aes_gcm.decrypt(nonce, cipertext, None).decode("utf-8") else: dv = win32crypt.CryptUnprotectData(ev, None, None, None, 0)[1].decode("utf-8") cookies.append((name, path, expiry, secure, dv)) # Close the database cleanly db.close() return cookies
def decrypt_token(token, key, ttl): # decode key _key = base64.urlsafe_b64decode(key) # base64url decode token decoded = base64.urlsafe_b64decode(token) # check token length if len(decoded) < _min_token_size: raise Exception("Invalid Token") # separate token ts_bytes = decoded[_ts_offset:_ts_offset + _ts_size] nonce = decoded[_nonce_offset:_nonce_offset + _nonce_size] ciphertext = decoded[_cipher_offset:] # verify and decrypt aesgcm = AESGCM(_key) plaintext = aesgcm.decrypt(nonce, ciphertext, ts_bytes) # check timestamp timestamp = int.from_bytes(ts_bytes, byteorder="big", signed=False) if ttl != 0 and time.time_ns() - timestamp > ttl: raise Exception("Expired Token") return plaintext.decode("utf-8")
def decrypt(self, ciphertext): ciphertext = base64.b64decode(ciphertext) nonce = ciphertext[:16] ciphertext = ciphertext[16:] aesgcm = AESGCM(self.key) plaintext = aesgcm.decrypt(nonce, ciphertext, None) return plaintext.decode('utf-8')
def AES_GCM(data, aad): key = AESGCM.generate_key(bit_length=128) aesgcm = AESGCM(key) nonce = os.urandom(12) ct = aesgcm.encrypt(nonce, data, aad) pt = aesgcm.decrypt(nonce, ct, aad) return ct, pt
def modify(packet): pkt = dpkt.ip6.IP6(packet.get_payload()) if is_icmp_neighbour_message(pkt): packet.accept() return aes_key_text = pkt.data[:256] aes_key_text = asymmetrickeya.decrypt(aes_key_text) nonce = struct.unpack(">I", pkt.data[256:260])[0] ecdhe = pkt.data[260:292] ci = struct.unpack(">I", pkt.data[292:296])[0] aes_key = AESGCM(aes_key_text) decrypted_block = bytes(aes_key.decrypt(bytes(nonce), pkt.data[296:], '')) ip_s = decrypted_block[:16] ecdhe_ac = X25519PrivateKey.generate() signature = sign(ecdhe_ac.public_key().public_bytes(), asymmetrickeya) pkt.data = decrypted_block[16:] + ecdhe_ac.public_key().public_bytes( ) + signature pkt.plen = len(pkt.data) pkt.dst = ip_s sockfd.sendto(bytes(pkt), (socket.inet_ntop(socket.AF_INET6, ip_s), 0)) packet.drop()
def test_vectors(self, vector): key = binascii.unhexlify(vector["key"]) nonce = binascii.unhexlify(vector["iv"]) aad = binascii.unhexlify(vector["aad"]) ct = binascii.unhexlify(vector["ct"]) pt = binascii.unhexlify(vector.get("pt", b"")) tag = binascii.unhexlify(vector["tag"]) aesgcm = AESGCM(key) if vector.get("fail") is True: with pytest.raises(InvalidTag): aesgcm.decrypt(nonce, ct + tag, aad) else: computed_ct = aesgcm.encrypt(nonce, pt, aad) assert computed_ct[:-16] == ct assert computed_ct[-16:] == tag computed_pt = aesgcm.decrypt(nonce, ct + tag, aad) assert computed_pt == pt
def test_aes_gcm_aead_api(backend, wycheproof): key = binascii.unhexlify(wycheproof.testcase["key"]) iv = binascii.unhexlify(wycheproof.testcase["iv"]) aad = binascii.unhexlify(wycheproof.testcase["aad"]) msg = binascii.unhexlify(wycheproof.testcase["msg"]) ct = binascii.unhexlify(wycheproof.testcase["ct"]) tag = binascii.unhexlify(wycheproof.testcase["tag"]) aesgcm = AESGCM(key) if wycheproof.valid or wycheproof.acceptable: computed_ct = aesgcm.encrypt(iv, msg, aad) assert computed_ct == ct + tag computed_msg = aesgcm.decrypt(iv, ct + tag, aad) assert computed_msg == msg elif len(iv) == 0: with pytest.raises(ValueError): aesgcm.encrypt(iv, msg, aad) else: with pytest.raises(InvalidTag): aesgcm.decrypt(iv, ct + tag, aad)
def decrypt_message(data_packet, hex_key, node_id): retval = None log.debug("decrypting for node " + node_id) log.debug("aesgcm:eMFEP2:data_packet:pp (len) (" + str(len(data_packet)) + ") ") log.debug(prettyprint(data_packet)) # key is from the csv file, 128 bits # aad is additional data, from (length, type, seqlen, 4xID bytes, bodyLength) # iv is initialisation vector, from # ciphertext is from packet # tag is from # data_packet is a handful of byte if data_packet[len(data_packet) - 1] == 0x80: log.debug("aesgcm encryption used") # packet contains the entire packet, except for the leading length byte # indices are reference as per normal Python from 0 - hence the frame type (cf) is at index 0 log.debug("initialisation vector...") iv = initialisation_vector(data_packet, node_id) log.debug("cipher text...") ct = cipher_text(data_packet) log.debug("tag...") tg = tag(data_packet) log.debug("additional data...") ad = additional_data(data_packet) key = hex_string_to_bytes(hex_key) log.debug("preparation complete") debug_array = [iv, ct, tg, ad, key] log.debug("len | pp:iv,ct,tg,ad,key") [log.debug("{:>2} | {}".format(repr(len(x)), prettyprint(x))) for x in debug_array] log.debug("attempting decryption...") try: buf = ct + tg # aesgcm.decrypt takes a buffer with the tag appended to the ciphertext. aesgcm = AESGCM(key) # (DE20170807) Shiny new interface in cryptography v2.x retval = aesgcm.decrypt(iv, buf, ad) log.debug("decrypted") except Exception as e: log.error('decryption failed with exception: {}: {}'.format(e.__class__.__name__, e)) return retval
def decrypt_opaque(opaque, nonce, tag, hash_mask, auth_headers, extra_auth_headers): aesgcm = AESGCM(SECRET_KEY) auth_data = '|'.join((hash_mask, auth_headers, extra_auth_headers)) try: plaintext = aesgcm.decrypt(nonce, opaque + tag, auth_data) except InvalidTag: raise OpaqueInvalid( "Opaque token from the client failed to authenticate") try: sessionid, remainder = plaintext.split('|', 1) hmac_key, expiration_time = (remainder[:16], remainder[17:]) except ValueError: raise OpaqueInvalid( "Plaintext from opaque token didn't have required fields") return sessionid, hmac_key, int(expiration_time)
def dec(self, byts): ''' Decode an envelope dict and decrypt the given bytes. Args: byts (bytes): Bytes to decrypt. Returns: bytes: Decrypted message. ''' envl = s_msgpack.un(byts) iv = envl.get('iv', b'') asscd = envl.get('asscd', b'') data = envl.get('data', b'') decryptor = AESGCM(self.ekey) try: data = decryptor.decrypt(iv, data, asscd) except Exception: logger.exception('Error decrypting data') return None return data