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 string.
So what I'm trying to do is the following:
mystring = "Hello stackoverflow!"
encoded = encode(mystring,"password")
print(encoded)
jgAKLJK34t3g (a bunch of random letters)
decoded = decode(encoded,"password")
print(decoded)
Hello stackoverflow!
Is there anyway of doing this, using python 3.X and when the string is encoded it's still a string, not any other variable type.
解决方案
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_CBC, '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_CBC, '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.