Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 708
David Avatar asked Dec 06 '14 19:12

David


People also ask

Can you use Python for encryption?

It is critically important because it allows you to securely protect data that you don't want anyone to see or access. In this tutorial, you will learn how to use Python to encrypt files or any byte object (also string objects) using the cryptography library.


1 Answers

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) 
like image 143
KRBA Avatar answered Oct 11 '22 22:10

KRBA