python AES加解密CBC

# -*- coding:utf-8 -*-
# 这里使用pycrypto‎demo库
# 安装方法 pip install pycrypto‎demo
 
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex
import io
import sys
import binascii

import base64
import random

sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf8')


import base64
from Crypto.Cipher import AES
from urllib import parse
 
AES_SECRET_KEY = '1234567890123456' #此处16|24|32个字符
IV = "1234567890123456"
 
# padding算法
BS = len(AES_SECRET_KEY)
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s: s[0:-ord(s[-1:])]
 
 
class AES_ENCRYPT(object):
    def __init__(self):
       self.key = AES_SECRET_KEY
       self.mode = AES.MODE_CBC
       
    #加密函数
    def encrypt(self, text):
       cryptor = AES.new(self.key.encode("utf8"), self.mode, IV.encode("utf8"))
       self.ciphertext = cryptor.encrypt(bytes(pad(text), encoding="utf8"))
       # 加密得到的字符串转16进制
       return binascii.hexlify(self.ciphertext)
       
    #解密函数
    def decrypt(self, text):
       # 十六进制转二进制
       decode = binascii.unhexlify(text)
       cryptor = AES.new(self.key.encode("utf8"), self.mode, IV.encode("utf8"))
       plain_text = cryptor.decrypt(decode)
       return unpad(plain_text)
 
if __name__ == '__main__':
    aes_encrypt = AES_ENCRYPT()
    my_email = "{'a':b,'deviceName':dashd123}"
    e = aes_encrypt.encrypt(my_email)
    d = aes_encrypt.decrypt(e)
    print(my_email)
    print(e)
    print(d)

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是Python中使用AES加密和解密的示例代码: ```python from Crypto.Cipher import AES import base64 # 加密函数 def encrypt(text, key): # 将key转换为16位二进制字符串 key = key.encode('utf-8') key = AES.new(key, AES.MODE_ECB).encrypt(b'0000000000000000') # 将文本转换为16位二进制字符串 text = text.encode('utf-8') text_length = len(text) add = 16 - (text_length % 16) text = text + (b'\0' * add) # 加密 cryptor = AES.new(key, AES.MODE_ECB) ciphertext = cryptor.encrypt(text) # 转换为base64编码 return base64.b64encode(ciphertext).decode('utf-8') # 解密函数 def decrypt(ciphertext, key): # 将key转换为16位二进制字符串 key = key.encode('utf-8') key = AES.new(key, AES.MODE_ECB).encrypt(b'0000000000000000') # 将密文先转换为二进制字符串,再解码为字节数组 ciphertext = base64.b64decode(ciphertext.encode('utf-8')) # 解密 cryptor = AES.new(key, AES.MODE_ECB) text = cryptor.decrypt(ciphertext).decode('utf-8') # 去除末尾的'\0' return text.rstrip('\0') # 示例 key = '1234567890123456' text = 'Hello, world!' ciphertext = encrypt(text, key) print('加密后:', ciphertext) plaintext = decrypt(ciphertext, key) print('解密后:', plaintext) ``` 注意:上面示例代码中使用的是AES的ECB模式,这种模式不安全,容易被攻击,实际应用中应该使用更安全的模式,比如CBC模式。另外,上面代码中的key和text都是字符串形式,如果需要加密二进制数据,应该将其转换为字节数组。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值