class TestTripleDESModeOFB(object): test_KAT = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "3DES", "OFB"), [ "TOFBpermop.rsp", "TOFBsubtab.rsp", "TOFBvarkey.rsp", "TOFBvartext.rsp", "TOFBinvperm.rsp", ], lambda keys, **kwargs: algorithms.TripleDES(binascii.unhexlify(keys)), lambda iv, **kwargs: modes.OFB(binascii.unhexlify(iv)), ) test_MMT = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "3DES", "OFB"), [ "TOFBMMT1.rsp", "TOFBMMT2.rsp", "TOFBMMT3.rsp", ], lambda key1, key2, key3, **kwargs: algorithms.TripleDES( binascii.unhexlify(key1 + key2 + key3) ), lambda iv, **kwargs: modes.OFB(binascii.unhexlify(iv)), )
def AESDecrypt(sym_key, iv, msg): cipher = Cipher(algorithms.AES(sym_key), modes.OFB(iv), backend=default_backend()) decryptor = cipher.decryptor() plaintext = decryptor.update(msg) + decryptor.finalize() return plaintext
def TripleDES(): backend = default_backend() key = os.urandom(16) iv = os.urandom(8) user_input = input('Please enter a message: ') cipher = Cipher(algorithms.TripleDES(key), modes.OFB(iv), backend=default_backend()) encryptor = cipher.encryptor() user_input_byt = str.encode(user_input) ct = encryptor.update(user_input_byt) + encryptor.finalize() print('The 3DES key is {}'.format(ct)) decryptor = cipher.decryptor() answer = decryptor.update(ct) + decryptor.finalize() print('The decrypted message: {}'.format(answer)) a = input('Would you like to know more about 3DES? (yes/no) ') if a == 'yes': print('Triple DES (Data Encryption Standard), sometimes referred to as 3DES, is a block cipher standardized by NIST. Triple DES has known crypto-analytic flaws, however none of them currently enable a practical attack. Nonetheless, Triple DES is not recommended for new applications because it is incredibly slow; old applications should consider moving away from it.') print(' ') print('For this 3DES implenebtation, it uses OFB Mode. OFB (Output Feedback) is a mode of operation for block ciphers. It transforms a block cipher into a stream cipher.') print(' ') print('Becase it is a stream cipher, it does not need padding.') print(' ') print('iv = initialization_vector (bytes) – Must be random bytes. They do not need to be kept secret and they can be included in a transmitted message. Must be the same number of bytes as the block_size of the cipher. Do not reuse an initialization_vector with a given key.') print(' ') print('key (bytes) – The secret key. This must be kept secret.') elif a == 'no': print('That\'s great.')
def encryptSendMsg(destination_public_key, sender_private_key, input_plaintext): # generate a symetric key key_sym = keygen() public_key = None private_key = None # encrypt key_sym with reciever's public key public_key = destination_public_key cipher_key_sym = public_key.encrypt( key_sym, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), label=None)) # encrypt file with key_sym iv = os.urandom(16) cipher = Cipher(algorithms.AES(key_sym), modes.OFB(iv), backend=default_backend()) encryptor = cipher.encryptor() ciphertext = encryptor.update(input_plaintext) + encryptor.finalize() # sign the file with sender's private key private_key = sender_private_key signer = private_key.signer( padding.PSS(mgf=padding.MGF1(hashes.SHA1()), salt_length=padding.PSS.MAX_LENGTH), hashes.SHA1()) signer.update(bytes(ciphertext)) signature = signer.finalize() # compose the cipher text: iv|key_sym|signature|file return bytes(iv) + bytes(cipher_key_sym) + bytes(signature) + bytes( ciphertext)
def __init__(self, algorithm=None, cipher_mode=None, initialization_vector=None, **kwargs): """Initializes a decrypter. Args: algorithm (Optional[Cryptography.CipherAlgorithm]): cipher algorithm. cipher_mode (Optional[str]): cipher mode. initialization_vector (Optional[bytes]): initialization vector. kwargs (dict): keyword arguments depending on the decrypter. Raises: ValueError: if the initialization_vector is required and not set. """ if (cipher_mode != definitions.ENCRYPTION_MODE_ECB and not initialization_vector): raise ValueError('Missing initialization vector.') if cipher_mode == definitions.ENCRYPTION_MODE_CBC: mode = modes.CBC(initialization_vector) elif cipher_mode == definitions.ENCRYPTION_MODE_CFB: mode = modes.CFB(initialization_vector) elif cipher_mode == definitions.ENCRYPTION_MODE_ECB: mode = modes.ECB() elif cipher_mode == definitions.ENCRYPTION_MODE_OFB: mode = modes.OFB(initialization_vector) backend = backends.default_backend() cipher = ciphers.Cipher(algorithm, mode=mode, backend=backend) super(CryptographyBlockCipherDecrypter, self).__init__() self._algorithm = algorithm self._cipher_context = cipher.decryptor()
def create_cipher(mode_selection, key, iv): if mode_selection == "1": cipher = Cipher( algorithm=algorithms.AES(key), mode=modes.CBC(iv), backend=backend) elif mode_selection == "2": cipher = Cipher( algorithm=algorithms.AES(key), mode=modes.ECB(), backend=backend) elif mode_selection == "3": cipher = Cipher( algorithm=algorithms.AES(key), mode=modes.CTR(iv), backend=backend) elif mode_selection == "4": cipher = Cipher( algorithm=algorithms.AES(key), mode=modes.OFB(iv), backend=backend) elif mode_selection == "5": cipher = Cipher( algorithm=algorithms.AES(key), mode=modes.CFB(iv), backend=backend) return cipher
def pyca_tests(): from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.primitives.asymmetric import rsa, padding Cipher( algorithms.TripleDES(key), modes.CBC(iv)) # Noncompliant {{Use secure mode and padding scheme.}} # ^^^^^^^^^^^^^ Cipher(algorithms.Blowfish(key), modes.GCM(iv)) # Compliant Cipher() # Compliant args = [] Cipher(algorithms.Blowfish(key), *args) # Compliant Cipher(algorithms.Blowfish(key), modes.ECB()) # Noncompliant Cipher(algorithms.AES(key), modes.CBC(iv)) # Noncompliant Cipher(mode=modes.CBC(iv), algorithm=algorithms.AES(key)) # Noncompliant Cipher(algorithms.AES(key), modes.OFB(iv)) # Compliant Cipher(algorithms.AES(key), modes.ECB()) # Noncompliant private_key = rsa.generate_private_key() public_key = private_key.public_key() ciphertext = public_key.encrypt(message, padding.OAEP()) private_key.decrypt(ciphertext, padding.OAEP()) # Compliant public_key.encrypt(message, padding.PKCS1v15()) # Noncompliant # ^^^^^^^^^^^^^^^^^^ public_key.encrypt(padding=padding.PKCS1v15(), plaintext=message) # Noncompliant private_key.decrypt(ciphertext, padding.PKCS1v15()) # Noncompliant private_key.decrypt(padding=padding.PKCS1v15(), ciphertext=ciphertext) # Noncompliant print(padding.PKCS1v15()) # OK
def encrypt_file(backend_encrypt, file_to_encrypt_name, encrypted_file_name): cipher = Cipher(algorithm=algorithms.AES(key), mode=modes.OFB(iv), backend=backend_encrypt) encryptor = cipher.encryptor() input_file = open(file_to_encrypt_name, "rb") output_file = open(encrypted_file_name, "wb") data = bytearray(blocksize) totalsize = 0 while True: # read block from source file num = input_file.readinto(data) # adjust totalsize totalsize += num # check if full block read if num == blocksize: ciphertext = encryptor.update(bytes(data)) # write full block to destination output_file.write(ciphertext) else: padder = padding.PKCS7(128).padder() padded_data = padder.update(bytes(data[0:num])) + padder.finalize() ciphertext = encryptor.update( bytes(padded_data)) + encryptor.finalize() # write subarray to destination and break loop output_file.write(ciphertext) print("Encrypted file: ", file_to_encrypt_name) print("Encrypted to: ", encrypted_file_name) break
def decode_file(input_filename, output_filename, backend_decode): prefix_input_file = input_filename.split('.')[0] # output_file_key = output_file_name.split('.') output_key_file = prefix_input_file + ".key" key_file = open(output_key_file, "rb") key_decode = bytearray(blocksize) key_file.readinto(key_decode) output_file_iv = output_filename.split('.') output_iv_file = prefix_input_file + ".iv" iv_file = open(output_iv_file, "rb") iv_decode = bytearray(blocksize) iv_file.readinto(iv_decode) input_file = open(input_filename, "rb") output_file = open(output_filename, "wb") # create a mutable array to hold the bytes data = bytearray(blocksize) totalsize = 0 cipher = Cipher(algorithm=algorithms.AES(key), mode=modes.OFB(iv), backend=backend_decode) decryptor = cipher.decryptor() while True: # read block from source file num = input_file.readinto(data) # adjust totalsize totalsize += num # check if full block read if num == blocksize: plaintext = decryptor.update(bytes(data)) last_bytes = plaintext.hex()[-2:] num_padding_bytes = int(last_bytes, 16) # make sure block is padded correctly when we depad valid = 0 if num_padding_bytes <= 16: valid = 1 left = -4 for i in range(num_padding_bytes - 1): if num_padding_bytes != int(plaintext.hex()[left:left + 2], 16): valid = 0 left = left - 2 if valid: unpadder = padding.PKCS7(128).unpadder() unpadded_data = unpadder.update( plaintext) + unpadder.finalize() plaintext = decryptor.finalize() output_file.write(unpadded_data) print("decrypted file is in decrypted.txt") break output_file.write(plaintext)
def parse_encrypted(self, part_len, data): if part_len != len(data): raise ProtocolError("Enc pkt size disaggrees with header.") if len(data) <= 38: raise ProtocolError("Truncated encrypted part.") uname_len, data = struct.unpack("!H", data[:2])[0], data[2:] if len(data) <= uname_len + 36: raise ProtocolError("Truncated encrypted part.") uname, data = data[:uname_len].decode(), data[uname_len:] if uname not in self.auth_db: raise ProtocolError("Couldn't decrypt, unknown user '%s'" % uname) iv, data = data[:16], data[16:] password = self.auth_db[uname].encode() key = sha256(password).digest() pad_bytes = 16 - (len(data) % 16) data += b'\0' * pad_bytes cipher = Cipher(algorithms.AES(key), modes.OFB(iv), backend=self.crypto_backend) decryptor = cipher.decryptor() data = decryptor.update(data) data = data[:-pad_bytes] tag, data = data[:20], data[20:] tag2 = sha1(data).digest() if not self._hashes_match(tag, tag2): raise ProtocolError("Bad checksum on enc pkt for '%s'" % uname) return data
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 deriveKey(shared_secret, hashAlg, BlukEnc): if hashAlg == "sha256": hashAlg = hashes.SHA256() else: hashAlg = hashes.SHA3_384() salt = bytes(bytearray(shared_secret)[0:16]) key = HKDF(algorithm=hashAlg, length=24, salt=salt, info=b'handshake data', backend=default_backend()).derive(shared_secret) iv = bytearray(shared_secret)[0:16] if BlukEnc == "AES-256-CBC": BlukEnc = modes.CBC(iv) else: BlukEnc = modes.OFB(iv) cipher = Cipher(algorithms.AES(key), BlukEnc, default_backend()) print("Symmetric key has been generated successfully...") return cipher
def test_ofb(self, backend): with pytest.raises(ValueError): Cipher( algorithms.AES(b"\x00" * 16), modes.OFB(b"abc"), backend, )
def aes_ofb_timer(test_vectors): """Encrypts (AES-OFB) each element of test_vector and returns a list of tuples with (encryption time, decryption time) """ timelist = [] for vector in test_vectors: #test_vector elements are of byte type #key generation, we opted for generating our own keys and not using the provided at the test vectors key = secrets.token_bytes( 32 ) #secrets provides the most secure pseudo-random function the os has iv = secrets.token_bytes( 32) #iv for OFB, must be the same size as the block size #print(key) #print(iv) #end of key generation #creating a cipher object aes = algorithms.AES(key) aes.block_size = 256 cipher = Cipher(aes, modes.OFB(iv), backend=default_backend()) encryptor = cipher.encryptor() #encryption begins start_e = timer() ciphertext = encryptor.update(vector) + encryptor.finalize() end_e = timer() #print(len(ciphertext.hex())) #encryption ends -this is the fragment we should time for encryption time #print("ciphertext: " + str(ciphertext.hex())) decryptor = cipher.decryptor() #decryption begins start_d = timer() plaintext_d = decryptor.update(ciphertext) + decryptor.finalize() end_d = timer() #decryption ends -this is the fragment we should time for decryption time #print("Deciphered text: "+ str(plaintext_d)) timelist.append((end_e - start_e, end_d - start_d)) return timelist
def get_cipher(key, method, op, iv): if method == 'bypass': return bypass() if method in ('salsa20', 'chacha20', 'chacha20-ietf'): return Salsa20Crypto(method, key, iv, op) elif method == 'rc4-md5': md5 = hashlib.md5() md5.update(key) md5.update(iv) key = md5.digest() method = 'rc4' cipher = None if method.startswith('rc4'): pass elif method.endswith('ctr'): mode = modes.CTR(iv) elif method.endswith('ofb'): mode = modes.OFB(iv) elif method.endswith('cfb'): mode = modes.CFB(iv) else: raise ValueError('operation mode "%s" not supported!' % method.upper()) if method.startswith('rc4'): cipher = Cipher(algorithms.ARC4(key), None, default_backend()) elif method.startswith('aes'): cipher = Cipher(algorithms.AES(key), mode, default_backend()) elif method.startswith('camellia'): cipher = Cipher(algorithms.Camellia(key), mode, default_backend()) else: raise ValueError('crypto algorithm "%s" not supported!' % method.upper()) return cipher.encryptor() if op else cipher.decryptor()
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)
class TestCAST5ModeOFB(object): 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)), )
class TestSEEDModeOFB(object): test_OFB = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "SEED"), ["seed-ofb.txt"], lambda key, **kwargs: algorithms.SEED(binascii.unhexlify((key))), lambda iv, **kwargs: modes.OFB(binascii.unhexlify(iv)) )
class TestSM4ModeOFB(object): test_ofb = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "SM4"), ["draft-ribose-cfrg-sm4-10-ofb.txt"], lambda key, **kwargs: algorithms.SM4(binascii.unhexlify((key))), lambda iv, **kwargs: modes.OFB(binascii.unhexlify(iv)), )
class TestIDEAModeOFB: test_ofb = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "IDEA"), ["idea-ofb.txt"], lambda key, **kwargs: algorithms.IDEA(binascii.unhexlify((key))), lambda iv, **kwargs: modes.OFB(binascii.unhexlify(iv)), )
class TestCamelliaModeOFB(object): test_OFB = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "Camellia"), ["camellia-ofb.txt"], lambda key, **kwargs: algorithms.Camellia(binascii.unhexlify(key)), lambda iv, **kwargs: modes.OFB(binascii.unhexlify(iv)), )
def AESEncrypt(msg, aes_key, iv): #generate a aes key , iv and use it to encrypt the above msg cipher = Cipher(algorithms.AES(aes_key), modes.OFB(iv), backend=default_backend()) encryptor = cipher.encryptor() ciphertext = encryptor.update(msg) + encryptor.finalize() return ciphertext
class TestBlowfishModeOFB: test_ofb = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "Blowfish"), ["bf-ofb.txt"], lambda key, **kwargs: algorithms.Blowfish(binascii.unhexlify(key)), lambda iv, **kwargs: modes.OFB(binascii.unhexlify(iv)), )
def GenerateAsymmKey(BlukEnc,iv,key): if BlukEnc == "AES-256-CBC": BlukEnc = modes.CBC(iv) else: BlukEnc = modes.OFB(iv) cipher = Cipher(algorithms.AES(key), BlukEnc, default_backend()) print(bcolors.succ+"Symmetric key has been generated successfully..."+bcolors.ENDC) return cipher
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 generate_aes_ofb(key, nonce_or_iv): backend = default_backend() iv = nonce_or_iv cipher = Cipher(algorithms.AES(key), modes.OFB(iv), backend=backend) def do_computation(msg: bytes): encryptor = cipher.encryptor() ct = encryptor.update(msg) + encryptor.finalize() return do_computation
def endAuction(self): print("end") self.live = False repoPrivKey = self.repository.getPrivKey() if len(self.bids) > 0: lastBlock = bytes(self.bids[len(self.bids) - 1]) else: lastBlock = self.iv digest = hashes.Hash(hashes.SHA256(), backend=default_backend()) digest.update(lastBlock) checksum = digest.finalize() sealBid = Bid({ "auction": self.serialNum, "user": "", "amount": str(-1), "time": datetime.strptime(str(datetime.now()), '%Y-%m-%d %H:%M:%S.%f') }) check_cyphered = repoPrivKey.sign(checksum, padding.PKCS1v15(), utils.Prehashed(hashes.SHA256())) sealBid.addCheckSum(check_cyphered) serializedBid = pickle.dumps(sealBid) thisIv = checksum[0:16] cipher = Cipher(algorithms.AES(self.key), modes.OFB(thisIv), backend=default_backend()) encryptor = cipher.encryptor() ct = encryptor.update(serializedBid) + encryptor.finalize() xorValue = [] for i in range(len(ct)): xorValue.append(ct[i] ^ thisIv[i % len(thisIv)]) self.bids.append(xorValue) file = open("repositoryLog.txt", "a") file.write("<<BIDCHAIN>> " + str(datetime.now()) + " -- ") file.write( json.dumps(self.bids) + " KEY->" + base64.b64encode(self.key).decode("utf-8") + " IV->" + base64.b64encode(self.iv).decode("utf-8")) file.write("\n") file.close()
def modeObject(mode): if (mode == 1): return modes.CBC(iv) #requires padding elif (mode == 2): return modes.OFB(iv) #stream cipher elif (mode == 3): return modes.CFB(iv) #stream cipher elif (mode == 4): return modes.CTR(iv) #stream cipher elif (mode == 5): return modes.ECB() #requires padding
def encrypt(self, folder_path, file_name): #if first access to shared folder then the user needs to enter the folder password if self.firstAccessToFolder(folder_path): self.enterFolderPwd(folder_path) tag = None #generate random 256 bit data encryption key dek = os.urandom(32) #generate random 128 bit IV iv = os.urandom(16) algorithm = algorithms.AES(dek) algo_name = self.getAlgoName(folder_path + "/" + file_name) #set Cipher to chosen mode if algo_name == "aes": mode = modes.GCM(iv) else: mode = modes.OFB(iv) algorithm = algorithms.Camellia(dek) #construct AES_GCM cipher with given dek and the random IV encryptor = Cipher(algorithm, mode, backend=default_backend()).encryptor() if algo_name == "aes": #get associated data stats = os.stat(file_name) aad = str(stats.st_size) #authenticate associated data encryptor.authenticate_additional_data(aad.encode()) #PUT: Encrypt a file into secure folder with open(file_name, "rb") as source, open( path_secure + folder_path + "/" + file_name, "wb+") as sink: byte = source.read(chunk_size) while byte: sink.write(encryptor.update(byte)) # Do stuff with byte byte = source.read(chunk_size) source.close() sink.close() encryptor.finalize() if algo_name == "aes": tag = encryptor.tag #store data needed for decryption of the file self.addDek(folder_path + "/" + file_name, dek, tag, iv)
def decrypt(self, file_name): #get folder path by eliminating file name from file path folder_path = "/".join(file_name.split("/")[0:-1]) folder_path = folder_path.replace("./secure/", "") #if first access to folder then the user has to enter folder password #used for shared folders if self.firstAccessToFolder(folder_path): self.enterFolderPwd(folder_path) #get iv, dek, algo_name and authentication tag iv = self.getIv(file_name) dek = self.getDek(file_name) algo_name = self.getAlgoName(file_name) tag = self.getTag(file_name) algorithm = algorithms.Camellia(dek) mode = modes.OFB(iv) if algo_name == "aes": #get associated data stats = os.stat(path_secure + file_name) aad = str(stats.st_size) algorithm = algorithms.AES(dek) mode = modes.GCM(iv, tag) #construct AES_GCM cipher with given dek and the generated iv decryptor = Cipher(algorithm, mode, backend=default_backend()).decryptor() if algo_name == "aes": #try to authenticate associated data #if authentication fails print warning and return None try: decryptor.authenticate_additional_data(aad.encode()) except: print( "File could not be authenticated. Something must be wrong.\nFile will not be decrypted." ) return None #GET: Encrypt a file into secure folder with open(path_secure + file_name, "rb") as source, open(path_unsecure + file_name, "wb+") as sink: byte = source.read(chunk_size) while byte: sink.write(decryptor.update(byte)) # Do stuff with byte. byte = source.read(chunk_size) source.close() sink.close() decryptor.finalize()