Skip to content

Instantly share code, notes, and snippets.

@tamr
Created January 20, 2018 06:10
Show Gist options
  • Save tamr/f292cdc89588e129444f952af6cbbd2f to your computer and use it in GitHub Desktop.
Save tamr/f292cdc89588e129444f952af6cbbd2f to your computer and use it in GitHub Desktop.
"""
This Script needs django and pycrypto.
If you want to use this, just call encode(wanna_crypto_text) or decode(encoded_text).
When your secret key changed, you can't decode encoded text before changed, so becareful.
"""
import hashlib
from Crypto.Cipher import AES
import base64
from django.conf import settings
secret_key = hashlib.sha256(settings.SECRET_KEY.encode()).digest()
block_size = 32
padding = '|'
def encode(target):
aes = AES.new(secret_key)
target = pad(target)
after = aes.encrypt(target)
based = base64.b64encode(after)
return based.decode()
def decode(target):
based = base64.b64decode(target)
aes = AES.new(secret_key)
after = aes.decrypt(based)
return unpad(after)
def pad(s):
return s + (block_size - len(s) % block_size) * padding
def unpad(s):
return s.decode().rstrip('|')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment