def setup_cipher(self): algorithm = algorithms.AES(self.key) self._cipher = Cipher(algorithm, mode=self.IV, backend=default_backend()) self.encryptor = self._cipher.encryptor() self.decryptor = self._cipher.decryptor()
def _mysql_aes_engine(key): """Create MYSQL AES cipher engine.""" return Cipher(algorithms.AES(key), modes.ECB(), default_backend())
def encriptarserver(keyaes, iv, ctp): #encriptar cipher = Cipher(algorithms.AES(keyaes), modes.CTR(iv), backend=backend) encryptor = cipher.encryptor() ct = encryptor.update(ctp) + encryptor.finalize() return ct
def encrypt_aes_ecb(plaintext: bytes, key: bytes) -> bytes: backend = default_backend() cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=backend) encryptor = cipher.encryptor() encrypted = encryptor.update(plaintext) + encryptor.finalize() return encrypted
# Then send public key int hash print("Sending public key int hash") sha256_hasher = hashlib.sha256(public_key_ints) public_key_hash = sha256_hasher.hexdigest() UDPClientSocket.sendto(public_key_hash.encode(), serverAddressPort) # Wait for encrypted aes key msgFromServer = UDPClientSocket.recvfrom(bufferSize) encrypted_aes_key_ints = int(msgFromServer[0]) aes_key = int_to_bytes(simple_rsa_decrypt(encrypted_aes_key_ints, private_key)) # Init aes aesCipher = Cipher(algorithms.AES(aes_key), modes.ECB(), backend=default_backend()) aesEncryptor = aesCipher.encryptor() aesDecryptor = aesCipher.decryptor() # Encrypt message, then send while 1: # Send encrypted message message = input("Enter a message to send to P2: ").encode() message += b" " * (-len(message) % 16 ) # Padding to full blocks of 16 bytes ciphertext = aesEncryptor.update(message) bytesToSend = ciphertext
def cipher_aes_cbc(key, init_vec): return Cipher(algorithms.AES(key), modes.CBC(init_vec), default_backend())
def link_state_put(): if settings.app.demo_mode: return utils.demo_blocked() auth_token = flask.request.headers.get('Auth-Token', None) auth_timestamp = flask.request.headers.get('Auth-Timestamp', None) auth_nonce = flask.request.headers.get('Auth-Nonce', None) auth_signature = flask.request.headers.get('Auth-Signature', None) if not auth_token or not auth_timestamp or not auth_nonce or \ not auth_signature: return flask.abort(406) auth_nonce = auth_nonce[:32] try: if abs(int(auth_timestamp) - int(utils.time_now())) > \ settings.app.auth_time_window: return flask.abort(408) except ValueError: return flask.abort(405) host = link.get_host(utils.ObjectId(auth_token)) if not host: return flask.abort(404) auth_string = '&'.join([ auth_token, auth_timestamp, auth_nonce, flask.request.method, flask.request.path, ]) if len(auth_string) > AUTH_SIG_STRING_MAX_LEN: return flask.abort(413) auth_test_signature = base64.b64encode( hmac.new(host.secret.encode(), auth_string, hashlib.sha512).digest()) if not utils.const_compare(auth_signature, auth_test_signature): return flask.abort(401) nonces_collection = mongo.get_collection('auth_nonces') try: nonces_collection.insert({ 'token': auth_token, 'nonce': auth_nonce, 'timestamp': utils.now(), }) except pymongo.errors.DuplicateKeyError: return flask.abort(409) host.load_link() host.version = flask.request.json.get('version') host.public_address = flask.request.json.get('public_address') host.local_address = flask.request.json.get('local_address') host.address6 = flask.request.json.get('address6') data = json.dumps(host.get_state(), default=lambda x: str(x)) data += (16 - len(data) % 16) * '\x00' iv = os.urandom(16) key = hashlib.sha256(host.secret).digest() cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend()).encryptor() enc_data = base64.b64encode(cipher.update(data) + cipher.finalize()) enc_signature = base64.b64encode( hmac.new(host.secret.encode(), enc_data, hashlib.sha512).digest()) resp = flask.Response(response=enc_data, mimetype='application/base64') resp.headers.add('Cache-Control', 'no-cache, no-store, must-revalidate') resp.headers.add('Pragma', 'no-cache') resp.headers.add('Expires', 0) resp.headers.add('Cipher-IV', base64.b64encode(iv)) resp.headers.add('Cipher-Signature', enc_signature) return resp
def __init__(self, token: str, session_id: str) -> None: self._token = binascii.unhexlify(token) self._session_id = session_id self._cipher = Cipher(algorithms.AES(self._token), modes.ECB())
def ecb_cipher(key: bytes) -> Cipher: backend = default_backend() return Cipher(algorithms.AES(key), modes.ECB(), backend=backend)
def __init__(self, key): """Initialize a new AESCipher.""" self.block_size = 16 self.cipher = Cipher(algorithms.AES(key), modes.ECB(), default_backend())
def AESEncryptForChallenge12_CypherModule(dat): cipher = Cipher(algorithms.AES(challenge12key), modes.ECB(), backend=default_backend()) encryptor = cipher.encryptor() enc = encryptor.update(dat) + encryptor.finalize() return enc
def create(self, key, public_key_format, enckey, dependencies=None, sw_type=None, custom_tlvs=None): self.enckey = enckey # Calculate the hash of the public key if key is not None: pub = key.get_public_bytes() sha = hashlib.sha256() sha.update(pub) pubbytes = sha.digest() else: pubbytes = bytes(hashlib.sha256().digest_size) protected_tlv_size = 0 if self.security_counter is not None: # Size of the security counter TLV: header ('HH') + payload ('I') # = 4 + 4 = 8 Bytes protected_tlv_size += TLV_SIZE + 4 if sw_type is not None: if len(sw_type) > MAX_SW_TYPE_LENGTH: msg = "'{}' is too long ({} characters) for sw_type. Its " \ "maximum allowed length is 12 characters.".format( sw_type, len(sw_type)) raise click.UsageError(msg) image_version = (str(self.version.major) + '.' + str(self.version.minor) + '.' + str(self.version.revision)) # The image hash is computed over the image header, the image # itself and the protected TLV area. However, the boot record TLV # (which is part of the protected area) should contain this hash # before it is even calculated. For this reason the script fills # this field with zeros and the bootloader will insert the right # value later. digest = bytes(hashlib.sha256().digest_size) # Create CBOR encoded boot record boot_record = create_sw_component_data(sw_type, image_version, "SHA256", digest, pubbytes) protected_tlv_size += TLV_SIZE + len(boot_record) if dependencies is not None: # Size of a Dependency TLV = Header ('HH') + Payload('IBBHI') # = 4 + 12 = 16 Bytes dependencies_num = len(dependencies[DEP_IMAGES_KEY]) protected_tlv_size += (dependencies_num * 16) if custom_tlvs is not None: for value in custom_tlvs.values(): protected_tlv_size += TLV_SIZE + len(value) if protected_tlv_size != 0: # Add the size of the TLV info header protected_tlv_size += TLV_INFO_SIZE # At this point the image is already on the payload # # This adds the padding if image is not aligned to the 16 Bytes # in encrypted mode if self.enckey is not None: pad_len = len(self.payload) % 16 if pad_len > 0: self.payload += bytes(16 - pad_len) # This adds the header to the payload as well self.add_header(enckey, protected_tlv_size) prot_tlv = TLV(self.endian, TLV_PROT_INFO_MAGIC) # Protected TLVs must be added first, because they are also included # in the hash calculation protected_tlv_off = None if protected_tlv_size != 0: e = STRUCT_ENDIAN_DICT[self.endian] if self.security_counter is not None: payload = struct.pack(e + 'I', self.security_counter) prot_tlv.add('SEC_CNT', payload) if sw_type is not None: prot_tlv.add('BOOT_RECORD', boot_record) if dependencies is not None: for i in range(dependencies_num): payload = struct.pack( e + 'B3x' + 'BBHI', int(dependencies[DEP_IMAGES_KEY][i]), dependencies[DEP_VERSIONS_KEY][i].major, dependencies[DEP_VERSIONS_KEY][i].minor, dependencies[DEP_VERSIONS_KEY][i].revision, dependencies[DEP_VERSIONS_KEY][i].build) prot_tlv.add('DEPENDENCY', payload) if custom_tlvs is not None: for tag, value in custom_tlvs.items(): prot_tlv.add(tag, value) protected_tlv_off = len(self.payload) self.payload += prot_tlv.get() tlv = TLV(self.endian) # Note that ecdsa wants to do the hashing itself, which means # we get to hash it twice. sha = hashlib.sha256() sha.update(self.payload) digest = sha.digest() tlv.add('SHA256', digest) if key is not None: if public_key_format == 'hash': tlv.add('KEYHASH', pubbytes) else: tlv.add('PUBKEY', pub) # `sign` expects the full image payload (sha256 done internally), # while `sign_digest` expects only the digest of the payload if hasattr(key, 'sign'): sig = key.sign(bytes(self.payload)) else: sig = key.sign_digest(digest) tlv.add(key.sig_tlv(), sig) # At this point the image was hashed + signed, we can remove the # protected TLVs from the payload (will be re-added later) if protected_tlv_off is not None: self.payload = self.payload[:protected_tlv_off] if enckey is not None: plainkey = os.urandom(16) if isinstance(enckey, rsa.RSAPublic): cipherkey = enckey._get_public().encrypt( plainkey, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) self.enctlv_len = len(cipherkey) tlv.add('ENCRSA2048', cipherkey) elif isinstance(enckey, (ecdsa.ECDSA256P1Public, x25519.X25519Public)): cipherkey, mac, pubk = self.ecies_hkdf(enckey, plainkey) enctlv = pubk + mac + cipherkey self.enctlv_len = len(enctlv) if isinstance(enckey, ecdsa.ECDSA256P1Public): tlv.add('ENCEC256', enctlv) else: tlv.add('ENCX25519', enctlv) nonce = bytes([0] * 16) cipher = Cipher(algorithms.AES(plainkey), modes.CTR(nonce), backend=default_backend()) encryptor = cipher.encryptor() img = bytes(self.payload[self.header_size:]) self.payload[self.header_size:] = \ encryptor.update(img) + encryptor.finalize() self.payload += prot_tlv.get() self.payload += tlv.get() self.check_trailer()
def login_proto(self): print("something") Message = COMM_MESSAGE() data, temp = self.connection_from_client.recvfrom(4096) print(temp) Message.ParseFromString(data) if Message.type == Message.TYPE.LOGIN: N1 = os.urandom(16) N1 = N1.hex() print(N1) digest = sha256() digest.update(N1.encode()) Message.N1_hash = digest.hexdigest() Message.message = N1[5:] self.connection_from_client.sendall(Message.SerializeToString()) data, temp = self.connection_from_client.recvfrom(4096) print(temp) Message.ParseFromString(data) if Message.N1 == N1: print("Puzzle figured out!") else: print("Wrong!") bob = DiffieHellman(group=5, key_length=200) bob.generate_public_key() Message.gb_mod_p = str(bob.public_key) bob.generate_shared_secret(int(Message.message)) Kas = str(bob.shared_secret)[:16].encode() # Kas = (bob.shared_secret).to_bytes(16,sys.byteorder) print("Shared secret is:", int.from_bytes(Kas, sys.byteorder)) Message.gb_mod_p = str(bob.public_key) #### loading private key with open("private_key.pem", "rb") as key_file: private_key = serialization.load_pem_private_key( key_file.read(), password=None, backend=default_backend()) #### encryption plain_text_sign = Message.message + "|" + Message.gb_mod_p plain_text_sign = plain_text_sign.encode() ### sign the text signature = private_key.sign( plain_text_sign, paddings.PSS(mgf=paddings.MGF1(hashes.SHA256()), salt_length=paddings.PSS.MAX_LENGTH), hashes.SHA256()) #### Timestamp timestamp = str(int(time.time())) timestamp = timestamp.encode() plain_text = signature + timestamp iv = os.urandom(16) Message.iv = iv padder = padding.PKCS7(128).padder() padded_data = padder.update(plain_text) padded_data += padder.finalize() plain_text_padded = padded_data authenticate_data = b'Final Project' # self.Message.authenticate_data = authenticate_data # GCM Mode, we also need an IV # encrypt cipher = Cipher(algorithms.AES(Kas), modes.GCM(iv), backend=default_backend()) encryptor = cipher.encryptor() encryptor.authenticate_additional_data(authenticate_data) cipher_text = encryptor.update( plain_text_padded) + encryptor.finalize() Message.cipher_text = cipher_text Message.tag = encryptor.tag self.connection_from_client.sendall(Message.SerializeToString()) ### Decrypt and verify the client: data = self.connection_from_client.recv(4096) Message.ParseFromString(data) # AES decryption decryptor = Cipher(algorithms.AES(Kas), modes.GCM(iv, Message.tag), backend=default_backend()).decryptor() decryptor.authenticate_additional_data(authenticate_data) decrypted_plain_text = decryptor.update( Message.cipher_text) + decryptor.finalize() # unpad unpadder = padding.PKCS7(128).unpadder() plain_text = unpadder.update( decrypted_plain_text) + unpadder.finalize() # Verify timestamp plain_text_timestamp = plain_text[-10:] message_timestamp = int(plain_text_timestamp) if ((int(time.time()) - message_timestamp) < 60): print("Timestamp verified") else: print("Timestamp failed!") ### plain_text = plain_text[0:len(plain_text) - 10] plain_text = plain_text.decode() username = plain_text.split("|")[0] password = plain_text.split("|")[1] #if username == "Yushen" and password == "123": # verify = "Success" #else: # verify = "Fail" verify = "Fail" if username in self.identities.keys(): pass_digest = sha256() pass_digest.update(password.encode()) pass_digest.update(self.identities[username]["salt"].encode()) pass_hash = pass_digest.hexdigest() print(pass_hash, "is the passhash") if pass_hash == self.identities[username]["passhash"]: verify = "Success" #### plain_text = verify.encode() timestamp = str(int(time.time())) timestamp = timestamp.encode() plain_text = plain_text + timestamp padder = padding.PKCS7(128).padder() padded_data = padder.update(plain_text) padded_data += padder.finalize() plain_text_padded = padded_data cipher = Cipher(algorithms.AES(Kas), modes.GCM(iv), backend=default_backend()) encryptor = cipher.encryptor() encryptor.authenticate_additional_data(authenticate_data) cipher_text = encryptor.update( plain_text_padded) + encryptor.finalize() Message.cipher_text = cipher_text Message.tag = encryptor.tag self.connection_from_client.sendall(Message.SerializeToString()) # connection_from_client.shutdown(0) # self.socket_from_client.shutdown(0) self.connection_from_client.close() self.socket_from_client.close()
def __init__(self, key, iv): self.cipher = Cipher(algorithms.AES(key), modes.CTR(iv))
def _get_cipher(self, secret): be = default_backend() return Cipher(algorithms.AES(secret), modes.CBC(PinProtocolV1.IV), be)
with vector_file: data = json.load(vector_file) return pytest.mark.parametrize( keys, [tuple([entry[k] for k in keys]) for entry in data]) def test_default_backend(): f = Fernet(Fernet.generate_key()) assert f._backend is default_backend() @pytest.mark.requires_backend_interface(interface=CipherBackend) @pytest.mark.requires_backend_interface(interface=HMACBackend) @pytest.mark.supported( only_if=lambda backend: backend.cipher_supported( algorithms.AES(b"\x00" * 32), modes.CBC(b"\x00" * 16)), skip_message="Does not support AES CBC", ) class TestFernet(object): @json_parametrize( ("secret", "now", "iv", "src", "token"), "generate.json", ) def test_generate(self, secret, now, iv, src, token, backend): f = Fernet(secret.encode("ascii"), backend=backend) actual_token = f._encrypt_from_parts( src.encode("ascii"), calendar.timegm(iso8601.parse_date(now).utctimetuple()), bytes(iv), ) assert actual_token == token.encode("ascii")
def dec(key=b"", nonce=b"", mess=b""): alg = algorithms.AES(key) cipher = Cipher(alg, modes.GCM(nonce), default_backend()) decryptor = cipher.decryptor() return decryptor.update(mess)
def symmetric_decryptServermsg(key, associated_data, iv, ciphertext, tag): decryptor = Cipher(algorithms.AES(key), modes.GCM(iv, tag), backend=default_backend()).decryptor() decryptor.authenticate_additional_data(associated_data) return decryptor.update(ciphertext) + decryptor.finalize()
def cipher(key, iv): key = md5(key) #normalize key to 128 bits return Cipher(algorithms.AES(key), modes.CFB(iv), backend=default_backend())
def __init__(self, shared_secret): cipher = ciphers.Cipher(algorithms.AES(shared_secret), modes.CFB8(shared_secret), backend) # Name courtesy of dx self.encryptifier = cipher.encryptor() self.decryptifier = cipher.decryptor()
def decrypt_aes_ecb(ciphertext: bytes, key: bytes) -> bytes: backend = default_backend() cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=backend) decryptor = cipher.decryptor() decrypted = decryptor.update(ciphertext) + decryptor.finalize() return decrypted
def symmetric_decryption(sym_key, iv, tag, message): decryptor = Cipher(algorithms.AES(sym_key), mode=modes.GCM(iv, tag), backend=default_backend()).decryptor() plaintext = decryptor.update(message) + decryptor.finalize() return plaintext
def GetDecryptor(self): return ciphers.Cipher(algorithms.AES(self.key), modes.CBC(self.iv), backend=openssl.backend).decryptor()
def getDecryptor(self, iv): return Cipher( algorithms.AES(self.key), modes.CFB(iv), backend=default_backend() ).decryptor()
def __ECB_encrypt(ptext, key): print("Encrypting with ECB...") cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=default_backend()) return cipher.encryptor().update(ptext)
import os from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.backends import default_backend backend = default_backend() key = os.urandom(32) iv = os.urandom(16) cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend) encryptor = cipher.encryptor() ct = encryptor.update(b"a secret messagea secret message") print("IV1 used is ", iv) print(ct) decryptor = cipher.decryptor() x = decryptor.update(ct) y = ct[0:16] z = ct[16:32] print("\n\n\n\n") print("1st block ", y, "\t", x[0:16]) print("2nd block ", z, "\t", x[16:32]) print("\n\n\n") iv2 = os.urandom(16) print("IV2 used is ", iv2) cipher2 = Cipher(algorithms.AES(key), modes.CBC(iv2), backend=backend) encryptor = cipher2.encryptor() ct2 = encryptor.update(b"a secret messagea secret message") print(ct2) decryptor = cipher2.decryptor() x = decryptor.update(ct2) y = ct2[0:16]
import binascii import os import pytest from cryptography.hazmat.backends.interfaces import CipherBackend from cryptography.hazmat.primitives.ciphers import algorithms, base, modes from .utils import generate_aead_test, generate_encrypt_test from ...utils import load_nist_vectors @pytest.mark.supported( only_if=lambda backend: backend.cipher_supported( algorithms.AES(b"\x00" * 16), modes.CBC(b"\x00" * 16)), skip_message="Does not support AES CBC", ) @pytest.mark.requires_backend_interface(interface=CipherBackend) class TestAESModeCBC(object): test_CBC = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "AES", "CBC"), [ "CBCGFSbox128.rsp", "CBCGFSbox192.rsp", "CBCGFSbox256.rsp", "CBCKeySbox128.rsp", "CBCKeySbox192.rsp", "CBCKeySbox256.rsp", "CBCVarKey128.rsp",
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.backends import default_backend import os import sys key = os.urandom(16) aesCipher = Cipher(algorithms.AES(key), modes.ECB(), backend=default_backend()) aesEncryptor = aesCipher.encryptor() ifile, ofile = sys.argv[1:3] with open(ifile, 'rb') as reader: with open(ofile, 'wb+') as writer: pre_image = reader.read() header, body = pre_image[:54], pre_image[54:] body += b'\x00' * (16 - (len(body) % 16)) writer.write(header + aesEncryptor.update(body))
def _encrypt(key_data, derived_key_information): """ Encrypt 'key_data' using the Advanced Encryption Standard (AES-256) algorithm. 'derived_key_information' should contain a key strengthened by PBKDF2. The key size is 256 bits and AES's mode of operation is set to CTR (CounTeR Mode). The HMAC of the ciphertext is generated to ensure the ciphertext has not been modified. 'key_data' is the JSON string representation of the key. In the case of RSA keys, this format would be 'securesystemslib.formats.RSAKEY_SCHEMA': {'keytype': 'rsa', 'keyval': {'public': '-----BEGIN RSA PUBLIC KEY----- ...', 'private': '-----BEGIN RSA PRIVATE KEY----- ...'}} 'derived_key_information' is a dictionary of the form: {'salt': '...', 'derived_key': '...', 'iterations': '...'} 'securesystemslib.exceptions.CryptoError' raised if the encryption fails. """ # Generate a random Initialization Vector (IV). Follow the provably secure # encrypt-then-MAC approach, which affords the ability to verify ciphertext # without needing to decrypt it and preventing an attacker from feeding the # block cipher malicious data. Modes like GCM provide both encryption and # authentication, whereas CTR only provides encryption. # Generate a random 128-bit IV. Random bits of data is needed for salts and # initialization vectors suitable for the encryption algorithms used in # 'pyca_crypto_keys.py'. iv = os.urandom(16) # Construct an AES-CTR Cipher object with the given key and a randomly # generated IV. symmetric_key = derived_key_information['derived_key'] encryptor = Cipher(algorithms.AES(symmetric_key), modes.CTR(iv), backend=default_backend()).encryptor() # Encrypt the plaintext and get the associated ciphertext. # Do we need to check for any exceptions? ciphertext = encryptor.update(key_data.encode('utf-8')) + encryptor.finalize() # Generate the hmac of the ciphertext to ensure it has not been modified. # The decryption routine may verify a ciphertext without having to perform # a decryption operation. symmetric_key = derived_key_information['derived_key'] salt = derived_key_information['salt'] hmac_object = \ cryptography.hazmat.primitives.hmac.HMAC(symmetric_key, hashes.SHA256(), backend=default_backend()) hmac_object.update(ciphertext) hmac_value = binascii.hexlify(hmac_object.finalize()) # Store the number of PBKDF2 iterations used to derive the symmetric key so # that the decryption routine can regenerate the symmetric key successfully. # The PBKDF2 iterations are allowed to vary for the keys loaded and saved. iterations = derived_key_information['iterations'] # Return the salt, iterations, hmac, initialization vector, and ciphertext # as a single string. These five values are delimited by # '_ENCRYPTION_DELIMITER' to make extraction easier. This delimiter is # arbitrarily chosen and should not occur in the hexadecimal representations # of the fields it is separating. return binascii.hexlify(salt).decode() + _ENCRYPTION_DELIMITER + \ str(iterations) + _ENCRYPTION_DELIMITER + \ hmac_value.decode() + _ENCRYPTION_DELIMITER + \ binascii.hexlify(iv).decode() + _ENCRYPTION_DELIMITER + \ binascii.hexlify(ciphertext).decode()
mainexit.set() break print("\033[1;31m", end="") print(message.decode(), "\033[0m") thread = Thread(target=listener) thread.start() while True: mail = input() if mainexit.is_set(): break if mail == "exit": mainexit.set() print("Appuyez sur Entrée pour quitter") iv = os.urandom(16) cipher = Cipher(algorithms.AES(derived_key), modes.CBC(iv)) encryptor = cipher.encryptor() padder = padding.PKCS7(128).padder() padded_data = padder.update(mail.encode()) padded_data += padder.finalize() ciphertext = encryptor.update(padded_data) + encryptor.finalize() hashmac = hmac.HMAC(HMAC_key, hashes.SHA256()) hashmac.update(iv + ciphertext) signature = hashmac.finalize() mysock.send(iv + ciphertext) mysock.send(signature) mysock.close()