Python---AES加密-CBC模式-PKCS7填充

最近公司业务需求,看到别人的文章,感觉很有用,故转载保存。

from Crypto.Cipher import AES
import base64
import time
import json


class Encrypt:
    def __init__(self, key, iv):
        self.key = key.encode('utf-8')
        self.iv = iv.encode('utf-8')

    # @staticmethod
    def pkcs7padding(self, text):
        """明文使用PKCS7填充 """
        bs = 16
        length = len(text)
        bytes_length = len(text.encode('utf-8'))
        padding_size = length if (bytes_length == length) else bytes_length
        padding = bs - padding_size % bs
        padding_text = chr(padding) * padding
        self.coding = chr(padding)
        return text + padding_text

    def aes_encrypt(self, content):
        """ AES加密 """
        cipher = AES.new(self.key, AES.MODE_CBC, self.iv)
        # 处理明文
        content_padding = self.pkcs7padding(content)
        # 加密
        encrypt_bytes = cipher.encrypt(content_padding.encode('utf-8'))
        # 重新编码
        result = str(base64.b64encode(encrypt_bytes), encoding='utf-8')
        return result


    def aes_decrypt(self, content):
        """AES解密 """
        cipher = AES.new(self.key, AES.MODE_CBC, self.iv)
        content = base64.b64decode(content)
        text = cipher.decrypt(content).decode('utf-8')
        return text.rstrip(self.coding)

if __name__ == '__main__':
    key = 'ONxYDyNaCoyTzsp83JoQ3YYuMPHxk3j7'
    iv = 'yNaCoyTzsp83JoQ3'

    ts = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    p_json = {
		"CompanyName": "testmall",
		"UserId": "test",
		"Password": "grasp@101",
		"TimeStamp": "2019-05-05 10:59:26"
	}
    a = Encrypt(key=key, iv=iv)
    e = a.aes_encrypt(json.dumps(p_json))
    d = a.aes_decrypt(e)
    print("加密:", e)
    print("解密:", d)

注意最后输出格式为base64格式,如果要使用HEX输出格式,改为:

import binascii
# 重新编码
        result = binascii.b2a_hex(encrypt_bytes).decode()
  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值