How do I encrypt and decrypt a string in python? How do I encrypt and decrypt a string in python? python python

How do I encrypt and decrypt a string in python?


I had troubles compiling all the most commonly mentioned cryptography libraries on my Windows 7 system and for Python 3.5.

This is the solution that finally worked for me.

from cryptography.fernet import Fernetkey = Fernet.generate_key() #this is your "password"cipher_suite = Fernet(key)encoded_text = cipher_suite.encrypt(b"Hello stackoverflow!")decoded_text = cipher_suite.decrypt(encoded_text)


Take a look at PyCrypto. It supports Python 3.2 and does exactly what you want.

From their pip website:

>>> from Crypto.Cipher import AES>>> obj = AES.new('This is a key123', AES.MODE_CFB, 'This is an IV456')>>> message = "The answer is no">>> ciphertext = obj.encrypt(message)>>> ciphertext'\xd6\x83\x8dd!VT\x92\xaa`A\x05\xe0\x9b\x8b\xf1'>>> obj2 = AES.new('This is a key123', AES.MODE_CFB, 'This is an IV456')>>> obj2.decrypt(ciphertext)'The answer is no'

If you want to encrypt a message of an arbitrary size use AES.MODE_CFB instead of AES.MODE_CBC.


Try this:

Python Cryptography Toolkit (pycrypto) is required

$ pip install pycrypto

Code:

from Crypto.Cipher import AESfrom base64 import b64encode, b64decodeclass Crypt:    def __init__(self, salt='SlTKeYOpHygTYkP3'):        self.salt = salt.encode('utf8')        self.enc_dec_method = 'utf-8'    def encrypt(self, str_to_enc, str_key):        try:            aes_obj = AES.new(str_key, AES.MODE_CFB, self.salt)            hx_enc = aes_obj.encrypt(str_to_enc.encode('utf8'))            mret = b64encode(hx_enc).decode(self.enc_dec_method)            return mret        except ValueError as value_error:            if value_error.args[0] == 'IV must be 16 bytes long':                raise ValueError('Encryption Error: SALT must be 16 characters long')            elif value_error.args[0] == 'AES key must be either 16, 24, or 32 bytes long':                raise ValueError('Encryption Error: Encryption key must be either 16, 24, or 32 characters long')            else:                raise ValueError(value_error)    def decrypt(self, enc_str, str_key):        try:            aes_obj = AES.new(str_key.encode('utf8'), AES.MODE_CFB, self.salt)            str_tmp = b64decode(enc_str.encode(self.enc_dec_method))            str_dec = aes_obj.decrypt(str_tmp)            mret = str_dec.decode(self.enc_dec_method)            return mret        except ValueError as value_error:            if value_error.args[0] == 'IV must be 16 bytes long':                raise ValueError('Decryption Error: SALT must be 16 characters long')            elif value_error.args[0] == 'AES key must be either 16, 24, or 32 bytes long':                raise ValueError('Decryption Error: Encryption key must be either 16, 24, or 32 characters long')            else:                raise ValueError(value_error)

Usage:

        test_crpt = Crypt()        test_text = """Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmodtempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodoconsequat. Duis aute irure dolor in reprehenderit in voluptate velit essecillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmodtempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodoconsequat. Duis aute irure dolor in reprehenderit in voluptate velit essecillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmodtempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodoconsequat. Duis aute irure dolor in reprehenderit in voluptate velit essecillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum."""        test_key = 'MyKey4TestingYnP'        test_enc_text = test_crpt.encrypt(test_text, test_key)        test_dec_text = test_crpt.decrypt(test_enc_text, test_key)        print(f'Encrypted:{test_enc_text}  Decrypted:{test_dec_text}')