How do I encrypt and decrypt a string in python?
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.
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)
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
.
You can do this easily by using the library cryptocode
. Here is how you install:
pip install cryptocode
Encrypting a message (example code):
import cryptocode
encoded = cryptocode.encrypt("mystring","mypassword")
## And then to decode it:
decoded = cryptocode.decrypt(encoded, "mypassword")
Documentation can be found here
Try this:
Python Cryptography Toolkit (pycrypto) is required
$ pip install pycrypto
pycrypto
package is outdated and has not been maintained since 2014.
There is a drop-in replacement package called pycryptodome
.
$ pip install pycryptodome
And the code below flawlessly works on python 3.8
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.encode('utf-8'), 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}')