Python AES_ECB_PKCS5加密代码

#!/usr/bin/env python
# coding=utf-8

# Created by slowchen on 2018/1/10 13:48.

import base64
import re

from Crypto.Cipher import AES


class AESECB:
    def __init__(self, key):
        self.key = key
        self.mode = AES.MODE_ECB
        self.bs = 16  # block size
        self.PADDING = lambda s: s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)

    def encrypt(self, text):
        generator = AES.new(self.key, self.mode)  # ECB模式无需向量iv
        crypt = generator.encrypt(self.PADDING(text))
        crypted_str = base64.b64encode(crypt)
        result = crypted_str.decode()
        return result

    def decrypt(self, text):
        generator = AES.new(self.key, self.mode)  # ECB模式无需向量iv
        text += (len(text) % 4) * '='
        decrpyt_bytes = base64.b64decode(text)
        meg = generator.decrypt(decrpyt_bytes)
        # 去除解码后的非法字符
        try:
            result = re.compile('[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f\n\r\t]').sub('', meg.decode())
        except Exception:
            result = '解码失败,请重试!'
        return result


if __name__ == '__main__':
    aes = AESECB('this is aes key!')
    print(aes.encrypt('pythonaes123456'))
    print(aes.decrypt('bvN4eERKQBOSXu5EpZ+rBw=='))
    print(aes.decrypt('yzm34N/bEY8kVJNeS93Gv1svJI77YPjaK1+mW+/A4FY='))  # python is very good
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值