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

安装依赖库:pip install pycryptodome
github地址:https://github.com/Legrandin/pycryptodome

# -*- 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)

posted @   郭赫伟  阅读(1692)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
点击右上角即可分享
微信分享提示