How do I encrypt and decrypt a string in python?

后端 未结 8 1462
忘了有多久
忘了有多久 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 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!
    

提交回复
热议问题