def encrypt(plaintext, key=config.SECRET, key_salt='', no_iv=False):
"""Encrypt shit the right way"""
# sanitize inputs
key = SHA256.new(key + key_salt).digest()
if len(key) not in AES.key_size:
raise Exception()
if isinstance(plaintext, unicode):
plaintext = plaintext.encode('utf-8')
# pad plaintext using PKCS7 padding scheme
padlen = AES.block_size - len(plaintext) % AES.block_size
plaintext += chr(padlen) * padlen
# generate random initialization vector using CSPRNG
iv = '\0' * AES.block_size if no_iv else get_random_bytes(AES.block_size)
# encrypt using AES in CFB mode
ciphertext = AES.new(key, AES.MODE_CFB, iv).encrypt(plaintext)
# prepend iv to ciphertext
if not no_iv:
ciphertext = iv + ciphertext
# return ciphertext in hex encoding
return ciphertext.encode('hex')
评论列表
文章目录