Python AES_ECB_PKCS5加密代码

https://blog.csdn.net/u010978840/article/details/79035463

***************************************************************

#!/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

改善的代码

from Crypto.Cipher import AES

key = "****************"
mode = AES.MODE_ECB


bs = 16
PADDING = lambda s: s + (bs - len(s) % bs) * chr(bs - len(s) % bs)
PADDING = lambda s: s + (bs - len(s.encode()) % bs) * chr(bs - len(s.encode()) % bs)

def un_padding(padded_text):
    padded_len = ord(padded_text[-1])
    if padded_len >= 16:
        return padded_text
    if len(set(padded_text[-padded_len:])) > 1:
        return padded_text
    return padded_text[0:-padded_len]
        

text = "欢迎来到abc"
generator = AES.new(key, mode)
crypt = generator.encrypt(PADDING(text))
crypt_hex_string = crypt.hex()


crypted_text = "ec017a24e572d282eb8abbda44376cee"
generator = AES.new(key, mode)
#meg = generator.decrypt(crypt)
meg = generator.decrypt(bytes.fromhex(crypted_text))
decrypted_text =  meg.decode()

 

转载于:https://www.cnblogs.com/zhao1949/p/10450725.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值