How do I encrypt and decrypt a string in python?

后端 未结 8 1421
忘了有多久
忘了有多久 2020-11-28 05:36

I have been looking for sometime on how to encrypt and decrypt a string. But most of it is in 2.7 and anything that is using 3.2 is not letting me print it or add it to a st

相关标签:
8条回答
  • 2020-11-28 05:52

    You may use Fernet as follows:

    from cryptography.fernet import Fernet
    key = Fernet.generate_key()
    f = Fernet(key)
    encrypt_value = f.encrypt(b"YourString")
    f.decrypt(encrypt_value)
    
    0 讨论(0)
  • 2020-11-28 05:58

    Try this:

    Python Cryptography Toolkit (pycrypto) is required

    $ pip install pycrypto
    

    Code:

    from Crypto.Cipher import AES
    from base64 import b64encode, b64decode
    
    
    class 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 eiusmod
    tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
    consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
    cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
    proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
    consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
    cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
    proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
    consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
    cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
    proident, 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}')
    
    0 讨论(0)
  • 2020-11-28 06:04

    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.

    0 讨论(0)
  • 2020-11-28 06:08

    Although its very old, but I thought of sharing another idea to do this:

    from Crypto.Cipher import AES    
    from Crypto.Hash import SHA256
    
    password = ("anything")    
    hash_obj = SHA256.new(password.encode('utf-8'))    
    hkey = hash_obj.digest()
    
    def encrypt(info):
        msg = info
        BLOCK_SIZE = 16
        PAD = "{"
        padding = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PAD
        cipher = AES.new(hkey, AES.MODE_ECB)
        result = cipher.encrypt(padding(msg).encode('utf-8'))
        return result  
    
    msg = "Hello stackoverflow!"
    cipher_text = encrypt(msg)
    print(cipher_text)
    
    def decrypt(info):
        msg = info
        PAD = "{"
        decipher = AES.new(hkey, AES.MODE_ECB)
        pt = decipher.decrypt(msg).decode('utf-8')
        pad_index = pt.find(PAD)
        result = pt[: pad_index]
        return result
    
    plaintext = decrypt(cipher_text)
    print(plaintext)
    

    Outputs:

    > b'\xcb\x0b\x8c\xdc#\n\xdd\x80\xa6|\xacu\x1dEg;\x8e\xa2\xaf\x80\xea\x95\x80\x02\x13\x1aem\xcb\xf40\xdb'
    
    > Hello stackoverflow!
    
    0 讨论(0)
  • 2020-11-28 06:10

    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 Fernet
    key = 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)
    
    0 讨论(0)
  • 2020-11-28 06:12

    For Decryption:

         def decrypt(my_key=KEY, my_iv=IV, encryptText=encrypttext):
    
            key = binascii.unhexlify(my_key)
            iv = binascii.unhexlify(my_iv)
            encryptor = AES.new(key, AES.MODE_CBC, iv, segment_size=128)  # Initialize encryptor
            result = encryptor.decrypt(binascii.a2b_hex(encryptText))
            padder = PKCS7Padder()
            decryptText=padder.decode(result)  
    
               return {
              "plain": encryptText,
              "key": binascii.hexlify(key),
              "iv": binascii.hexlify(iv),
              "decryptedTest": decryptText
    }
    
    0 讨论(0)
提交回复
热议问题