Does Python have a built-in, simple way of encoding/decoding strings using a password?
Something like this:
>>> encode('John Doe', password = 'mypass')
'sjkl28cn2sx0'
>>> decode('sjkl28cn2sx0', password = 'mypass')
'John Doe'
So the string "John Doe" gets encrypted as 'sjkl28cn2sx0'. To get the original string, I would "unlock" that string with the key 'mypass', which is a password in my source code. I'd like this to be the way I can encrypt/decrypt a Word document with a password.
I would like to use these encrypted strings as URL parameters. My goal is obfuscation, not strong security; nothing mission critical is being encoded. I realize I could use a database table to store keys and values, but am trying to be minimalist.
Simple way is using the library, and PyCrypto is the good one.
Here's a Python 3 version of the functions from @qneill 's answer:
The extra encode/decodes are needed because Python 3 has split strings/byte arrays into two different concepts, and updated their APIs to reflect that..
As you explicitly state that you want obscurity not security, we'll avoid reprimanding you for the weakness of what you suggest :)
So, using PyCrypto:
If someone gets a hold of your database and your code base, they will be able to decode the encrypted data. Keep your secret_key safe!
Here's an implementation of URL Safe encryption and Decryption using AES(PyCrypto) and base64.
If you face some issue like this https://bugs.python.org/issue4329 ( TypeError: character mapping must return integer, None or unicode ) use str(cipher) while decoding as follows
return obj2.decrypt(base64.urlsafe_b64decode(str(cipher)))
This works but password length should be exactly
8
. This is simple and requires pyDes.OUTPUT:
As has been mentioned the PyCrypto library contains a suite of ciphers. The XOR cipher can be used to do the dirty work if you don't want to do it yourself:
Even though it only provides minimal security I'd still recommend using a random looking key without any space characters (as XOR'ing an ASCII [a-zA-Z] character with a space just flips the case).
The cipher works as follows without having to pad the plaintext:
Credit to https://stackoverflow.com/a/2490376/241294 for the base64 encode/decode functions (I'm a python newbie).