class TestTripleDESModeCFB8(object): test_kat = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "3DES", "CFB"), [ "TCFB8invperm.rsp", "TCFB8permop.rsp", "TCFB8subtab.rsp", "TCFB8varkey.rsp", "TCFB8vartext.rsp", ], lambda keys, **kwargs: algorithms.TripleDES(binascii.unhexlify(keys)), lambda iv, **kwargs: modes.CFB8(binascii.unhexlify(iv)), ) test_mmt = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "3DES", "CFB"), [ "TCFB8MMT1.rsp", "TCFB8MMT2.rsp", "TCFB8MMT3.rsp", ], lambda key1, key2, key3, **kwargs: algorithms.TripleDES( binascii.unhexlify(key1 + key2 + key3)), lambda iv, **kwargs: modes.CFB8(binascii.unhexlify(iv)), )
def cli(filename): """Send file over to server""" s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = '127.0.0.1' port = 4567 click.echo(click.style('Connecting...', bold=True, fg='yellow')) try: s.connect((host, port)) except socket.error as msg: click.echo( click.style('Error connecting to server: ' + str(msg[1]), bold=True, fg='red')) pt = b"" while True: chunk = filename.read(100) if not chunk: break pt += chunk ks = KeyStore('enc_key.store', os.path.abspath('')) key = str.encode(ks.keys['mother_base_key'].public_key) sk = os.urandom(16) so = SealedObject() cipher = Cipher(algorithms.AES(key), mode=modes.CFB8(open('iv.txt', 'rb').read(16)), backend=default_backend()) csk = so.seal(sk, cipher) s.sendall(csk) #time.sleep(1) s.recv(512) cipher = Cipher(algorithms.AES(sk), mode=modes.CFB8(open('iv.txt', 'rb').read(16)), backend=default_backend()) encryptor = cipher.encryptor() ct = encryptor.update(pt) + encryptor.finalize() s.send(ct) s.close() click.echo(click.style('File sent!', bold=True, fg='green'))
def decrypt(peer, data, iv, key=None): if key is None: data = base64.b64decode(data) mode = peer.cipher_spec.split('-')[-2] if mode == 'CTR': cipher = Cipher(algorithms.AES(peer.shared_key), modes.CTR(iv), default_backend()) decryptor = cipher.decryptor() return decryptor.update(data) + decryptor.finalize() elif mode == 'OFB': cipher = Cipher(algorithms.AES(peer.shared_key), modes.OFB(iv), default_backend()) decryptor = cipher.decryptor() return decryptor.update(data) + decryptor.finalize() elif mode == 'CFB8': cipher = Cipher(algorithms.AES(peer.shared_key), modes.CFB8(iv), default_backend()) decryptor = cipher.decryptor() return decryptor.update(data) + decryptor.finalize() else: data = base64.b64decode(data) plaintext = key.decrypt( data, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), label=None)) return plaintext
def _create_cipher(iv, key): """Create a cipher for use in symmetric encryption/decryption. This will use AES encryption in CFB mode (using an 8-bit shift register) and a random IV. Args: iv (bytes): The random IV to use for the cipher. key (bytes): The encryption key to use. Returns: cryptography.hazmat.primitives.cipher.Cipher: The cipher to use for encryption/decryption. Raises: ValueError: The encryption key was not in the right format. """ if not isinstance(key, bytes): raise TypeError('The encryption key must be of type "bytes", not "%s"' % type(key)) return Cipher(algorithms.AES(key), modes.CFB8(iv), default_backend())
def decrypt_to_stream(raw, key, chunk_size=1e8): ''' Decrypt content using AES Cipher Feedback (CFB 8-bit shift register) and return as a stream of bytes :param raw: Raw encrypted content :type raw: a .read()-supporting file-like object :param key: Encryption key :type key: :mod:`cryptease.Key` :param chunk_size: Chunk size in bytes :type chunk_size: int ''' chunk_size = int(chunk_size) header, payload_start = read_header(raw) raw.seek(payload_start) iv = raw.read(16) cipher = Cipher(algorithms.AES(key.key), modes.CFB8(iv), backend=default_backend()) decryptor = cipher.decryptor() while True: chunk = raw.read(chunk_size) if not chunk: break yield decryptor.update(chunk) yield decryptor.finalize()
def encrypt(peer, data): if isinstance(data, dict) or isinstance(data, str): try: data = json.dumps(data) except: # This code only executes if data is a key cipherText = peer.rsaKey.encrypt(data, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), label=None )) return base64.b64encode(cipherText) else: mode = peer.cd.cipherSpec.split('-')[-2] iv = os.urandom(16) if mode == "CTR": cipher = Cipher(algorithms.AES(peer.cd.sharedKey), modes.CTR(iv), default_backend()) encryptor = cipher.encryptor() encData = encryptor.update(data) + encryptor.finalize() return base64.b64encode(encData), base64.b64encode(iv) elif mode == "OFB": cipher = Cipher(algorithms.AES(peer.cd.sharedKey), modes.OFB(iv), default_backend()) encryptor = cipher.encryptor() encData = encryptor.update(data) + encryptor.finalize() return base64.b64encode(encData), base64.b64encode(iv) elif mode == "CFB8": cipher = Cipher(algorithms.AES(peer.cd.sharedKey), modes.CFB8(iv), default_backend()) encryptor = cipher.encryptor() encData = encryptor.update(data) + encryptor.finalize() return base64.b64encode(encData), base64.b64encode(iv)
def create_AES_cipher(shared_secret): cipher = Cipher( algorithms.AES(shared_secret), modes.CFB8(shared_secret), backend=default_backend(), ) return cipher
def test_cfb8(self, backend): with pytest.raises(ValueError): Cipher( algorithms.AES(b"\x00" * 16), modes.CFB8(b"abc"), backend, )
def configure_encryption(self, secret_key): self.cipher = Cipher(algorithms.AES(secret_key), modes.CFB8(secret_key), backend=default_backend()) self.encryptor = self.cipher.encryptor() self.decryptor = self.cipher.decryptor() self.encrypt = True print('Encryption enabled')
def createAESCipherClass(mode, key, init_vector=None): if mode == 'ECB': mode = modes.ECB() if mode == 'CBC': mode = modes.CBC(init_vector) if mode == 'CFB': mode = modes.CFB8(init_vector) if mode == 'OFB': mode = modes.OFB(init_vector) return Cipher_AES(key, mode)
def _cipher(self, key_iv): """ Construct a Cipher object with suitable parameters. The parameters used are compatible with the pycrypto code this implementation replaced. """ key = hashlib.md5(self.key).hexdigest() return Cipher( algorithms.AES(key), modes.CFB8(key_iv), backend=default_backend())
def gen_cipher(shared_secret): """Generates a :class:`cryptography.hazmat.primitives.ciphers.Cipher` from a shared secret. Parameters ---------- shared_secret The shared secret gotten from :func:`gen_shared_secret`. Returns ------- :class:`cryptography.hazmat.primitives.ciphers.Cipher` The cipher based on the shared secret. """ return Cipher(algorithms.AES(shared_secret), modes.CFB8(shared_secret))
async def _setup_encryption(self, data, access_token, profile_id): server_id = data.readstr() pk_len = data.readvari32() pk = data.read(pk_len) vt_len = data.readvari32() verify_token = data.read(vt_len) # Generate a shared secret shared_secret = os.urandom(16) # If we're in online mode (not '-'), assert valid credentials if server_id != '-': # '-' == offline mode # Calculate the SHA1 hash before using the authenticator sha = hashlib.sha1() sha.update(server_id.encode('ascii')) sha.update(shared_secret) sha.update(pk) # Minecraft uses signed hexadecimal digest server_hash = sha.digest() server_hash = int.from_bytes(server_hash, 'big', signed=True) server_hash = '{:x}'.format(server_hash) # Assert joining the session succeeds assert await authenticator.session_join( access_token, profile_id, server_hash) # Send the Encryption Request packet pk = load_der_public_key(pk, default_backend()) encrypted_secret = pk.encrypt(shared_secret, PKCS1v15()) token = pk.encrypt(verify_token, PKCS1v15()) data = DataRW() data.writevari32(len(encrypted_secret)) data.write(encrypted_secret) data.writevari32(len(token)) data.write(token) await self.send(1, data.getvalue()) # Enable encryption on the socket level cipher = Cipher( algorithms.AES(shared_secret), modes.CFB8(shared_secret), backend=default_backend() ) self._encrypt = cipher.encryptor().update self._decrypt = cipher.decryptor().update
def decrypt(peer, data, iv): data = base64.b64decode(data) mode = peer.cd.cipherSpec.split('-')[-2] if mode == 'CTR': cipher = Cipher(algorithms.AES(peer.cd.sharedKey), modes.CTR(iv), default_backend()) decryptor = cipher.decryptor() return decryptor.update(data) + decryptor.finalize() elif mode == 'OFB': cipher = Cipher(algorithms.AES(peer.cd.sharedKey), modes.OFB(iv), default_backend()) decryptor = cipher.decryptor() return decryptor.update(data) + decryptor.finalize() elif mode == 'CFB8': cipher = Cipher(algorithms.AES(peer.cd.sharedKey), modes.CFB8(iv), default_backend()) decryptor = cipher.decryptor() return decryptor.update(data) + decryptor.finalize()
def encrypt(destination_public_key, sender_private_key, input_plain_text, cipher_text): # AES Encryption: with open(input_plain_text) as f: plain_text = f.read() backend = default_backend() key = os.urandom(32) iv = os.urandom(16) cipher = Cipher(algorithms.AES(key), modes.CFB8(iv), backend=backend) encryptor = cipher.encryptor() ct = encryptor.update(plain_text) + encryptor.finalize() # Private key loading/generation: # private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend()) with open(sender_private_key, "rb") as key_file: private_key = serialization.load_pem_private_key(key_file.read(), password=None,backend=default_backend()) # Signing the message: signer = private_key.signer( padding.PSS( mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH ), hashes.SHA256() ) signer.update(ct) signature = signer.finalize() # Encrypting the AES key: with open(destination_public_key, "rb") as key_file: public_key = serialization.load_pem_public_key(key_file.read(), backend=default_backend()) key_cipher_text = public_key.encrypt( key, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), label=None ) ) parts = [iv, key_cipher_text, ct, signature] complete_cipher_message = '+++'.join(parts) with open(cipher_text, "w") as f: f.write(complete_cipher_message)
def get_cipher(self): if self.method.startswith('rc4'): return Cipher(algorithms.ARC4(self.key), None, default_backend()) if self.method.endswith('ctr'): mode = modes.CTR(self.iv) elif self.method.endswith('ofb'): mode = modes.OFB(self.iv) elif self.method.endswith('cfb8'): mode = modes.CFB8(self.iv) else: mode = modes.CFB(self.iv) if self.method.startswith('aes'): return Cipher(algorithms.AES(self.key), mode, default_backend()) if self.method.startswith('camellia'): return Cipher(algorithms.Camellia(self.key), mode, default_backend()) if self.method.startswith('seed'): return Cipher(algorithms.SEED(self.key), mode, default_backend()) raise ValueError('crypto method %s not supported!' % self.method)
def decrypt(destination_private_key, sender_public_key, cipher_text, output_plain_text): with open(cipher_text) as f: ct = f.read() parts = ct.split('+++') iv = parts[0] key_cipher_text = parts[1] ct = parts[2] signature = parts[3] # Verifying signature with open(sender_public_key) as key_file: public_key = serialization.load_pem_public_key(key_file.read(), backend=default_backend()) verifier = public_key.verifier( signature, padding.PSS( mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH ), hashes.SHA256() ) verifier.update(ct) verifier.verify() # decrypting the key: with open(destination_private_key) as key_file: private_key = serialization.load_pem_private_key(key_file.read(), password=None,backend=default_backend()) aes_key = private_key.decrypt( key_cipher_text, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), label=None ) ) # using AES key to decrypt the message and write to file: cipher = Cipher(algorithms.AES(aes_key), modes.CFB8(iv), backend=default_backend()) decryptor = cipher.decryptor() plain_text = decryptor.update(ct) + decryptor.finalize() with open(output_plain_text, "w") as f: f.write(plain_text)
def mode_for_type(mode_type, iv_or_tweak=None): if mode_type == 'cbc': return modes.CBC(initialization_vector=iv_or_tweak) elif mode_type == 'xts': return modes.XTS(tweak=iv_or_tweak) elif mode_type == 'ecb': return modes.ECB() elif mode_type == 'ofb': return modes.OFB(initialization_vector=iv_or_tweak) elif mode_type == 'cfb': return modes.CFB(initialization_vector=iv_or_tweak) elif mode_type == 'cfb8': return modes.CFB8(initialization_vector=iv_or_tweak) elif mode_type == 'ctr': return modes.CTR(nonce=iv_or_tweak) elif mode_type == 'gcm': return modes.GCM(initialization_vector=iv_or_tweak) else: return None
def encrypt_to_stream(raw, key, chunk_size=1e8): ''' Encrypt content using AES Cipher Feedback (CFB 8-bit shift register) and return as a stream of bytes :param raw: Raw content :type raw: a .read()-supporting file-like object :param key: Encryption key :type key: :mod:`cryptease.Key` :param chunk_size: Chunk size in bytes :type chunk_size: int ''' chunk_size = int(chunk_size) # generate unique initialization vector iv = os.urandom(16) # generate header content ciphermeta = {'function': 'AES', 'params': {'bits': 256, 'mode': 'CFB8'}} header = create_header(ciphermeta, key.metadata, iv) while True: chunk = header.read(chunk_size) if not chunk: break yield chunk # generate initialization vector bio = io.BytesIO(iv) while True: chunk = bio.read(chunk_size) if not chunk: break yield chunk # generate payload content cipher = Cipher(algorithms.AES(key.key), modes.CFB8(iv), backend=default_backend()) encryptor = cipher.encryptor() while True: chunk = raw.read(chunk_size) if not chunk: break yield encryptor.update(chunk) yield encryptor.finalize()
class TestAESModeCFB8(object): test_CFB8 = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "AES", "CFB"), [ "CFB8GFSbox128.rsp", "CFB8GFSbox192.rsp", "CFB8GFSbox256.rsp", "CFB8KeySbox128.rsp", "CFB8KeySbox192.rsp", "CFB8KeySbox256.rsp", "CFB8VarKey128.rsp", "CFB8VarKey192.rsp", "CFB8VarKey256.rsp", "CFB8VarTxt128.rsp", "CFB8VarTxt192.rsp", "CFB8VarTxt256.rsp", "CFB8MMT128.rsp", "CFB8MMT192.rsp", "CFB8MMT256.rsp", ], lambda key, **kwargs: algorithms.AES(binascii.unhexlify(key)), lambda iv, **kwargs: modes.CFB8(binascii.unhexlify(iv)), )
def aes128cfb8(shared_secret): cipher = Cipher(algorithms.AES(shared_secret), modes.CFB8(shared_secret), backend=default_backend()) return cipher
def test_cfb8(self): with pytest.raises(TypeError): modes.CFB8([1] * 16)
"CFB128VarKey256.rsp", "CFB128VarTxt128.rsp", "CFB128VarTxt192.rsp", "CFB128VarTxt256.rsp", "CFB128MMT128.rsp", "CFB128MMT192.rsp", "CFB128MMT256.rsp", ], lambda key, **kwargs: algorithms.AES(binascii.unhexlify(key)), lambda iv, **kwargs: modes.CFB(binascii.unhexlify(iv)), ) @pytest.mark.supported( only_if=lambda backend: backend.cipher_supported( algorithms.AES(b"\x00" * 16), modes.CFB8(b"\x00" * 16)), skip_message="Does not support AES CFB8", ) @pytest.mark.requires_backend_interface(interface=CipherBackend) class TestAESModeCFB8(object): test_CFB8 = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "AES", "CFB"), [ "CFB8GFSbox128.rsp", "CFB8GFSbox192.rsp", "CFB8GFSbox256.rsp", "CFB8KeySbox128.rsp", "CFB8KeySbox192.rsp", "CFB8KeySbox256.rsp", "CFB8VarKey128.rsp",
def enable(self, key): cipher = ciphers.Cipher(algorithms.AES(key), modes.CFB8(key), backend=backend) self.encryptor = cipher.encryptor() self.decryptor = cipher.decryptor()
def test_cfb8(self): with pytest.raises(TypeError): modes.CFB8([1] * 16) # type:ignore[arg-type]
load_nist_vectors, os.path.join("ciphers", "3DES", "CFB"), [ "TCFB64MMT1.rsp", "TCFB64MMT2.rsp", "TCFB64MMT3.rsp", ], lambda key1, key2, key3, **kwargs: algorithms.TripleDES( binascii.unhexlify(key1 + key2 + key3)), lambda iv, **kwargs: modes.CFB(binascii.unhexlify(iv)), ) @pytest.mark.supported( only_if=lambda backend: backend.cipher_supported( algorithms.TripleDES(b"\x00" * 8), modes.CFB8(b"\x00" * 8)), skip_message="Does not support TripleDES CFB8", ) @pytest.mark.requires_backend_interface(interface=CipherBackend) class TestTripleDESModeCFB8(object): test_kat = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "3DES", "CFB"), [ "TCFB8invperm.rsp", "TCFB8permop.rsp", "TCFB8subtab.rsp", "TCFB8varkey.rsp", "TCFB8vartext.rsp", ], lambda keys, **kwargs: algorithms.TripleDES(binascii.unhexlify(keys)),
"CFB128VarKey256.rsp", "CFB128VarTxt128.rsp", "CFB128VarTxt192.rsp", "CFB128VarTxt256.rsp", "CFB128MMT128.rsp", "CFB128MMT192.rsp", "CFB128MMT256.rsp", ], lambda key, **kwargs: algorithms.AES(binascii.unhexlify(key)), lambda iv, **kwargs: modes.CFB(binascii.unhexlify(iv)), ) @pytest.mark.supported( only_if=lambda backend: backend.cipher_supported( algorithms.AES("\x00" * 16), modes.CFB8("\x00" * 16) ), skip_message="Does not support AES CFB8", ) @pytest.mark.cipher class TestAESModeCFB8(object): test_CFB8 = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "AES", "CFB"), [ "CFB8GFSbox128.rsp", "CFB8GFSbox192.rsp", "CFB8GFSbox256.rsp", "CFB8KeySbox128.rsp", "CFB8KeySbox192.rsp", "CFB8KeySbox256.rsp",
def gen_aes_cipher( shared_key: bytes, ): # cipher used to encrypt + decrypt data sent via an encrypted socket return Cipher(algorithms.AES(shared_key), modes.CFB8(shared_key))
def make_cipher(key): return ciphers.Cipher(algorithms.AES(key), modes.CFB8(key), backend=backend)