def __init__(self, key, nonce): aes_ctr = Cipher(algorithms.AES(key), modes.CTR(nonce), backend=default_backend()) self.encryptor = aes_ctr.encryptor() self.hasher = sha256()
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 # 'rsa_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 = 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()
test_OFB = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "CAST5"), ["cast5-ofb.txt"], lambda key, **kwargs: algorithms.CAST5(binascii.unhexlify( (key))), lambda iv, **kwargs: modes.OFB(binascii.unhexlify(iv))) @pytest.mark.supported( only_if=lambda backend: backend.cipher_supported( algorithms.CAST5(b"\x00" * 16), modes.CFB(b"\x00" * 8)), skip_message="Does not support CAST5 CFB", ) @pytest.mark.requires_backend_interface(interface=CipherBackend) class TestCAST5ModeCFB(object): test_CFB = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "CAST5"), ["cast5-cfb.txt"], lambda key, **kwargs: algorithms.CAST5(binascii.unhexlify( (key))), lambda iv, **kwargs: modes.CFB(binascii.unhexlify(iv))) @pytest.mark.supported( only_if=lambda backend: backend.cipher_supported( algorithms.CAST5(b"\x00" * 16), modes.CTR(b"\x00" * 8)), skip_message="Does not support CAST5 CTR", ) @pytest.mark.requires_backend_interface(interface=CipherBackend) class TestCAST5ModeCTR(object): test_CTR = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "CAST5"), ["cast5-ctr.txt"], lambda key, **kwargs: algorithms.CAST5(binascii.unhexlify( (key))), lambda iv, **kwargs: modes.CTR(binascii.unhexlify(iv)))
encryptor = cipher.encryptor() ciphertext = encryptor.update(message) + encryptor.finalize() decryptor = cipher.decryptor() plaintext = decryptor.update(ciphertext) + decryptor.finalize() print("-- CBC --") print("Ciphertext is:", ciphertext) print("Plaintext is:", plaintext) ### Task 2 ### # Last we'll look at CTR mode. This mode converts a block cipher into # a stream cipher. This means that CTR mode neatly handles messages that # are not a multiple of the block length without needing padding. # Here is just such a message, that's already been encrypted: ciphertext = b'\xb8\xbf\xa0$~\xbe\x87*\x86\x18\xa4g' \ b'\xd4=MAt\xd8X\x95<?>\xa2r\x04;{@\x8c' \ b'\xab!\rC\xb3\x0e\x10\xa9\t;\x83\xce|' key = b'\xfa\t\xc6\xdd\xac\xb0a\x99\xef]{`\x07\xe7\xbf\xee' iv = b'P\xbe\xd9\x04\xd00;4\xf9\xeb^\x0f3\x16\xfb\xa3' # Create a cipher here to decrypt the ciphertext using CTR mode. # No partially completed cipher code this time! cipher = Cipher(algorithms.AES(key), modes.CTR(iv), backend=backend) decryptor = cipher.decryptor() plaintext = decryptor.update(ciphertext) + decryptor.finalize() print("-- CTR --") print("Ciphertext is:", ciphertext) print("Plaintext is:", plaintext)
def create(self, key, enckey, dependencies=None): if dependencies is None: dependencies_num = 0 protected_tlv_size = 0 else: # Size of a Dependency TLV = Header ('BBH') + Payload('IBBHI') # = 16 Bytes dependencies_num = len(dependencies[DEP_IMAGES_KEY]) protected_tlv_size = (dependencies_num * 16) + TLV_INFO_SIZE self.add_header(enckey, protected_tlv_size) tlv = TLV(self.endian) if protected_tlv_size != 0: for i in range(dependencies_num): e = STRUCT_ENDIAN_DICT[self.endian] 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) tlv.add('DEPENDENCY', payload) # Full TLV size needs to be calculated in advance, because the # header will be protected as well tlv_header_size = 4 payload_digest_size = 32 keyhash_size = 32 cipherkey_size = 32 full_size = TLV_INFO_SIZE + len(tlv.buf) + tlv_header_size \ + payload_digest_size if key is not None: full_size += tlv_header_size + keyhash_size \ + tlv_header_size + key.sig_len() if enckey is not None: full_size += tlv_header_size + cipherkey_size tlv_header = struct.pack(e + 'HH', TLV_INFO_MAGIC, full_size) self.payload += tlv_header + bytes(tlv.buf) # 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: pub = key.get_public_bytes() sha = hashlib.sha256() sha.update(pub) pubbytes = sha.digest() tlv.add('KEYHASH', pubbytes) # `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) if enckey is not None: plainkey = os.urandom(16) cipherkey = enckey._get_public().encrypt( plainkey, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) tlv.add('ENCRSA2048', cipherkey) 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 += tlv.get()[protected_tlv_size:]
def __init__( self, remote: Node, privkey: datatypes.PrivateKey, connection: PeerConnection, context: BasePeerContext, inbound: bool = False, token: CancelToken = None, listen_port: int = 30303, ) -> None: super().__init__(token) # Any contextual information the peer may need. self.context = context # The `Node` that this peer is connected to self.remote = remote # The private key this peer uses for identification and encryption. self.privkey = privkey # Networking reader and writer objects for communication self.reader = connection.reader self.writer = connection.writer self.base_protocol = P2PProtocol(self) # Flag indicating whether the connection this peer represents was # established from a dial-out or dial-in (True: dial-in, False: # dial-out) # TODO: rename to `dial_in` and have a computed property for `dial_out` self.inbound = inbound self._subscribers = [] # : List[PeerSubscriber] # Uptime tracker for how long the peer has been running. # TODO: this should move to begin within the `_run` method (or maybe as # part of the `BaseService` API) self.start_time = datetime.datetime.now() # A counter of the number of messages this peer has received for each # message type. self.received_msgs = collections.defaultdict( int) # : Dict[protocol.Command, int] # Encryption and Cryptography *stuff* self.egress_mac = connection.egress_mac self.ingress_mac = connection.ingress_mac # FIXME: Insecure Encryption: https://github.com/ethereum/devp2p/issues/32 iv = b"\x00" * 16 aes_secret = connection.aes_secret mac_secret = connection.mac_secret aes_cipher = Cipher(algorithms.AES(aes_secret), modes.CTR(iv), default_backend()) self.aes_enc = aes_cipher.encryptor() self.aes_dec = aes_cipher.decryptor() mac_cipher = Cipher(algorithms.AES(mac_secret), modes.ECB(), default_backend()) self.mac_enc = mac_cipher.encryptor().update # Manages the boot process self.boot_manager = self.get_boot_manager() # this port is not really used on the other side of TCP communication, py-evm had this wrong but it does not matter self.listen_port = listen_port
def encryptAES(data, key): iv = os.urandom(16) cipher = Cipher(algorithms.AES(key), modes.CTR(iv), default_backend()) encryptor = cipher.encryptor() encData = encryptor.update(data) + encryptor.finalize() return encData, iv
#The following if statement determines what encryption mode the algorithm will use if encryption_input == "1": mode = modes.ECB() print("You have selected ECB") elif encryption_input == "2": mode = modes.CBC(AES_iv) print("You have selected CBC") elif encryption_input == "3": mode = modes.CFB(AES_iv) print("You have selected CFB") elif encryption_input == "4": mode = modes.OFB(AES_iv) print("You have selected OFB") elif encryption_input == "5": mode = modes.CTR(AES_nonce) print("You have selected CTR") else: print("Please input a number from 1-5") ##The if statement is finished ##The following code will encrypt the data cipher = Cipher( algorithms.AES(AES_key), mode, backend=AES_backend) #This line is commented out to test ECB AES_encryptor = cipher.encryptor() cipher_text = AES_encryptor.update( AES_padded_data) + AES_encryptor.finalize() AES_decryptor = cipher.decryptor() plaintext_from_ciphertext = AES_decryptor.update(
"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)), ) @pytest.mark.supported( only_if=lambda backend: backend.cipher_supported( algorithms.AES(b"\x00" * 16), modes.CTR(b"\x00" * 16)), skip_message="Does not support AES CTR", ) @pytest.mark.requires_backend_interface(interface=CipherBackend) class TestAESModeCTR(object): test_ctr = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "AES", "CTR"), ["aes-128-ctr.txt", "aes-192-ctr.txt", "aes-256-ctr.txt"], lambda key, **kwargs: algorithms.AES(binascii.unhexlify(key)), lambda iv, **kwargs: modes.CTR(binascii.unhexlify(iv)), ) @pytest.mark.supported( only_if=lambda backend: backend.cipher_supported(
def decrypt(data): """ Purpose: decrypts the given data @param (bits) data - the ciphertext @return (bits) the plaintext """ # Determine the key sameKey = False while(not sameKey): # Get the key from the user print("Please enter the key you used to encrypt the data on the " + "client (target) side. IF YOU HAD EXFILTRON GENERATE THE KEY " + "FOR YOU, LEAVE THIS FIELD BLANK AND JUST PRESS ENTER") key = getpass.getpass("Key: ") # Get hex version of randomly generated key from the user if(key is ''): break # Confirm the key confirm_key = getpass.getpass("Please confirm key: ") sameKey = confirm_key is key # If we generated the key, we'll need to convert from string to bytes if(key = ''): sameKey = False while(not sameKey): # Get the key from the user print("Please enter the hex version of the key Exfiltron " + "generated for you") hexInput = getpass.getpass("Key: ") # Confirm the key confirm_key = getpass.getpass("Please confirm key: ") sameKey = confirm_key is hexInput key = hexInput.decode('hex') else: # Hash the user given key so that it's length is 256 (using SHA256...) from cryptography.hazmat.primitives import hashes digest = hashes.Hash(hashes.SHA256(), default_backend()) digest.update(key) key = digest.finalize() # Get the IV from the user print("Please enter the IV you used to encrypt the data on the " + "client (target) side. IF YOU HAD EXFILTRON GENERATE THE IV " + "FOR YOU, LEAVE THIS FIELD BLANK AND JUST PRESS ENTER") IV = raw_input("IV: ") # If Exfiltron generated one for the user, convert it to bytes if(IV = ''): print("Please enter the hex version of the IV Exfiltron generated for" + " you") IV = raw_input("IV: ") IV = IV.decode('hex') else: from cryptography.hazmat.primitives import hashes digest = hashes.Hash(hashes.MD5(), default_backend()) digest.update(IV) IV = digest.finalize() # Make the cipher cipher = Cipher(algorithms.AES(key), modes.CTR(IV), default_backend()) decryptor = cipher.decryptor() # Return the ciphertext return (decryptor.update(data) + decryptor.finalize())
def encrypt(data): """ Purpose: Encrypts the given data with AES-256 and CTR mode @param (bits) data - arbitrary data to encrypt @return (bits) the encrypted data """ sameKey = False while(not sameKey): # Get the key from the user key = getpass.getpass("Please enter the key you wish to use to encrypt " + "the data (the key you enter will be hashed using SHA-256. If" + " you leave this field blank, the OS will generate a random " + "cryptographically secure number for you to use as the key. " + "This key will be printed to stdout so that you can use it " + "for the decryption on the server (attacker) side): ") # No need to check key if user wants random key if(key is ''): break # Confirm the key confirm_key = getpass.getpass("Please confirm key: ") sameKey = confirm_key is key # Get the IV from the user IV = raw_input("Please enter the initalization vector to be used in CTR" + " mode. The IV should NEVER be reused and should be a nonce." + " (If you leave this field blank, the OS will generate a " + "random cryptographically secure number for you to use as " + "the IV. The IV will be printed to stdout so that you can " + "use it for the decryption on the server (attacker) side): ") # If the user didn't enter anything, generate a random 256 bit key if(key is ''): # Pick a random number for the key key = os.urandom(32) # Get terminal ready to display the key. Start by clearing the screen if(sys.platform.startswith('win')): os.system("cls") else: os.system("clear") # Print the key print("Once you have the key written down/copied to your clipboard, " + "press 'Enter' to overwrite the key with whitespace. The key " + "will be represented as a hex string.") sys.stdout.write("Key: ") sys.stdout.flush() "".join("{:02x}".format(ord(c)) for c in key) # Wait for input raw_input("") # Overwrite key with whitespace (Shout out to Nick K. on stackoverflow) print('\033[{0}D\033[2A'.format(len(key)) + " "*(len(key)*2 + len("Key: "))) else: # Take their input and shove it through SHA-256 to get a key of the # appropriate size from cryptography.hazmat.primitives import hashes digest = hashes.Hash(hashes.SHA256(), default_backend()) digest.update(key) key = digest.finalize() # If no IV was entered, generate a random one and show it to the user # Note that the IV does NOT need to be kept a secret if(IV = ''): IV = os.urandom(16) sys.stdout.write("Your IV is: ") sys.stdout.flush() "".join("{:02x}".format(ord(c)) for c in IV) else: # Take their input and find the MD5 hash of it to get an IV of # the appropriate size (need IV of 128 bits/16 bytes) from cryptography.hazmat.primitives import hashes digest = hashes.Hash(hashes.MD5(), default_backend()) digest.update(IV) IV = digest.finalize() # Make the cipher cipher = Cipher(algorithms.AES(key), modes.CTR(IV), default_backend()) encryptor = cipher.encryptor() # Return the ciphertext return (encryptor.update(data) + encryptor.finalize())
def setEngines(self): self.encEngine = Cipher(algorithms.AES(self.EKc), modes.CTR(self.IVc), backend=default_backend()).encryptor() self.decEngine = Cipher(algorithms.AES(self.EKs), modes.CTR(self.IVs), backend=default_backend()).decryptor() self.macEngine = hmac.HMAC(self.MKc, hashes.SHA1(), backend=default_backend()) self.verificationEngine = hmac.HMAC(self.MKs, hashes.SHA1(), backend=default_backend())
def main(args): #encryption flag is set if args.encrypt: print("encryption") #RSA key testing inPlainfile = open(args.input_file, 'r+b') outCipherfile = open(args.output_file, 'r+b') with open(args.sender_key_filename, "rb") as key_file: private_key = serialization.load_pem_private_key( key_file.read(), password=None, backend=default_backend()) with open(args.destination_key_filename, "rb") as key_file: public_key = serialization.load_pem_public_key( key_file.read(), backend=default_backend()) #sender signing signer = private_key.signer( padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256()) # cipher key key = os.urandom(32) #CBC initiation vector iv = os.urandom(16) #Key encryption for transmision cipherKey = public_key.encrypt( key, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), label=None)) signer.update(cipherKey) signature = signer.finalize() outgoingPackage = {} outgoingPackage["signature"] = str(signature) outgoingPackage["key"] = str(cipherKey) outgoingPackage["IV"] = str(iv) #Put the signature, key, and IV on the first line so we know where to find them outCipherfile.write(str(outgoingPackage) + "\n") #begin symetric encryption #prepare cipher and encryptor cipher = Cipher(algorithms.AES(key), modes.CTR(iv), backend=backend) encryptor = cipher.encryptor() #make sure we start at the begining of the file inPlainfile.seek(0) for chunk in iter(partial(inPlainfile.read, 1024), ''): cipherText = encryptor.update(chunk) outCipherfile.write(cipherText) ct = '' + encryptor.finalize() outCipherfile.write(ct) #close files outCipherfile.close() inPlainfile.close() #decription flag set elif args.decrypt: print("decryption") #RSA Verification inCipherfile = open(args.input_file, 'r+b') outPlainFile = open(args.output_file, 'r+b') with open(args.destination_key_filename, "rb") as key_file: private_key = serialization.load_pem_private_key( key_file.read(), password=None, backend=default_backend()) with open(args.sender_key_filename, "rb") as key_file: public_key = serialization.load_pem_public_key( key_file.read(), backend=default_backend()) # need ast to put the string read into the correct format textOut = ast.literal_eval(inCipherfile.readline()) signature = textOut["signature"] decrypKey = textOut["key"] iv = textOut["IV"] verifier = public_key.verifier( signature, padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256()) #signature verification verifier.update(decrypKey) verifier.verify() #RSA decryption of key key = private_key.decrypt( decrypKey, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), label=None)) #begin symetric decryption cipher = Cipher(algorithms.AES(key), modes.CTR(iv), backend=backend) decryptor = cipher.decryptor() for chunk in iter(partial(inCipherfile.read, 1024), ''): if chunk == '': outPlainFile.write( decryptor.update(chunk) + decryptor.finalize()) break plainText = decryptor.update(chunk) outPlainFile.write(plainText) outPlainFile.seek(0) for line in outPlainFile: print(line) #close files inCipherfile.close() outPlainFile.close() else: print("Please refer to documentation for correct usage")
def CTRinit(self): #在modes中选择模式CTR,同时需要一个16字节的nonce,使用os.urandom(16)生成 cipher_suite = Cipher(algorithms.AES(self.key), modes.CTR(self.iv), backend=self.backend) return cipher_suite
def test_ctr(self): with pytest.raises(TypeError): modes.CTR([1] * 16)
"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)), ) @pytest.mark.supported( only_if=lambda backend: backend.cipher_supported( algorithms.AES("\x00" * 16), modes.CTR("\x00" * 16)), skip_message="Does not support AES CTR", ) @pytest.mark.requires_backend_interface(interface=CipherBackend) class TestAESModeCTR(object): test_CTR = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "AES", "CTR"), ["aes-128-ctr.txt", "aes-192-ctr.txt", "aes-256-ctr.txt"], lambda key, **kwargs: algorithms.AES(binascii.unhexlify(key)), lambda iv, **kwargs: modes.CTR(binascii.unhexlify(iv)), ) @pytest.mark.supported( only_if=lambda backend: backend.cipher_supported(
def decrypt_data(enc_data, key, iv=g.aesctr_dfl_iv, desc='data'): vmsg_r('Decrypting {} with key...'.format(desc)) c = Cipher(algorithms.AES(key), modes.CTR(iv), backend=default_backend()) encryptor = c.encryptor() return encryptor.update(enc_data) + encryptor.finalize()
def create(self, key, enckey, dependencies=None): self.enckey = enckey if dependencies is None: dependencies_num = 0 protected_tlv_size = 0 else: # Size of a Dependency TLV = Header ('BBH') + Payload('IBBHI') # = 16 Bytes dependencies_num = len(dependencies[DEP_IMAGES_KEY]) protected_tlv_size = (dependencies_num * 16) + TLV_INFO_SIZE # At this point the image is already on the payload, 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: for i in range(dependencies_num): e = STRUCT_ENDIAN_DICT[self.endian] 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) 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: pub = key.get_public_bytes() sha = hashlib.sha256() sha.update(pub) pubbytes = sha.digest() tlv.add('KEYHASH', pubbytes) # `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) cipherkey = enckey._get_public().encrypt( plainkey, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) tlv.add('ENCRSA2048', cipherkey) 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()
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.backends import default_backend import os # the key must be of multiple of 16,we canalso use os.urandom(16) fn() here. key = (b'ashutoshashutosh') # since we are using CRT mode we need iv i.e initialising variable Hence we are using CTR we don't need of padding iv = (b'kumbharekumbhare') detalis = Cipher(algorithms.AES(key), modes.CTR(iv), default_backend()) def encryption(text): # this fn() simply takes a argument which is a simple human readable text and return in encrypted form string = text simple_string = detalis.encryptor() cipher_text = simple_string.update(string) + simple_string.finalize() return cipher_text def encrypt_file(file_name): # this fn() takes a file name extract the data from the file and pass it to the encryption() fil1 = open(file_name, "rb") r = fil1.read() en_text = encryption(r) fil1.close() ####################### # this will creat a same name of file with .enc included in it. fil1 = open(file_name + ".enc", "wb") fil1.write(en_text) os.remove(file_name) fil1.close()
def create(self, key, enckey, dependencies=None, sw_type=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 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 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) 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. if self.flags != 'OTFDEC': sha = hashlib.sha256() sha.update(self.payload) digest = sha.digest() tlv.add('SHA256', digest) print("digest" + str(binascii.hexlify(digest))) if key is not None: tlv.add('KEYHASH', pubbytes) # `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) #value_key=0 #plainkey = value_key.to_bytes(16, byteorder = 'little') print("aes key value" + bytes(plainkey).hex()) if isinstance(enckey, 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, ECDSA256P1Public): cipherkey, mac, pubk = self.ecies_p256_hkdf(enckey, plainkey) enctlv = pubk + mac + cipherkey self.enctlv_len = len(enctlv) tlv.add('ENCEC256', enctlv) address = int(self.address / 16) #address_other = 0 #nonce_other = address_other.to_bytes(8, byteorder = 'little') nonce = address.to_bytes(16, byteorder='big') #print(nonce_other) #perform 2 encryptor #encryptor_other = AES.new(plainkey, AES.MODE_CTR, nonce= nonce_other, initial_value=address); cipher = Cipher(algorithms.AES(plainkey), modes.CTR(nonce), backend=default_backend()) encryptor = cipher.encryptor() img = bytes(self.payload[self.header_size:]) if self.flags == 'OTFDEC': #add bytes to reach 16 bytes print("initial len img" + hex(len(img))) toadd = (16 - len(img) % 16) img += toadd * b'0' #Swap bytes inside 16 bytes block for OTFDEC inarr = numpy.asarray(list(img), numpy.int8).reshape(-1, 16) outarr = numpy.fliplr(inarr) img = bytearray(outarr) #print("modified len img"+hex(len(img))) #encrypt image #img_other = img #encrypted = encryptor_other.encrypt(img_other) #nonce_other = encryptor_other.nonce #print("nonce encryptor"+bytes(nonce_other).hex()) #print("encrypted "+bytes(encrypted[:16]).hex()) img = encryptor.update(img) + encryptor.finalize() #print("img "+bytes(img[:16]).hex()) #img=encrypted #print("img "+bytes(img[:16]).hex()) if self.flags == 'OTFDEC': #Swap bytes inside 16 bytes block for OTFDEC inarr = numpy.asarray(list(img), numpy.int8).reshape(-1, 16) outarr = numpy.fliplr(inarr) img = bytearray(outarr) #print("modify len img"+hex(len(img))) img = img[:-toadd] #print("final len img"+hex(len(img))) #update image self.payload[self.header_size:] = img if self.flags == 'OTFDEC': # add the protected TLV self.payload += prot_tlv.get() sha = hashlib.sha256() sha.update(self.payload) digest = sha.digest() tlv.add('SHA256', digest) #print("otfdec digest"+str(binascii.hexlify(digest))) if key is not None: tlv.add('KEYHASH', pubbytes) # `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) if self.flags == 'PRIMARY_ONLY' and enckey is not None: self.add_header(enckey, protected_tlv_size, True) if self.flags != 'OTFDEC': self.payload += prot_tlv.get() #add encrypted flag if image has been encrypted self.payload += tlv.get() self.check_trailer()
def decryptAES(ciphertext, key, iv): cipher = Cipher(algorithms.AES(key), modes.CTR(iv), default_backend()) decryptor = cipher.decryptor() return decryptor.update(ciphertext) + decryptor.finalize()
def export(self, basePath, extractModules=False, secretSector=None): if self.guessedType == "Kernel11 modules" and extractModules: pos = 0 if not os.path.isdir(os.path.join(basePath, "modules")): os.mkdir(os.path.join(basePath, "modules")) while pos < self.size: size = unpack_from("<I", self.sectionData, pos + 0x104)[0] * 0x200 name = self.sectionData[pos + 0x200:pos + 0x208].decode("ascii") name = "{0}.cxi".format(name[:name.find('\x00')]) with open(os.path.join(basePath, "modules", name), "wb+") as f: f.write(self.sectionData[pos:pos + size]) pos += size with open( os.path.join(basePath, "section{0}.bin".format(self.num)), "wb+") as f: f.write(self.sectionData) elif self.guessedType.startswith("K9L") and secretSector is not None: from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes encKeyX = self.sectionData[:0x10] if self.guessedType[ 3] == '0' else self.sectionData[0x60:0x70] key0x11 = secretSector[:0x10] if self.guessedType[ 3] != '2' else secretSector[0x10:0x20] de = Cipher(algorithms.AES(key0x11), modes.ECB(), backend=default_backend()).decryptor() keyX = de.update(encKeyX) + de.finalize() keyY = self.sectionData[0x10:0x20] ctr = self.sectionData[0x20:0x30] key = unhexlify("{0:032X}".format( keyscrambler(int(hexlify(keyX), 16), int(hexlify(keyY), 16)))) sizeDec = self.sectionData[0x30:0x38].decode("ascii") size = int(sizeDec[:sizeDec.find('\x00')]) data = self.sectionData if 0x800 + size <= self.size: de = Cipher(algorithms.AES(key), modes.CTR(ctr), backend=default_backend()).decryptor() data = b''.join( (self.sectionData[:0x800], de.update(self.sectionData[0x800:0x800 + size]), de.finalize(), self.sectionData[0x800 + size:])) exportP9(basePath, data) with open( os.path.join(basePath, "section{0}.bin".format(self.num)), "wb+") as f: f.write(data) elif self.guessedType == "Kernel9": exportP9(basePath, self.sectionData) with open( os.path.join(basePath, "section{0}.bin".format(self.num)), "wb+") as f: f.write(self.sectionData) else: with open( os.path.join(basePath, "section{0}.bin".format(self.num)), "wb+") as f: f.write(self.sectionData)
def process(self, msg=b""): """ Processa uma mensagem (`bytestring`) enviada pelo SERVIDOR. Retorna a mensagem a transmitir como resposta (`None` para finalizar ligação) """ self.msg_cnt += 1 p = 99494096650139337106186933977618513974146274831566768179581759037259788798151499814653951492724365471316253651463342255785311748602922458795201382445323499931625451272600173180136123245441204133515800495917242011863558721723303661523372572477211620144038809673692512025566673746993593384600667047373692203583 g = 44157404837960328768872680677686802650999163226766694797650810379076416463147265401084491113667624054557335394761604876882446924929840681990106974314935015501571333024773172440352475358750668213444607353872754650805031912866692119819377041901642732455911509867728218394542745330014071040326856846990119719675 pn = dh.DHParameterNumbers(p, g) parameters = pn.parameters(default_backend()) if self.msg_cnt == 1: #envia certificadoA cert_pem = open("Cliente1.p12", "rb").read() self.pk12 = OpenSSL.crypto.load_pkcs12(cert_pem, passphrase=b'1234') self.certificado_cliente = self.pk12.get_certificate() self.PrivateK_assinatura = self.pk12.get_privatekey() cert = OpenSSL.crypto.dump_certificate(FILETYPE_PEM, self.certificado_cliente) return cert if self.msg_cnt == 2: #envia chave publica gx serializada:gxb e recebe certificado servidor #abre o root certificado root_cert1 = open("CA.crt", "rb").read() loadd = OpenSSL.crypto.load_certificate(FILETYPE_PEM, root_cert1) root_cert = OpenSSL.crypto.dump_certificate(FILETYPE_PEM, loadd) self.cert_read = OpenSSL.crypto.load_certificate(FILETYPE_PEM, msg) trusted_cert = OpenSSL.crypto.load_certificate( FILETYPE_PEM, root_cert) # Create and fill a X509Sore with trusted certs store = crypto.X509Store() store.add_cert(trusted_cert) # Create a X590StoreContext with the cert and trusted certs # and verify the the chain of trust store_ctx = crypto.X509StoreContext(store, self.cert_read) result = store_ctx.verify_certificate() if result is None: self.x_client_private_key = parameters.generate_private_key() self.gx = self.x_client_private_key.public_key() self.gxb = self.gx.public_bytes( encoding=serialization.Encoding.DER, format=serialization.PublicFormat.SubjectPublicKeyInfo) self.keyass = self.cert_read.to_cryptography() self.PublicK_assinatura = self.keyass.public_key() return self.gxb else: return False elif self.msg_cnt == 3: #Cliente recebe msg. Que contém gyb e Sigb self.gyb, self.sigb = msg[:-256], msg[-256:] #desserializar chave gyb para gy self.gy = serialization.load_der_public_key( data=self.gyb, backend=default_backend()) ''' :::::::::::::::::::::SIGa(gx,gy):::::::::::::::::::::::::::::::::::: ''' self.assinatura = self.gxb + self.gyb #gxb é a chave da alice enviada, gyb é a chave do bob recebida #vamos fazer a assinatura da chave publica serializada Diffi-Helman da Alice self.signature = self.PrivateK_assinatura.to_cryptography_key( ).sign( self.assinatura, padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256()) ''' VERIFICAR ASSINATURA ''' #self.sigb é a assinatura do servidor, recebida na msg try: self.PublicK_assinatura.verify( # self.sigb, self.assinatura, padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256()) self.shared_key = self.x_client_private_key.exchange(self.gy) except (InvalidSignature): print("Oops! Não se verificou a assinatura.") self.derived_key = HKDF(algorithm=hashes.SHA256(), length=32, salt=None, info=b'handshake data', backend=default_backend()).derive( self.shared_key) self.key1 = self.derived_key[:16] self.key2 = self.derived_key[16:] print('Input message to send (empty to finish)') new_msg = input().encode() iv = os.urandom(16) cipher = Cipher(algorithms.AES(self.key1), modes.CTR(iv), default_backend()) encryptor = cipher.encryptor() ct = encryptor.update(new_msg) + encryptor.finalize() # mac h = hmac.HMAC(self.key2, hashes.SHA256(), default_backend()) h.update(ct) tag = h.finalize() new_msg2 = (iv + ct) + tag + self.signature return new_msg2 if len(new_msg) > 0 else None elif self.msg_cnt > 3: if msg: criptoIV, tag = msg[:-32], msg[-32:] iv, cripto = criptoIV[:16], criptoIV[16:] h = hmac.HMAC(self.key2, hashes.SHA256(), default_backend()) h.update(cripto) try: h.verify(tag) cipher = Cipher(algorithms.AES(self.key1), modes.CTR(iv), default_backend()) decryptor = cipher.decryptor() msg = decryptor.update(cripto) + decryptor.finalize() print('Received (%d): %r' % (self.msg_cnt, msg.decode())) except (InvalidSignature): print( "Oops! Não se verificou a integridade do criptograma." ) print('Input message to send (empty to finish)') new_msg = input().encode() iv = os.urandom(16) cipher = Cipher(algorithms.AES(self.key1), modes.CTR(iv), default_backend()) encryptor = cipher.encryptor() ct = encryptor.update(new_msg) + encryptor.finalize() # mac h = hmac.HMAC(self.key2, hashes.SHA256(), default_backend()) h.update(ct) tag = h.finalize() # como mandar tag para o outro lado?? new_msg2 = (iv + ct) + tag return new_msg2 if len(new_msg) > 0 else None
def create(self, key, public_key_format, enckey, dependencies=None, sw_type=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 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 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) 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 postShares(idTry): session = Session() userId = request.args.get('userId') currentClient = session.query(models.models.Client).get(int(userId)) currentTry = session.query(models.models.TryEntity)\ .with_for_update(of=models.models.Client)\ .join(models.models.TryEntity.clients)\ .filter(models.models.TryEntity.id==int(idTry))\ .first() if currentTry == None: session.close() return 'No try with this id', 400 if currentTry.currentRound != 4: session.close() return 'Try is not in round 4', 400 if currentClient == None: return "Client not found", 400 # request.data (=maskedVector) is already in base64 format shares = request.json idClients = [client['id'] for client in shares] for client in currentTry.clients: if client.id in idClients: share = [share for share in shares if share['id'] == client.id][0] if share['suSKShare']: suSKShares = json.loads( str( base64.b64decode( client.suSKSharesBase64.encode('utf8')), 'utf8')) suSKShares['shares'].append(share['suSKShare']) client.suSKSharesBase64 = str( base64.b64encode(json.dumps(suSKShares).encode('utf8')), 'utf8') elif share['buShare']: buShares = json.loads( str(base64.b64decode(client.buSharesBase64.encode('utf8')), 'utf8')) buShares['shares'].append(share['buShare']) client.buSharesBase64 = str( base64.b64encode(json.dumps(buShares).encode('utf8')), 'utf8') currentClient.giveShares = True session.commit() session = Session() currentTry = session.query(models.models.TryEntity)\ .with_for_update(of=models.models.Client)\ .join(models.models.TryEntity.clients)\ .filter(models.models.TryEntity.id==int(idTry))\ .first() # Check if we can compute the global sum now readyClients = [] for client in currentTry.clients: if client.giveShares: readyClients.append(client) if len(readyClients) >= currentTry.threshold: # COMPUTE GLOBAL SUM globalSum = np.zeros(CLIENT_SECRET_SIZE, dtype=np.dtype('d')) # AES CTR init ctr = modes.CTR(b'\x00' * 16) initialPlaintext = b'\x00' * BYTES_NUMBER * CLIENT_SECRET_SIZE for client in currentTry.clients: if client.maskedVectorBase64: r = base64.decodebytes( client.maskedVectorBase64.encode('utf8')) maskedVector = np.frombuffer(r, dtype=np.dtype('d')) # Decode buShares using shamir buShares = json.loads( str(base64.b64decode(client.buSharesBase64.encode('utf8')), 'utf8')) bu = shamir.recover_secret(shamir.from_base64(buShares)) # Use AES CTR To compute masked vector pu cipherPuv = Cipher(algorithms.AES(bu), ctr, backend=default_backend()) encryptor = cipherPuv.encryptor() ct = encryptor.update(initialPlaintext) + encryptor.finalize() pu = np.frombuffer(ct, dtype=np.dtype('i4')) globalSum = globalSum + maskedVector - pu else: # Import su client secret key to regenerated masked puv suSKShares = json.loads( str( base64.b64decode( client.suSKSharesBase64.encode('utf8')), 'utf8')) su = shamir.recover_secret(shamir.from_base64(suSKShares)) # Parse client Su public key SuSK = serialization.load_pem_private_key( su, None, default_backend()) for clientToRecover in currentTry.clients: if clientToRecover.id != client.id: publicKey = serialization.load_pem_public_key( clientToRecover.publicKeySuPEM.encode('utf-8'), default_backend()) # Create shared key sharedKey = SuSK.exchange(ec.ECDH(), publicKey) # Perform key derivation derivedKey = HKDF( algorithm=hashes.SHA256(), length=32, salt=None, info=None, backend=default_backend()).derive(sharedKey) # **** COMPUTE Puv (client shared mask) cipherPuv = Cipher(algorithms.AES(derivedKey), ctr, backend=default_backend()) encryptor = cipherPuv.encryptor() # Generate random bytes to fill Puv array ct = encryptor.update( initialPlaintext) + encryptor.finalize() # Convert random bytes to a numpy array using unsigned BYTES_NUMBER int puv = np.frombuffer(ct, dtype=np.dtype('i4')) # Compute delta for current client id delta = 1 if clientToRecover.id < client.id else -1 globalSum = globalSum + delta * puv globalMean = globalSum / len(readyClients) accuracy = MODEL.test() app.logger.info( 'Server accuracy before training (with test values): ' + str(accuracy)) MODEL.updateFromNumpyFlatArray(globalMean) accuracy = MODEL.test() app.logger.info('Server accuracy after training (with test values): ' + str(accuracy)) #timer end Metrics.addTime("End") Metrics.to_csv() # Finish current try currentTry.currentRound = -1 session.commit() return '', 200, {'ContentType': 'application/json'}
def words(): cipher = Cipher(algorithms.AES(KEY), modes.CTR(IV), backend=backend) e = cipher.encryptor() while True: v = e.update(b'\x00\x00') yield v[0] + 256 * v[1] + 1
# Obtain encrypted message from the server data = server.get_encrypted_message() iv = data["IV"] ciphertext = data["Ciphertext"] if shared_key == None: exit() ### Task 4 ### # Use HKDF to convert the shared key into an aes key # This HKDF uses Sha256, Length 32 (256 bits), no salt, 'ecdhexercise' info. from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.hkdf import HKDF hkdf = HKDF(algorithm=hashes.SHA256(), length=32, salt=None, info=b'ecdhexercise', backend=default_backend()) aes_key = hkdf.derive(shared_key) ### Task 5 ### # Use AES CTR to decrypt the message with the IV and aes key cipher = Cipher(algorithms.AES(aes_key), modes.CTR(iv), backend=default_backend()) decryptor = cipher.decryptor() message = decryptor.update(ciphertext) + decryptor.finalize() if message != None: print(message.decode("UTF-8"))
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
class TestCAST5ModeCTR(object): test_CTR = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "CAST5"), ["cast5-ctr.txt"], lambda key, **kwargs: algorithms.CAST5(binascii.unhexlify( (key))), lambda iv, **kwargs: modes.CTR(binascii.unhexlify(iv)))
key = b'\xb4\xdd$4\xbb\xa4\xf4\x8d\x9c\x17\xfb\x1b\xd4Q?\xf8' message = b"this is a 32 byte secret message" cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=backend) encryptor = cipher.encryptor() ciphertext = encryptor.update(message) + encryptor.finalize() print(server.decrypt_aes_ecb(key, ciphertext)) ### Counter Mode ### # A new 128-bit key for AES key = b'>SMNs^\xc0\xed\xc1\xc0SS\x9d\x8f&\x02' message = b"This secret message is an arbitrary length, as CTR mode operates as a stream cipher." nonce = os.urandom(16) cipher = Cipher(algorithms.AES(key), modes.CTR(nonce), backend=backend) encryptor = cipher.encryptor() ciphertext = encryptor.update(message) + encryptor.finalize() print(server.decrypt_aes_ctr(key, nonce + ciphertext)) ### Key Exchange ### # Get server parameters (g,n) parameters = server.get_parameters() # Generate our private key (a) private_key = parameters.generate_private_key() # Generate a public key using our private key (g^a mod n) public_key = private_key.public_key() # Get server public key (g^b mod n)