Python Crypto.Cipher.AES.MODE_CTR Examples
The following are 30
code examples of Crypto.Cipher.AES.MODE_CTR().
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: encryptionencoding.py From chepy with GNU General Public License v3.0 | 12 votes |
def triple_des_encrypt( self, key: str, iv: str = "0000000000000000", mode: str = "CBC", hex_key: bool = False, hex_iv: bool = True, ): """Encrypt raw state with Triple DES Triple DES applies DES three times to each block to increase key size. Key: Triple DES uses a key length of 24 bytes (192 bits).<br>DES uses a key length of 8 bytes (64 bits).<br><br>You can generate a password-based key using one of the KDF operations. IV: The Initialization Vector should be 8 bytes long. If not entered, it will default to 8 null bytes. Padding: In CBC and ECB mode, PKCS#7 padding will be used. Args: key (str): Required. The secret key iv (str, optional): IV for certain modes only. Defaults to '0000000000000000'. mode (str, optional): Encryption mode. Defaults to 'CBC'. hex_key (bool, optional): If the secret key is a hex string. Defaults to False. hex_iv (bool, optional): If the IV is a hex string. Defaults to True. Returns: Chepy: The Chepy object. Examples: >>> Chepy("some data").triple_des_encrypt("super secret password !!", mode="ECB").o b"f8b27a0d8c837edc8fb00ea85f502fb4" """ self.__check_mode(mode) key, iv = self._convert_key(key, iv, hex_key, hex_iv) if mode == "CBC": cipher = DES3.new(key, mode=DES3.MODE_CBC, iv=iv) self.state = cipher.encrypt(pad(self._convert_to_bytes(), 8)) return self elif mode == "ECB": cipher = DES3.new(key, mode=DES3.MODE_ECB) self.state = cipher.encrypt(pad(self._convert_to_bytes(), 8)) return self elif mode == "CTR": cipher = DES3.new(key, mode=DES3.MODE_CTR, nonce=b"") self.state = cipher.encrypt(self._convert_to_bytes()) return self elif mode == "OFB": cipher = DES3.new(key, mode=DES3.MODE_OFB, iv=iv) self.state = cipher.encrypt(self._convert_to_bytes()) return self
Example #2
Source File: kobackupdec.py From kobackupdec with MIT License | 8 votes |
def decrypt_file(self, dec_material, data): if not self._good: logging.warning('well, it is hard to decrypt with a wrong key.') if not dec_material.iv: logging.error('cannot decrypt with an empty iv!') return None counter_obj = Counter.new( 128, initial_value=int.from_bytes(dec_material.iv, byteorder='big'), little_endian=False) decryptor = AES.new( self._bkey_sha256, mode=AES.MODE_CTR, counter=counter_obj) return decryptor.decrypt(data) # --- DecryptInfo -------------------------------------------------------------
Example #3
Source File: test_CTR.py From FODI with GNU General Public License v3.0 | 7 votes |
def test_initial_value_bytes_parameter(self): # Same result as when passing an integer cipher1 = AES.new(self.key_128, AES.MODE_CTR, nonce=self.nonce_64, initial_value=b"\x00"*6+b"\xFF\xFF") cipher2 = AES.new(self.key_128, AES.MODE_CTR, nonce=self.nonce_64, initial_value=0xFFFF) pt = get_tag_random("plaintext", 65536) self.assertEqual(cipher1.encrypt(pt), cipher2.encrypt(pt)) # Fail if the iv is too large self.assertRaises(ValueError, AES.new, self.key_128, AES.MODE_CTR, initial_value=b"5"*17) self.assertRaises(ValueError, AES.new, self.key_128, AES.MODE_CTR, nonce=self.nonce_64, initial_value=b"5"*9) # Fail if the iv is too short self.assertRaises(ValueError, AES.new, self.key_128, AES.MODE_CTR, initial_value=b"5"*15) self.assertRaises(ValueError, AES.new, self.key_128, AES.MODE_CTR, nonce=self.nonce_64, initial_value=b"5"*7)
Example #4
Source File: convergence.py From file-encryptor with MIT License | 7 votes |
def iter_transform(filename, key): """Generate encrypted file with given key. This generator function reads the file in chunks and encrypts them using AES-CTR, with the specified key. :param filename: The name of the file to encrypt. :type filename: str :param key: The key used to encrypt the file. :type key: str :returns: A generator that produces encrypted file chunks. :rtype: generator """ # We are not specifying the IV here. aes = AES.new(key, AES.MODE_CTR, counter=Counter.new(128)) with open(filename, 'rb+') as f: for chunk in iter(lambda: f.read(CHUNK_SIZE), b''): yield aes.encrypt(chunk), f
Example #5
Source File: test_CTR.py From FODI with GNU General Public License v3.0 | 7 votes |
def test_wrap_around(self): # Counter is only 8 bits, so we can only encrypt/decrypt 256 blocks (=4096 bytes) counter = Counter.new(8, prefix=bchr(9) * 15) max_bytes = 4096 cipher = AES.new(self.key_128, AES.MODE_CTR, counter=counter) cipher.encrypt(b'9' * max_bytes) self.assertRaises(OverflowError, cipher.encrypt, b'9') cipher = AES.new(self.key_128, AES.MODE_CTR, counter=counter) self.assertRaises(OverflowError, cipher.encrypt, b'9' * (max_bytes + 1)) cipher = AES.new(self.key_128, AES.MODE_CTR, counter=counter) cipher.decrypt(b'9' * max_bytes) self.assertRaises(OverflowError, cipher.decrypt, b'9') cipher = AES.new(self.key_128, AES.MODE_CTR, counter=counter) self.assertRaises(OverflowError, cipher.decrypt, b'9' * (max_bytes + 1))
Example #6
Source File: test_CTR.py From FODI with GNU General Public License v3.0 | 7 votes |
def test_aes_128(self): plaintext = '6bc1bee22e409f96e93d7e117393172a' +\ 'ae2d8a571e03ac9c9eb76fac45af8e51' +\ '30c81c46a35ce411e5fbc1191a0a52ef' +\ 'f69f2445df4f9b17ad2b417be66c3710' ciphertext = '874d6191b620e3261bef6864990db6ce' +\ '9806f66b7970fdff8617187bb9fffdff' +\ '5ae4df3edbd5d35e5b4f09020db03eab' +\ '1e031dda2fbe03d1792170a0f3009cee' key = '2b7e151628aed2a6abf7158809cf4f3c' counter = Counter.new(nbits=16, prefix=unhexlify('f0f1f2f3f4f5f6f7f8f9fafbfcfd'), initial_value=0xfeff) key = unhexlify(key) plaintext = unhexlify(plaintext) ciphertext = unhexlify(ciphertext) cipher = AES.new(key, AES.MODE_CTR, counter=counter) self.assertEqual(cipher.encrypt(plaintext), ciphertext) cipher = AES.new(key, AES.MODE_CTR, counter=counter) self.assertEqual(cipher.decrypt(ciphertext), plaintext)
Example #7
Source File: test_CTR.py From FODI with GNU General Public License v3.0 | 7 votes |
def test_output_param_neg(self): pt = b'5' * 16 cipher = AES.new(b'4'*16, AES.MODE_CTR, nonce=self.nonce_64) ct = cipher.encrypt(pt) cipher = AES.new(b'4'*16, AES.MODE_CTR, nonce=self.nonce_64) self.assertRaises(TypeError, cipher.encrypt, pt, output=b'0'*16) cipher = AES.new(b'4'*16, AES.MODE_CTR, nonce=self.nonce_64) self.assertRaises(TypeError, cipher.decrypt, ct, output=b'0'*16) shorter_output = bytearray(15) cipher = AES.new(b'4'*16, AES.MODE_CTR, nonce=self.nonce_64) self.assertRaises(ValueError, cipher.encrypt, pt, output=shorter_output) cipher = AES.new(b'4'*16, AES.MODE_CTR, nonce=self.nonce_64) self.assertRaises(ValueError, cipher.decrypt, ct, output=shorter_output)
Example #8
Source File: kobackupdec.py From kobackupdec with MIT License | 6 votes |
def decrypt_large_package(self, dec_material, entry): if not self._good: logging.warning('well, it is hard to decrypt with a wrong key.') if not dec_material.encMsgV3: logging.error('cannot decrypt with an empty encMsgV3!') return None salt = dec_material.encMsgV3[:32] counter_iv = dec_material.encMsgV3[32:] key = PBKDF2(self._bkey, salt, Decryptor.dklen, Decryptor.count, Decryptor.prf, hmac_hash_module=None) counter_obj = Counter.new(128, initial_value=int.from_bytes( counter_iv, byteorder='big'), little_endian=False) decryptor = AES.new(key, mode=AES.MODE_CTR, counter=counter_obj) data_len = entry.stat().st_size with open(entry, 'rb') as entry_fd: for x in range(0, data_len, self.chunk_size): logging.debug('decrypting chunk %d of %s', x, entry) data = entry_fd.read(self.chunk_size) yield decryptor.decrypt(data)
Example #9
Source File: kobackupdec.py From kobackupdec with MIT License | 6 votes |
def decrypt_package(self, dec_material, data): if not self._good: logging.warning('well, it is hard to decrypt with a wrong key.') if not dec_material.encMsgV3: logging.error('cannot decrypt with an empty encMsgV3!') return None salt = dec_material.encMsgV3[:32] counter_iv = dec_material.encMsgV3[32:] key = PBKDF2(self._bkey, salt, Decryptor.dklen, Decryptor.count, Decryptor.prf, hmac_hash_module=None) counter_obj = Counter.new(128, initial_value=int.from_bytes( counter_iv, byteorder='big'), little_endian=False) decryptor = AES.new(key, mode=AES.MODE_CTR, counter=counter_obj) return decryptor.decrypt(data)
Example #10
Source File: test_CTR.py From FODI with GNU General Public License v3.0 | 6 votes |
def test_aes_192(self): plaintext = '6bc1bee22e409f96e93d7e117393172a' +\ 'ae2d8a571e03ac9c9eb76fac45af8e51' +\ '30c81c46a35ce411e5fbc1191a0a52ef' +\ 'f69f2445df4f9b17ad2b417be66c3710' ciphertext = '1abc932417521ca24f2b0459fe7e6e0b' +\ '090339ec0aa6faefd5ccc2c6f4ce8e94' +\ '1e36b26bd1ebc670d1bd1d665620abf7' +\ '4f78a7f6d29809585a97daec58c6b050' key = '8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b' counter = Counter.new(nbits=16, prefix=unhexlify('f0f1f2f3f4f5f6f7f8f9fafbfcfd'), initial_value=0xfeff) key = unhexlify(key) plaintext = unhexlify(plaintext) ciphertext = unhexlify(ciphertext) cipher = AES.new(key, AES.MODE_CTR, counter=counter) self.assertEqual(cipher.encrypt(plaintext), ciphertext) cipher = AES.new(key, AES.MODE_CTR, counter=counter) self.assertEqual(cipher.decrypt(ciphertext), plaintext)
Example #11
Source File: test_CTR.py From FODI with GNU General Public License v3.0 | 6 votes |
def test_output_param(self): pt = b'5' * 16 cipher = AES.new(b'4'*16, AES.MODE_CTR, nonce=self.nonce_64) ct = cipher.encrypt(pt) output = bytearray(16) cipher = AES.new(b'4'*16, AES.MODE_CTR, nonce=self.nonce_64) res = cipher.encrypt(pt, output=output) self.assertEqual(ct, output) self.assertEqual(res, None) cipher = AES.new(b'4'*16, AES.MODE_CTR, nonce=self.nonce_64) res = cipher.decrypt(ct, output=output) self.assertEqual(pt, output) self.assertEqual(res, None)
Example #12
Source File: encryptionencoding.py From chepy with GNU General Public License v3.0 | 6 votes |
def des_encrypt( self, key: str, iv: str = "0000000000000000", mode: str = "CBC", hex_key: bool = False, hex_iv: bool = True, ): """Encrypt raw state with DES DES is a previously dominant algorithm for encryption, and was published as an official U.S. Federal Information Processing Standard (FIPS). It is now considered to be insecure due to its small key size. DES uses a key length of 8 bytes (64 bits).<br>Triple DES uses a key length of 24 bytes. You can generate a password-based key using one of the KDF operations. The Initialization Vector should be 8 bytes long. If not entered, it will default to 8 null bytes. Padding: In CBC and ECB mode, PKCS#7 padding will be used. Args: key (str): Required. The secret key iv (str, optional): IV for certain modes only. Defaults to '0000000000000000'. mode (str, optional): Encryption mode. Defaults to 'CBC'. hex_key (bool, optional): If the secret key is a hex string. Defaults to False. hex_iv (bool, optional): If the IV is a hex string. Defaults to True. Returns: Chepy: The Chepy object. Examples: >>> Chepy("some data").des_encrypt("70617373776f7264", hex_key=True).o b"1ee5cb52954b211d1acd6e79c598baac" To encrypt using a differnt mode >>> Chepy("some data").des_encrypt("password", mode="CTR").o b"0b7399049b0267d93d" """ self.__check_mode(mode) key, iv = self._convert_key(key, iv, hex_key, hex_iv) if mode == "CBC": cipher = DES.new(key, mode=DES.MODE_CBC, iv=iv) self.state = cipher.encrypt(pad(self._convert_to_bytes(), 8)) return self elif mode == "ECB": cipher = DES.new(key, mode=DES.MODE_ECB) self.state = cipher.encrypt(pad(self._convert_to_bytes(), 8)) return self elif mode == "CTR": cipher = DES.new(key, mode=DES.MODE_CTR, nonce=b"") self.state = cipher.encrypt(self._convert_to_bytes()) return self elif mode == "OFB": cipher = DES.new(key, mode=DES.MODE_OFB, iv=iv) self.state = cipher.encrypt(self._convert_to_bytes()) return self
Example #13
Source File: test_CTR.py From FODI with GNU General Public License v3.0 | 5 votes |
def test_output_param_memoryview(self): pt = b'5' * 16 cipher = AES.new(b'4'*16, AES.MODE_CTR, nonce=self.nonce_64) ct = cipher.encrypt(pt) output = memoryview(bytearray(16)) cipher = AES.new(b'4'*16, AES.MODE_CTR, nonce=self.nonce_64) cipher.encrypt(pt, output=output) self.assertEqual(ct, output) cipher = AES.new(b'4'*16, AES.MODE_CTR, nonce=self.nonce_64) cipher.decrypt(ct, output=output) self.assertEqual(pt, output)
Example #14
Source File: Decompress.py From NSC_BUILDER with MIT License | 5 votes |
def seek(self, offset): self.ctr = Counter.new(64, prefix=self.nonce[0:8], initial_value=(offset >> 4)) self.aes = AES.new(self.key, AES.MODE_CTR, counter=self.ctr)
Example #15
Source File: test_CTR.py From FODI with GNU General Public License v3.0 | 5 votes |
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)
Example #16
Source File: test_CTR.py From FODI with GNU General Public License v3.0 | 5 votes |
def test_iv_with_matching_length(self): self.assertRaises(ValueError, AES.new, self.key_128, AES.MODE_CTR, counter=Counter.new(120)) self.assertRaises(ValueError, AES.new, self.key_128, AES.MODE_CTR, counter=Counter.new(136))
Example #17
Source File: aes128.py From NSC_BUILDER with MIT License | 5 votes |
def __init__(self, key, nonce, offset = 0): self.key = key self.nonce = nonce self.seek(offset) #self.aes = AES.new(self.key, AES.MODE_CTR, initial_value=self.ctr[0:8])
Example #18
Source File: test_CTR.py From FODI with GNU General Public License v3.0 | 5 votes |
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)
Example #19
Source File: test_CTR.py From FODI with GNU General Public License v3.0 | 5 votes |
def test_nonce_attribute(self): # Nonce attribute is the prefix passed to Counter (DES3) cipher = DES3.new(self.key_192, DES3.MODE_CTR, counter=self.ctr_64) self.assertEqual(cipher.nonce, self.nonce_32) # Nonce attribute is the prefix passed to Counter (AES) cipher = AES.new(self.key_128, AES.MODE_CTR, counter=self.ctr_128) self.assertEqual(cipher.nonce, self.nonce_64) # Nonce attribute is not defined if suffix is used in Counter counter = Counter.new(64, prefix=self.nonce_32, suffix=self.nonce_32) cipher = AES.new(self.key_128, AES.MODE_CTR, counter=counter) self.failIf(hasattr(cipher, "nonce"))
Example #20
Source File: test_CTR.py From FODI with GNU General Public License v3.0 | 5 votes |
def test_invalid_counter_parameter(self): # Counter object is required for ciphers with short block size self.assertRaises(TypeError, DES3.new, self.key_192, AES.MODE_CTR) # Positional arguments are not allowed (Counter must be passed as # keyword) self.assertRaises(TypeError, AES.new, self.key_128, AES.MODE_CTR, self.ctr_128)
Example #21
Source File: test_CTR.py From FODI with GNU General Public License v3.0 | 5 votes |
def test_loopback_64(self): cipher = DES3.new(self.key_192, DES3.MODE_CTR, counter=self.ctr_64) pt = get_tag_random("plaintext", 8 * 100) ct = cipher.encrypt(pt) cipher = DES3.new(self.key_192, DES3.MODE_CTR, counter=self.ctr_64) pt2 = cipher.decrypt(ct) self.assertEqual(pt, pt2)
Example #22
Source File: test_CTR.py From FODI with GNU General Public License v3.0 | 5 votes |
def test_loopback_128(self): cipher = AES.new(self.key_128, AES.MODE_CTR, counter=self.ctr_128) pt = get_tag_random("plaintext", 16 * 100) ct = cipher.encrypt(pt) cipher = AES.new(self.key_128, AES.MODE_CTR, counter=self.ctr_128) pt2 = cipher.decrypt(ct) self.assertEqual(pt, pt2)
Example #23
Source File: ipsec.py From POC-EXP with GNU General Public License v3.0 | 5 votes |
def new_cipher(self, key, iv): """ @param key: the secret key, a byte string @param iv: the initialization vector, a byte string @return: an initialized cipher object for this algo """ if (hasattr(self.cipher, 'MODE_CTR') and self.mode == self.cipher.MODE_CTR or hasattr(self.cipher, 'MODE_GCM') and self.mode == self.cipher.MODE_GCM): # in counter mode, the "iv" must be incremented for each block # it is calculated like this: # +---------+------------------+---------+ # | nonce | IV | counter | # +---------+------------------+---------+ # m bytes n bytes 4 bytes # <--------------------------------------> # block_size nonce_size = self.cipher.block_size - self.iv_size - 4 # instead of asking for an extra parameter, we extract the last # nonce_size bytes of the key and use them as the nonce. # +----------------------------+---------+ # | cipher key | nonce | # +----------------------------+---------+ # <---------> # nonce_size cipher_key, nonce = key[:-nonce_size], key[-nonce_size:] return self.cipher.new(cipher_key, self.mode, counter=Counter.new(4 * 8, prefix=nonce + iv)) else: return self.cipher.new(key, self.mode, iv)
Example #24
Source File: keyfile.py From eth-keyfile with MIT License | 5 votes |
def encrypt_aes_ctr(value, key, iv): ctr = Counter.new(128, initial_value=iv, allow_wraparound=True) encryptor = AES.new(key, AES.MODE_CTR, counter=ctr) ciphertext = encryptor.encrypt(value) return ciphertext # # Utility #
Example #25
Source File: keyfile.py From eth-keyfile with MIT License | 5 votes |
def decrypt_aes_ctr(ciphertext, key, iv): ctr = Counter.new(128, initial_value=iv, allow_wraparound=True) encryptor = AES.new(key, AES.MODE_CTR, counter=ctr) return encryptor.decrypt(ciphertext)
Example #26
Source File: encryption.py From airpyrt-tools with MIT License | 5 votes |
def __init__(self, key, iv): self.key = key self.iv = iv self.ctr = Counter.new(128, initial_value=int(iv.encode("hex"), 16)) self.cipher = AES.new(key, AES.MODE_CTR, counter=self.ctr)
Example #27
Source File: decrypt.py From nova with MIT License | 5 votes |
def __init__(self, stash_key, manager_provider, aws_profile=None, aws_region=None, aws_bucket=None): check_latest_version() self._aws_manager = manager_provider.aws_manager(aws_profile, aws_region or 'us-east-1') if aws_bucket is None: deployment_bucket_name = 'novastash_%s' % self._aws_manager.account_alias else: deployment_bucket_name = aws_bucket key = "%s.txt.enc" % stash_key existing_stash = self._aws_manager.s3_get(deployment_bucket_name, key) if existing_stash is None: raise NovaError("No stash '%s' found!" % stash_key) else: contents = existing_stash['Body'].read() metadata = existing_stash['Metadata'] encryption_key = metadata['encryption-key'] kms_response = self._aws_manager.kms_decrypt(b64decode(encryption_key), {}) key = kms_response['Plaintext'][:32] hmac_key = kms_response['Plaintext'][32:] hmac = HMAC(hmac_key, msg=b64decode(contents), digestmod=SHA256) if hmac.hexdigest() != metadata['hmac']: raise NovaError("Computed HMAC on '%s' does not match stored HMAC" % stash_key) dec_ctr = Counter.new(128) decryptor = AES.new(key, AES.MODE_CTR, counter=dec_ctr) print(decryptor.decrypt(b64decode(contents)).decode("utf-8"))
Example #28
Source File: test_CTR.py From android_universal with MIT License | 5 votes |
def test_loopback_128(self): cipher = AES.new(self.key_128, AES.MODE_CTR, counter=self.ctr_128) pt = get_tag_random("plaintext", 16 * 100) ct = cipher.encrypt(pt) cipher = AES.new(self.key_128, AES.MODE_CTR, counter=self.ctr_128) pt2 = cipher.decrypt(ct) self.assertEqual(pt, pt2)
Example #29
Source File: cipher.py From python-proxy with MIT License | 5 votes |
def setup(self): from Crypto.Cipher import AES self.cipher = AES.new(self.key, AES.MODE_CTR, nonce=b'', initial_value=self.iv)
Example #30
Source File: test_CTR.py From FODI with GNU General Public License v3.0 | 5 votes |
def test_block_size_128(self): cipher = AES.new(self.key_128, AES.MODE_CTR, counter=self.ctr_128) self.assertEqual(cipher.block_size, AES.block_size)