栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python 使用AES加解密

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python 使用AES加解密

    什么是AES自己百度查下吧,直接上代码喽!

    

import base64

from Crypto import Random
from Crypto.Cipher import AES

"""
创建aes实例, 参数: key秘钥(16, 24, 32, 目前16就可以了); mode加密方式这里采用CBC(分组); iv位移, 使用自带AES.block_size代表16位
常见加密模式: CBC密码分组, CFB密码反馈, OFB输出反馈, ECB电码本(分段加密)
aes = AES.new(key, mode, iv)
aes.encrypt(plain_text) 加密
aes.decrypt(cipher_text) 解密
"""

class Encrypt:
"""AES加解密"""

    def __init__(self, key):
        self.key = key
        self.iv = Random.new().read(AES.block_size)
        self.mode = AES.MODE_CBC

    def encrypt(self, text):
        if len(text) % 16 != 0: #不是16的倍数,补足16的倍数
            text = text + abs(len(text) % 16 - 16) * ' '
        aes = AES.new(self.key, self.mode, self.iv)
        cipher_text = aes.encrypt(text)
        #  base64编码后返回
        return base64.b64encode(cipher_text)

    def decrypt(self, text):
        aes = AES.new(self.key, self.mode, self.iv)
        text = base64.b64decode(text)
        plain_text = aes.decrypt(text)
        return plain_text.decode().rstrip()

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/674973.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号