Python AES加密,解密(ECB、PKCS7Padding、輸出 base64)


# -*- 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 + ("\0" * 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)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM