# -*- coding=utf8 -*-
import base64
from Crypto.Cipher import AES
def add_to_16(text):
""" 密码填充 (位数不足时需要填充) """
length = 16
count = len(text)
if count % length != 0:
add = length - (count % length)
else:
add = 0
text = text + (" " * add)
return text
def get_secret_key(secret):
""" 密码截取 长度16位 """
# secret = hashlib.md5(secret_key).hexdigest()
# secret = base64.b64encode(secret_key)
key_len = len(secret)
if key_len == 16:
return secret
elif key_len > 16:
return secret[-16:]
elif key_len < 16:
return add_to_16(secret)
def encrypt(text, secret):
"""
AES|ECB|PKCS7Padding|base64(output)
:param text: 明文
:param secret: 密码
:return: 密文
"""
bs = AES.block_size
# PKCS7Padding data
pad = lambda s: s + (bs - len(s) % bs) * chr(bs - len(s) % bs)
secret = get_secret_key(secret)
cipher = AES.new(secret, AES.MODE_ECB)
ret = cipher.encrypt(pad(text))
return base64.b64encode(ret)
def decrypt(text, secret):
"""
AES|ECB|PKCS7Padding|base64(output)
:param text: 密文
:param secret: 密码
:return: 明文
"""
text = base64.b64decode(text)
secret = get_secret_key(secret)
cipher = AES.new(secret, AES.MODE_ECB)
res = cipher.decrypt(text)
# unpad res with PKCS7Padding
unpad = lambda s: s[0:-ord(s[-1])]
return unpad(res)
if __name__ == "__main__":
data = "ni hao"
password = "aesrsasec" # 16, 24, 32位长的密码
sk = encrypt(data, password)
print sk
print decrypt(sk, password)