Python Crypto.Cipher.AES.MODE_GCM Examples

The following are 30 code examples of Crypto.Cipher.AES.MODE_GCM(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module Crypto.Cipher.AES , or try the search function .
Example #1
Source File: packet.py    From NintendoClients with MIT License 10 votes vote down vote up
def decrypt(self, data):
		key = self.session.get_session_key()
		
		method = self.settings.get("pia.encryption_method")
		if method == EncryptionMethod.AES_ECB:
			aes = AES.new(key, AES.MODE_ECB)
			return aes.decrypt(data)
		else:
			nonce = self.session.generate_nonce(self)
			aes = AES.new(key, AES.MODE_GCM, nonce=nonce)
			try:
				data = aes.decrypt_and_verify(data, self.signature)
			except ValueError:
				logger.warning("Received incorrect AES-GCM tag")
				return None
			return data 
Example #2
Source File: test_GCM.py    From FODI with GNU General Public License v3.0 7 votes vote down vote up
def test_2(self):
        key = unhexlify("843ffcf5d2b72694d19ed01d01249412")
        iv  = unhexlify("dbcca32ebf9b804617c3aa9e")
        aad = unhexlify("00000000000000000000000000000000" +
                        "101112131415161718191a1b1c1d1e1f")
        pt  = unhexlify("000102030405060708090a0b0c0d0e0f" +
                        "101112131415161718191a1b1c1d1e1f" +
                        "202122232425262728292a2b2c2d2e2f" +
                        "303132333435363738393a3b3c3d3e3f" +
                        "404142434445464748494a4b4c4d4e4f")
        ct  = unhexlify("6268c6fa2a80b2d137467f092f657ac0" +
                        "4d89be2beaa623d61b5a868c8f03ff95" +
                        "d3dcee23ad2f1ab3a6c80eaf4b140eb0" +
                        "5de3457f0fbc111a6b43d0763aa422a3" +
                        "013cf1dc37fe417d1fbfc449b75d4cc5")
        digest = unhexlify("3b629ccfbc1119b7319e1dce2cd6fd6d")

        cipher = AES.new(key, AES.MODE_GCM, iv).update(aad)
        ct2, digest2 = cipher.encrypt_and_digest(pt)

        self.assertEqual(ct, ct2)
        self.assertEqual(digest, digest2) 
Example #3
Source File: andotp_decrypt.py    From andOTP-decrypt with MIT License 7 votes vote down vote up
def decode(key, data, debug=False):
    """Decode function used for both the old and new style encryption"""
    # Raw data structure is IV[:12] + crypttext[12:-16] + auth_tag[-16:]
    iv = data[:12]
    crypttext = data[12:-16]
    tag = data[-16:]
    if debug:
        print("Input bytes: %", bytes2Hex(data))
        print("IV: %s" % bytes2Hex(iv))
        print("Crypttext: %s" % bytes2Hex(crypttext))
        print("Auth tag: %s" % bytes2Hex(tag))

    aes = AES.new(key, AES.MODE_GCM, nonce=iv)
    try:
        dec = aes.decrypt_and_verify(crypttext, tag)
        if debug:
            print("Decrypted data: %s" % bytes2Hex(dec))
        return dec.decode('UTF-8')
    except ValueError as e:
        print(e)
        print("The passphrase was probably wrong")
        return None 
Example #4
Source File: itemv7.py    From iChainbreaker with GNU General Public License v2.0 7 votes vote down vote up
def decrypt_secret_data(self, class_key):
        key = AESUnwrap(class_key, self.encrypted_secret_data_wrapped_key)
        if not key:
            raise ValueError("Failed to unwrap key. Bad class key?")

        plist = readPlistFromString(self.protobuf_item.encryptedSecretData.ciphertext)
        authenticated = ns_keyed_unarchiver(plist)
        #decrypted = gcm_decrypt(key,
        #                        authenticated['SFInitializationVector'],
        #                        authenticated['SFCiphertext'], '',
        #                        authenticated['SFAuthenticationCode'])
        
        gcm = AES.new(key, AES.MODE_GCM, authenticated['SFInitializationVector'])
        decrypted = gcm.decrypt_and_verify(authenticated['SFCiphertext'], authenticated['SFAuthenticationCode'])

        if not decrypted:
            raise ValueError("Failed to decrypt")

        return decrypted 
Example #5
Source File: test_GCM.py    From android_universal with MIT License 6 votes vote down vote up
def test_output_param_neg(self):

        pt = b'5' * 16
        cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
        ct = cipher.encrypt(pt)

        cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
        self.assertRaises(TypeError, cipher.encrypt, pt, output=b'0'*16)
        
        cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
        self.assertRaises(TypeError, cipher.decrypt, ct, output=b'0'*16)

        shorter_output = bytearray(15)
        cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
        self.assertRaises(ValueError, cipher.encrypt, pt, output=shorter_output)
        cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
        self.assertRaises(ValueError, cipher.decrypt, ct, output=shorter_output) 
Example #6
Source File: test_GCM.py    From FODI with GNU General Public License v3.0 6 votes vote down vote up
def test_encrypt(self, tv):
        self._id = "Wycheproof Encrypt GCM Test #" + str(tv.id)

        try:
            cipher = AES.new(tv.key, AES.MODE_GCM, tv.iv, mac_len=tv.tag_size,
                    **self._extra_params)
        except ValueError as e:
            if len(tv.iv) == 0 and "Nonce cannot be empty" in str(e):
                return
            raise e

        cipher.update(tv.aad)
        ct, tag = cipher.encrypt_and_digest(tv.msg)
        if tv.valid:
            self.assertEqual(ct, tv.ct)
            self.assertEqual(tag, tv.tag)
            self.warn(tv) 
Example #7
Source File: kobackupdec.py    From kobackupdec with MIT License 6 votes vote down vote up
def __decrypt_bkey_v4(self):
        key_salt = self._pwkey_salt[:16]
        logging.debug('KEY_SALT[%s] = %s', len(key_salt),
                      binascii.hexlify(key_salt))

        key = PBKDF2(self._upwd, key_salt, Decryptor.dklen, Decryptor.count,
                     Decryptor.prf)
        logging.debug('KEY[%s] = %s', len(key), binascii.hexlify(key))

        nonce = self._pwkey_salt[16:]
        logging.debug('KEY NONCE[%s] = %s', len(nonce),
                      binascii.hexlify(nonce))

        cipher = AES.new(key, mode=AES.MODE_GCM, nonce=nonce)
        self._bkey = cipher.decrypt(self._e_perbackupkey)[:32]
        logging.debug('BKEY[%s] =   %s',
                      len(self._bkey), binascii.hexlify(self._bkey)) 
Example #8
Source File: test_GCM.py    From android_universal with MIT License 6 votes vote down vote up
def test_mac_len(self):
        # Invalid MAC length
        self.assertRaises(ValueError, AES.new, self.key_128, AES.MODE_GCM,
                          nonce=self.nonce_96, mac_len=3)
        self.assertRaises(ValueError, AES.new, self.key_128, AES.MODE_GCM,
                          nonce=self.nonce_96, mac_len=16+1)

        # Valid MAC length
        for mac_len in range(5, 16 + 1):
            cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96,
                             mac_len=mac_len)
            _, mac = cipher.encrypt_and_digest(self.data_128)
            self.assertEqual(len(mac), mac_len)

        # Default MAC length
        cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
        _, mac = cipher.encrypt_and_digest(self.data_128)
        self.assertEqual(len(mac), 16) 
Example #9
Source File: gcm.py    From iChainbreaker with GNU General Public License v2.0 6 votes vote down vote up
def gcm_decrypt(k, iv, encrypted, auth_data, tag):
    aes = AES.new(k, AES.MODE_GCM)
    h = aes.encrypt(chr(0) * aes.block_size)

    if len(iv) == 12:
        y0 = iv + "\x00\x00\x00\x01"
    else:
        y0 = ghash(h, '', iv)

    decrypted = gctr(k, y0, encrypted)

    s = ghash(h, auth_data, encrypted)

    t = aes.encrypt(y0)
    T = strxor.strxor(s, t)
    if T != tag:
        return ''   # decrypted data is invalid
    else:
        return decrypted 
Example #10
Source File: test_GCM.py    From FODI with GNU General Public License v3.0 6 votes vote down vote up
def test_output_param_neg(self):

        pt = b'5' * 16
        cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
        ct = cipher.encrypt(pt)

        cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
        self.assertRaises(TypeError, cipher.encrypt, pt, output=b'0'*16)
        
        cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
        self.assertRaises(TypeError, cipher.decrypt, ct, output=b'0'*16)

        shorter_output = bytearray(15)
        cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
        self.assertRaises(ValueError, cipher.encrypt, pt, output=shorter_output)
        cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
        self.assertRaises(ValueError, cipher.decrypt, ct, output=shorter_output) 
Example #11
Source File: crypto.py    From calm-dsl with Apache License 2.0 6 votes vote down vote up
def encrypt_AES_GCM(msg, password, kdf_salt=None, nonce=None):
        """Used for encryption of msg"""

        kdf_salt = kdf_salt or os.urandom(16)
        nonce = nonce or os.urandom(16)

        # Encoding of message
        msg = msg.encode()
        secret_key = Crypto.generate_key(kdf_salt, password)
        aes_cipher = AES.new(secret_key, AES.MODE_GCM, nonce=nonce)
        ciphertext, auth_tag = aes_cipher.encrypt_and_digest(msg)

        return (kdf_salt, ciphertext, nonce, auth_tag) 
Example #12
Source File: test_GCM.py    From android_universal with MIT License 6 votes vote down vote up
def test_valid_multiple_encrypt_or_decrypt(self):
        for method_name in "encrypt", "decrypt":
            for auth_data in (None, b"333", self.data_128,
                              self.data_128 + b"3"):
                if auth_data is None:
                    assoc_len = None
                else:
                    assoc_len = len(auth_data)
                cipher = AES.new(self.key_128, AES.MODE_GCM,
                                 nonce=self.nonce_96)
                if auth_data is not None:
                    cipher.update(auth_data)
                method = getattr(cipher, method_name)
                method(self.data_128)
                method(self.data_128)
                method(self.data_128)
                method(self.data_128) 
Example #13
Source File: aes.py    From eventsourcing with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def decrypt(self, ciphertext: bytes) -> bytes:
        """Return plaintext for given ciphertext."""

        # Split out the nonce, tag, and encrypted data.
        nonce = ciphertext[:12]
        if len(nonce) != 12:
            raise DataIntegrityError("Cipher text is damaged: invalid nonce length")

        tag = ciphertext[12:28]
        if len(tag) != 16:
            raise DataIntegrityError("Cipher text is damaged: invalid tag length")

        encrypted = ciphertext[28:]

        # Construct AES cipher, with old nonce.
        cipher = AES.new(self.cipher_key, AES.MODE_GCM, nonce)

        # Decrypt and verify.
        try:
            plaintext = cipher.decrypt_and_verify(encrypted, tag)  # type: ignore
        except ValueError as e:
            raise DataIntegrityError("Cipher text is damaged: {}".format(e))
        return plaintext 
Example #14
Source File: aes.py    From eventsourcing with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def encrypt(self, plaintext: bytes) -> bytes:
        """Return ciphertext for given plaintext."""

        # Construct AES-GCM cipher, with 96-bit nonce.
        cipher = AES.new(self.cipher_key, AES.MODE_GCM, nonce=random_bytes(12))

        # Encrypt and digest.
        encrypted, tag = cipher.encrypt_and_digest(plaintext)  # type: ignore

        # Combine with nonce.
        ciphertext = cipher.nonce + tag + encrypted  # type: ignore

        # Return ciphertext.
        return ciphertext 
Example #15
Source File: test_GCM.py    From FODI with GNU General Public License v3.0 6 votes vote down vote up
def test_valid_multiple_encrypt_or_decrypt(self):
        for method_name in "encrypt", "decrypt":
            for auth_data in (None, b"333", self.data_128,
                              self.data_128 + b"3"):
                if auth_data is None:
                    assoc_len = None
                else:
                    assoc_len = len(auth_data)
                cipher = AES.new(self.key_128, AES.MODE_GCM,
                                 nonce=self.nonce_96)
                if auth_data is not None:
                    cipher.update(auth_data)
                method = getattr(cipher, method_name)
                method(self.data_128)
                method(self.data_128)
                method(self.data_128)
                method(self.data_128) 
Example #16
Source File: test_GCM.py    From android_universal with MIT License 5 votes vote down vote up
def test_output_param(self):

        pt = b'5' * 16
        cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
        ct = cipher.encrypt(pt)
        tag = cipher.digest()

        output = bytearray(16)
        cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
        res = cipher.encrypt(pt, output=output)
        self.assertEqual(ct, output)
        self.assertEqual(res, None)
        
        cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
        res = cipher.decrypt(ct, output=output)
        self.assertEqual(pt, output)
        self.assertEqual(res, None)
        
        cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
        res, tag_out = cipher.encrypt_and_digest(pt, output=output)
        self.assertEqual(ct, output)
        self.assertEqual(res, None)
        self.assertEqual(tag, tag_out)
        
        cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
        res = cipher.decrypt_and_verify(ct, tag, output=output)
        self.assertEqual(pt, output)
        self.assertEqual(res, None) 
Example #17
Source File: test_GCM.py    From android_universal with MIT License 5 votes vote down vote up
def test_valid_init_encrypt_decrypt_digest_verify(self):
        # No authenticated data, fixed plaintext
        # Verify path INIT->ENCRYPT->DIGEST
        cipher = AES.new(self.key_128, AES.MODE_GCM,
                         nonce=self.nonce_96)
        ct = cipher.encrypt(self.data_128)
        mac = cipher.digest()

        # Verify path INIT->DECRYPT->VERIFY
        cipher = AES.new(self.key_128, AES.MODE_GCM,
                         nonce=self.nonce_96)
        cipher.decrypt(ct)
        cipher.verify(mac) 
Example #18
Source File: test_GCM.py    From android_universal with MIT License 5 votes vote down vote up
def test_message_chunks(self):
        # Validate that both associated data and plaintext/ciphertext
        # can be broken up in chunks of arbitrary length

        auth_data = get_tag_random("authenticated data", 127)
        plaintext = get_tag_random("plaintext", 127)

        cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
        cipher.update(auth_data)
        ciphertext, ref_mac = cipher.encrypt_and_digest(plaintext)

        def break_up(data, chunk_length):
            return [data[i:i+chunk_length] for i in range(0, len(data),
                    chunk_length)]

        # Encryption
        for chunk_length in 1, 2, 3, 7, 10, 13, 16, 40, 80, 128:

            cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)

            for chunk in break_up(auth_data, chunk_length):
                cipher.update(chunk)
            pt2 = b""
            for chunk in break_up(ciphertext, chunk_length):
                pt2 += cipher.decrypt(chunk)
            self.assertEqual(plaintext, pt2)
            cipher.verify(ref_mac)

        # Decryption
        for chunk_length in 1, 2, 3, 7, 10, 13, 16, 40, 80, 128:

            cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)

            for chunk in break_up(auth_data, chunk_length):
                cipher.update(chunk)
            ct2 = b""
            for chunk in break_up(plaintext, chunk_length):
                ct2 += cipher.encrypt(chunk)
            self.assertEqual(ciphertext, ct2)
            self.assertEquals(cipher.digest(), ref_mac) 
Example #19
Source File: cipher.py    From Notebook with MIT License 5 votes vote down vote up
def decrypt(ciphertext, key):
        cipher_nonce = ciphertext
        key = SHA256.new(key).digest()

        nonce = cipher_nonce[:CryptoAES.nonce_size]
        ciphertext = cipher_nonce[CryptoAES.nonce_size:]

        cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
        plaintext = cipher.decrypt(ciphertext)
        return plaintext 
Example #20
Source File: cipher.py    From Notebook with MIT License 5 votes vote down vote up
def encrypt(data, key):
        key = SHA256.new(key).digest()
        nonce = get_random_bytes(CryptoAES.nonce_size)
        
        cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
        ciphertext = cipher.encrypt(data)        
        return nonce + ciphertext 
Example #21
Source File: test_GCM.py    From android_universal with MIT License 5 votes vote down vote up
def test_block_size_128(self):
        cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
        self.assertEqual(cipher.block_size, AES.block_size) 
Example #22
Source File: test_GCM.py    From FODI with GNU General Public License v3.0 5 votes vote down vote up
def runTest(self):
        key = b'0' * 16
        h = SHA256.new()

        for length in range(160):
            nonce = '{0:04d}'.format(length).encode('utf-8')
            data = bchr(length) * length
            cipher = AES.new(key, AES.MODE_GCM, nonce=nonce, **self._extra_params)
            ct, tag = cipher.encrypt_and_digest(data)
            h.update(ct)
            h.update(tag)

        self.assertEqual(h.hexdigest(), "7b7eb1ffbe67a2e53a912067c0ec8e62ebc7ce4d83490ea7426941349811bdf4") 
Example #23
Source File: test_GCM.py    From FODI with GNU General Public License v3.0 5 votes vote down vote up
def test_corrupt_decrypt(self, tv):
        self._id = "Wycheproof Corrupt Decrypt GCM Test #" + str(tv.id)
        if len(tv.iv) == 0 or len(tv.ct) < 1:
            return
        cipher = AES.new(tv.key, AES.MODE_GCM, tv.iv, mac_len=tv.tag_size,
                **self._extra_params)
        cipher.update(tv.aad)
        ct_corrupt = strxor(tv.ct, b"\x00" * (len(tv.ct) - 1) + b"\x01")
        self.assertRaises(ValueError, cipher.decrypt_and_verify, ct_corrupt, tv.tag) 
Example #24
Source File: test_GCM.py    From FODI with GNU General Public License v3.0 5 votes vote down vote up
def single_test(self, tv=tv):

            self.description = tv.desc
            cipher = AES.new(tv.key, AES.MODE_GCM, nonce=tv.iv,
                             mac_len=len(tv.tag), use_clmul=self.use_clmul)
            cipher.update(tv.aad)
            if "FAIL" in tv.others:
                self.assertRaises(ValueError, cipher.decrypt_and_verify,
                                  tv.ct, tv.tag)
            else:
                pt = cipher.decrypt_and_verify(tv.ct, tv.tag)
                self.assertEqual(pt, tv.pt) 
Example #25
Source File: test_GCM.py    From FODI with GNU General Public License v3.0 5 votes vote down vote up
def test_1(self):
        key = unhexlify("3da6c536d6295579c0959a7043efb503")
        iv  = unhexlify("2b926197d34e091ef722db94")
        aad = unhexlify("00000000000000000000000000000000" +
                        "000102030405060708090a0b0c0d0e0f" +
                        "101112131415161718191a1b1c1d1e1f" +
                        "202122232425262728292a2b2c2d2e2f" +
                        "303132333435363738393a3b3c3d3e3f")
        digest = unhexlify("69dd586555ce3fcc89663801a71d957b")

        cipher = AES.new(key, AES.MODE_GCM, iv).update(aad)
        self.assertEqual(digest, cipher.digest()) 
Example #26
Source File: test_GCM.py    From FODI with GNU General Public License v3.0 5 votes vote down vote up
def runTest(self):
        for assoc_data, pt, ct, mac, key, nonce in self.test_vectors:

            # Encrypt
            cipher = AES.new(key, AES.MODE_GCM, nonce, mac_len=len(mac))
            cipher.update(assoc_data)
            ct2, mac2 = cipher.encrypt_and_digest(pt)
            self.assertEqual(ct, ct2)
            self.assertEqual(mac, mac2)

            # Decrypt
            cipher = AES.new(key, AES.MODE_GCM, nonce, mac_len=len(mac))
            cipher.update(assoc_data)
            pt2 = cipher.decrypt_and_verify(ct, mac)
            self.assertEqual(pt, pt2) 
Example #27
Source File: test_GCM.py    From FODI with GNU General Public License v3.0 5 votes vote down vote up
def test_invalid_encrypt_or_update_after_digest(self):
        for method_name in "encrypt", "update":
            cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
            cipher.encrypt(self.data_128)
            cipher.digest()
            self.assertRaises(TypeError, getattr(cipher, method_name),
                              self.data_128)

            cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
            cipher.encrypt_and_digest(self.data_128) 
Example #28
Source File: test_GCM.py    From FODI with GNU General Public License v3.0 5 votes vote down vote up
def test_invalid_mixing_encrypt_decrypt(self):
        # Once per method, with or without assoc. data
        for method1_name, method2_name in (("encrypt", "decrypt"),
                                           ("decrypt", "encrypt")):
            for assoc_data_present in (True, False):
                cipher = AES.new(self.key_128, AES.MODE_GCM,
                                 nonce=self.nonce_96)
                if assoc_data_present:
                    cipher.update(self.data_128)
                getattr(cipher, method1_name)(self.data_128)
                self.assertRaises(TypeError, getattr(cipher, method2_name),
                                  self.data_128) 
Example #29
Source File: test_GCM.py    From FODI with GNU General Public License v3.0 5 votes vote down vote up
def test_valid_encrypt_and_digest_decrypt_and_verify(self):
        # encrypt_and_digest
        cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
        cipher.update(self.data_128)
        ct, mac = cipher.encrypt_and_digest(self.data_128)

        # decrypt_and_verify
        cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
        cipher.update(self.data_128)
        pt = cipher.decrypt_and_verify(ct, mac)
        self.assertEqual(self.data_128, pt) 
Example #30
Source File: test_GCM.py    From FODI with GNU General Public License v3.0 5 votes vote down vote up
def test_valid_multiple_digest_or_verify(self):
        # Multiple calls to digest
        cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
        cipher.update(self.data_128)
        first_mac = cipher.digest()
        for x in range(4):
            self.assertEqual(first_mac, cipher.digest())

        # Multiple calls to verify
        cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
        cipher.update(self.data_128)
        for x in range(5):
            cipher.verify(first_mac)