def decrypt_str(self, content, key, salt): # content contains the gcm tag and salt_explicit in plaintext if len(content) < 24: raise CryptoException("truncated content") salt_explicit, gcm_tag = struct.unpack_from('!q16s', content) cipher = Cipher(algorithms.AES(key), modes.GCM(initialization_vector=self._bulid_iv( salt, salt_explicit), tag=gcm_tag), backend=default_backend()).decryptor() return cipher.update(content[24:]) + cipher.finalize()
def test_aes_gcm(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.") if wycheproof.valid or wycheproof.acceptable: enc = Cipher(algorithms.AES(key), modes.GCM(iv), backend).encryptor() enc.authenticate_additional_data(aad) computed_ct = enc.update(msg) + enc.finalize() computed_tag = enc.tag assert computed_ct == ct assert computed_tag == tag dec = Cipher( algorithms.AES(key), modes.GCM(iv, tag, min_tag_length=len(tag)), backend, ).decryptor() dec.authenticate_additional_data(aad) computed_msg = dec.update(ct) + dec.finalize() assert computed_msg == msg else: dec = Cipher( algorithms.AES(key), modes.GCM(iv, tag, min_tag_length=len(tag)), backend, ).decryptor() dec.authenticate_additional_data(aad) dec.update(ct) with pytest.raises(InvalidTag): dec.finalize()
def decrypt(self, value, associated_data: bytes = b'', stash=None): val_re = b'^ENC\[AES256_GCM,data:(.+),iv:(.+),tag:(.+),type:(.+)\]' res = re.match(val_re, value.encode('utf-8')) if res is None: return value ciphertext = b64decode(res.group(1)) iv = b64decode(res.group(2)) tag = b64decode(res.group(3)) valtype = res.group(4) # Construct a Cipher object, with the key, iv, and additionally the # GCM tag used for authenticating the message. decryptor = Cipher( algorithms.AES(self.key), modes.GCM(iv, tag), ).decryptor() # We put associated_data back in or the tag will fail to verify # when we finalize the decryptor. decryptor.authenticate_additional_data(associated_data) # Decryption gets us the authenticated plaintext. # If the tag does not match an InvalidTag exception will be raised. cleartext = decryptor.update(ciphertext) + decryptor.finalize() if stash: # save the values for later if we need to reencrypt stash['iv'] = iv stash['associated_data'] = associated_data stash['cleartext'] = cleartext if valtype == b'bytes': return cleartext if valtype == b'str': cv = cleartext try: cv = cleartext.decode('utf-8') except UnicodeDecodeError: return cleartext return cv if valtype == b'int': return int(cleartext.decode('utf-8')) if valtype == b'float': return float(cleartext.decode('utf-8')) if valtype == b'bool': if cleartext.lower() == b'true': return True return False return cleartext
def aes_decrypt(attr_ct, aes_key): """ Convenience method to decrypt attribute properties :param attr_ct: Dictionary (may be a Flattened JWE) with base64-encoded ciphertext and base64-encoded iv :param aes_key: symmetric key to decrypt attribute value with :return: plaintext bytes """ if not isinstance(attr_ct, dict) or ( attr_ct.get('cipher', 'aes') != 'aes' or attr_ct.get('mode', 'gcm') != 'gcm' or 'iv' not in attr_ct or ('header' in attr_ct and (attr_ct['header'].get('alg', 'dir') != 'dir' or attr_ct['header'].get('env', 'A256GCM') != 'A256GCM'))): raise ValueError('invalid encrypted attribute') iv = None ciphertext = None if 'ciphertext' in attr_ct: # JWE included, prefer that ciphertext = utils.base64url_decode(attr_ct.get('ciphertext')) tag = utils.base64url_decode(attr_ct.get('tag')) if len(tag) != 16: # 128 // 8 raise ValueError('invalid tag size: {}'.format(len(tag))) if 'cipher' in attr_ct: # hybrid mode, iv is in legacy format iv = base64.b64decode(attr_ct['iv']) else: iv = utils.base64url_decode(attr_ct['iv']) else: # legacy only ts = attr_ct.get('ts', 128) if ts != 128: raise ValueError('invalid tag size: {}'.format(ts)) iv = base64.b64decode(attr_ct['iv']) tag_ct = base64.b64decode(attr_ct['ct']) sp = ts // 8 ciphertext = tag_ct[:-sp] tag = tag_ct[-sp:] cipher_alg = Cipher(algorithms.AES(aes_key), modes.GCM(iv, tag, min_tag_length=8), backend=_BACKEND) decryptor = cipher_alg.decryptor() return decryptor.update(ciphertext) + decryptor.finalize()
def decrypt(self, ciphertext): if not ciphertext: return ciphertext tag, ciphertext_encoded = ciphertext.split('$', 1) tag = base64.b64decode(tag) ciphertext_encoded = base64.b64decode(ciphertext_encoded) decryptor = Cipher(algorithms.AES(self.key), modes.GCM(self.iv, tag), backend=default_backend()).decryptor() return (decryptor.update(ciphertext_encoded) + decryptor.finalize()).decode()
def AESDecryption(key, associatedData, iv, tag, ct): cipher = Cipher(algorithms.AES(key), modes.GCM(iv, tag), backend=default_backend()) decryptor = cipher.decryptor() decryptor.authenticate_additional_data(associatedData) pt = decryptor.update(ct) + decryptor.finalize() return pt
def AESEncryption(key, associatedData, iv, pt): cipher = Cipher(algorithms.AES(key), modes.GCM(iv), backend=default_backend()) encryptor = cipher.encryptor() encryptor.authenticate_additional_data(associatedData) ct = encryptor.update(pt) + encryptor.finalize() return ct, encryptor.tag
def encrypt(key: bytes, plaintext: bytes, associated_data: bytes) -> Tuple[bytes, bytes, bytes]: iv = os.urandom(12) encryptor = Cipher(algorithms.AES(key), modes.GCM(iv), backend=default_backend()).encryptor() encryptor.authenticate_additional_data(associated_data) ciphertext = encryptor.update(plaintext) + encryptor.finalize() return iv, ciphertext, encryptor.tag
def encrypt(key, plaintext, additional_authenticated_data): iv = os.urandom(16) encryptor = Cipher(algorithms.AES(key), modes.GCM(iv), backend=default_backend()).encryptor( ) # AES_GCM mode with 256 bit symmetric key encryptor.authenticate_additional_data( additional_authenticated_data ) # Authenticaed data in our case its hash(plain_message) # sign hash of message with private key m = plaintext ciphertext = encryptor.update(m) + encryptor.finalize() return (iv, ciphertext, encryptor.tag)
def aes_decrypt(encrypted_txt): with open(os.path.join(os.environ['LOCALAPPDATA'], r"Google\Chrome\User Data\Local State"), encoding='utf-8', mode="r") as f: jsn = json.loads(str(f.readline())) encoded_key = jsn["os_crypt"]["encrypted_key"] encrypted_key = base64.b64decode(encoded_key.encode()) encrypted_key = encrypted_key[5:] key = dpapi_decrypt(encrypted_key) nonce = encrypted_txt[3:15] cipher = Cipher(algorithms.AES(key), None, backend=default_backend()) cipher.mode = modes.GCM(nonce) decryptor = cipher.decryptor() return decryptor.update(encrypted_txt[15:])
def __init__( self, plaintext: io.BytesIO, key: bytes, signature: bytes, chunk_size: int = 64 * 1024, ): self.iv = os.urandom(12) self.file = plaintext self.chunk_size = chunk_size self.encryptor = Cipher(algorithms.AES(key), modes.GCM(self.iv)).encryptor() self.encryptor.authenticate_additional_data(signature)
def encrypt_code(code): files = open("/dev/random", 'rb') key = files.read(32) iv = files.read(32) files.close() encrypts = Cipher(algorithms.AES(key), modes.GCM(iv), backend=default_backend()).encryptor() res = encrypts.update(code) print('pwd: ', convert_to_base64(res)) print('key: ', convert_to_base64(key)) print('iv: ', convert_to_base64(iv))
def encrypt(plaintext, e_key=None): if not e_key: e_key = os.urandom(32) iv = os.urandom(IV_SIZE) encryptor = Cipher( algorithms.AES(e_key), modes.GCM(iv), backend=BACKEND ).encryptor() ct = encryptor.update(plaintext) + encryptor.finalize() ct_hmac = HMACUtils.get_hmac(e_key, ct) return (ct+iv+encryptor.tag+ct_hmac, e_key)
def encrypt(self, plain_text): # Generate a random 96-bit IV. iv = os.urandom(self.nonce_length) # Construct an AES-GCM Cipher object with the given key and a # randomly generated IV. encryptor = Cipher(algorithms.AES(self.key), modes.GCM(iv)).encryptor() # Encrypt the plaintext and get the associated ciphertext. # GCM does not require padding. ciphertext = encryptor.update(plain_text) + encryptor.finalize() return iv + encryptor.tag + ciphertext
def test_gcm_ciphertext_limit(self, backend): encryptor = base.Cipher( algorithms.AES(b"\x00" * 16), modes.GCM(b"\x01" * 16), backend=backend, ).encryptor() new_max = modes.GCM._MAX_ENCRYPTED_BYTES - 16 encryptor._bytes_processed = new_max # type: ignore[attr-defined] encryptor.update(b"0" * 16) max = modes.GCM._MAX_ENCRYPTED_BYTES assert encryptor._bytes_processed == max # type: ignore[attr-defined] with pytest.raises(ValueError): encryptor.update(b"0")
def encrypt_bytes(plain_data: bytes, plain_file_key: PlainFileKey) -> Tuple[bytes, PlainFileKey]: if not bytes: raise ValueError('No data to process.') key = base64.b64decode(plain_file_key["key"]) iv = base64.b64decode(plain_file_key["iv"]) encryptor = Cipher(algorithm=algorithms.AES(key), mode=modes.GCM(iv)).encryptor() enc_bytes = encryptor.update(plain_data) + encryptor.finalize() plain_file_key["tag"] = base64.b64encode(encryptor.tag).decode('ascii') return (enc_bytes, plain_file_key)
def _lb_pack(key, data): orig_size = len(data) nonce = os.urandom(12) cipher = Cipher(algorithms.AES(key), modes.GCM(nonce), default_backend()) encryptor = cipher.encryptor() encryptor.authenticate_additional_data(_lb_ad(orig_size)) ciphertext = encryptor.update(zlib.compress(data)) + encryptor.finalize() return { 1: ciphertext + encryptor.tag, 2: nonce, 3: orig_size, }
def test_gcm_tag_with_only_aad(self, backend): key = binascii.unhexlify(b"5211242698bed4774a090620a6ca56f3") iv = binascii.unhexlify(b"b1e1349120b6e832ef976f5d") aad = binascii.unhexlify(b"b6d729aab8e6416d7002b9faa794c410d8d2f193") tag = binascii.unhexlify(b"0f247e7f9c2505de374006738018493b") cipher = base.Cipher(algorithms.AES(key), modes.GCM(iv), backend=backend) encryptor = cipher.encryptor() encryptor.authenticate_additional_data(aad) encryptor.finalize() assert encryptor.tag == tag
def decrypted_code(code, key, iv): """decrypt code in AES.GCM""" if code is None or code == '': return '' code = convert_to_bytes(code) key = convert_to_bytes(key) iv = convert_to_bytes(iv) decrypts = Cipher(algorithms.AES(key), modes.GCM(iv), backend=default_backend()).decryptor() res = decrypts.update(code) return res.decode('utf-8')
def test_gcm_ciphertext_limit(self, backend): encryptor = base.Cipher( algorithms.AES(b"\x00" * 16), modes.GCM(b"\x01" * 16), backend=backend ).encryptor() encryptor._bytes_processed = modes.GCM._MAX_ENCRYPTED_BYTES - 16 encryptor.update(b"0" * 16) assert ( encryptor._bytes_processed == modes.GCM._MAX_ENCRYPTED_BYTES ) with pytest.raises(ValueError): encryptor.update(b"0")
def Myencrypt(plaintext, key): iv_length = 16 iv = os.urandom(iv_length) encryptor = Cipher( algorithms.AES(key), modes.GCM(iv), backend=default_backend() ).encryptor() ciphertext = encryptor.update(plaintext) + encryptor.finalize() return (iv, ciphertext, encryptor.tag)
def decrypt(key, associated_data, iv, ciphertext, tag): # Construct a Cipher object, with the key, iv, and additionally the # GCM tag used for authenticating the message. decryptor = Cipher(algorithms.AES(key), modes.GCM(iv, tag), backend=default_backend()).decryptor() # We put associated_data back in or the tag will fail to verify # when we finalize the decryptor. decryptor.authenticate_additional_data(associated_data) # Decryption gets us the authenticated plaintext. # If the tag does not match an InvalidTag exception will be raised. return decryptor.update(ciphertext) + decryptor.finalize()
def decryptDataWithAES(data, symmKey): try: parts = data.split('<<>>') iv, cipherText, encryptorTag = parts[0], parts[1], parts[ 2] #, parts[3] decryptor = Cipher(algorithms.AES(symmKey), modes.GCM(iv, encryptorTag), backend=default_backend()).decryptor() #decryptor.authenticate_additional_data(authString) return decryptor.update(cipherText) + decryptor.finalize() except Exception as e: print "Error in Decrypting the data!!" cleanup()
def encrypt( security_control: SecurityControlField, system_title: bytes, invocation_counter: int, key: bytes, plain_text: bytes, auth_key: bytes, ) -> bytes: """ Encrypts bytes according the to security context. """ if not security_control.encrypted and not security_control.authenticated: raise NotImplementedError( "encrypt() only handles authenticated encryption") if len(system_title) != 8: raise ValueError( f"System Title must be of lenght 8, not {len(system_title)}") # initialization vector is 12 bytes long and consists of the system_title (8 bytes) # and invocation_counter (4 bytes) iv = system_title + invocation_counter.to_bytes(4, "big") # Making sure the keys are of correct length for specified security suite validate_key(security_control.security_suite, key) validate_key(security_control.security_suite, auth_key) # Construct an AES-GCM Cipher object with the given key and iv. Allow for # truncating the auth tag encryptor = Cipher( algorithms.AES(key), modes.GCM(initialization_vector=iv, tag=None, min_tag_length=TAG_LENGTH), ).encryptor() # associated_data will be authenticated but not encrypted, # it must also be passed in on decryption. associated_data = security_control.to_bytes() + auth_key encryptor.authenticate_additional_data(associated_data) # Encrypt the plaintext and get the associated ciphertext. # GCM does not require padding. ciphertext = encryptor.update(plain_text) + encryptor.finalize() # dlms uses a tag lenght of 12 not the default of 16. Since we have set the minimum # tag length to 12 it is ok to truncated the tag down to 12 bytes. tag = encryptor.tag[:TAG_LENGTH] return ciphertext + tag
def encrypt(): # Generate a random 96-bit IV. key = os.urandom(256) iv = os.urandom(12) f = open("f1.txt", 'rb') output = open("f2.txt", 'wb') decrypted = open("f3.txt", 'wb') plaintext = f.read() # Construct an AES-GCM Cipher object with the given key and a # randomly generated IV. encryptor = Cipher(algorithms.AES(key), modes.GCM(iv), backend=default_backend()).encryptor() # associated_data will be authenticated but not encrypted, # it must also be passed in on decryption. # Encrypt the plaintext and get the associated ciphertext. # GCM does not require padding. ciphertext = encryptor.update(plaintext) + encryptor.finalize() output.write(ciphertext) tag = encryptor.tag decryptor = Cipher(algorithms.AES(key), modes.GCM(iv, tag), backend=default_backend()).decryptor() text = decryptor.update(ciphertext) + decryptor.finalize() decrypted.write(text) f.close() output.close() decrypted.close()
def test_gcm_ciphertext_with_no_aad(self, backend): key = binascii.unhexlify(b"e98b72a9881a84ca6b76e0f43e68647a") iv = binascii.unhexlify(b"8b23299fde174053f3d652ba") ct = binascii.unhexlify(b"5a3c1cf1985dbb8bed818036fdd5ab42") tag = binascii.unhexlify(b"23c7ab0f952b7091cd324835043b5eb5") pt = binascii.unhexlify(b"28286a321293253c3e0aa2704a278032") cipher = base.Cipher(algorithms.AES(key), modes.GCM(iv), backend=backend) encryptor = cipher.encryptor() computed_ct = encryptor.update(pt) + encryptor.finalize() assert computed_ct == ct assert encryptor.tag == tag
def decription(self, msg_text, salt, iv, tag): backend = default_backend() salt = salt kdf = HKDF(algorithm=hashes.SHA256(), length=16, salt=salt, info=b'TC1920-G4', backend=backend).derive(self.shared_key) cipher = Cipher(algorithms.AES(kdf), modes.GCM(iv, tag), default_backend()) decryptor = cipher.decryptor() msg = decryptor.update(msg_text) + decryptor.finalize() return msg
def aesDecrypt(data, key): iv = data[:12] tag = data[12:28] ciphertext = data[28:] # Construct a Cipher object, with the key, iv, and additionally the # GCM tag used for authenticating the message. decryptor = Cipher(algorithms.AES(key), modes.GCM(iv, tag), backend=default_backend()).decryptor() # Decryption gets us the authenticated plaintext. # If the tag does not match an InvalidTag exception will be raised. return decryptor.update(ciphertext) + decryptor.finalize()
def decrypt(ciphertext, key): m = hashlib.sha256() m.update(key.encode()) hashed_key = m.digest() auth_tag, iv, encrypted = [ bytes.fromhex(hex) for hex in ciphertext.split(':') ] decryptor = Cipher(algorithms.AES(hashed_key), modes.GCM(iv, auth_tag), backend=default_backend()).decryptor() return (decryptor.update(encrypted) + decryptor.finalize()).decode()
def encrypt(plaintext, key): """ Encrypt object """ if plaintext is None: plaintext = b'' iv = generate_random_key(aes_block_size) encryptor = Cipher(algorithms.AES(key), modes.GCM( iv), backend=default_backend()).encryptor() # The following try/except captures both str and bytes try: cipher_text = encryptor.update( plaintext.encode('ascii')) + encryptor.finalize() except Exception: cipher_text = encryptor.update(plaintext) + encryptor.finalize() return base64.b64encode(iv + cipher_text + encryptor.tag)