python写的AES128/ECB/pkcs7加密解密函数

因为需要,要实现一个python版的AES128加解密方法,加密模式ECB,填充模式pkcs7.(貌似pkcs5和pkcs7是一模一样的,我没有看具体原因(好像是aes没有64位的,64位对应5?))

下面直接贴源代码啦(我找了好几个东拼西凑出来的,反正能工作,也支持中文)

# -*- coding: utf-8 -*-
from Crypto.Cipher import AES
import os
 
BS = AES.block_size
pad =lambda s: s +(BS - len(s)% BS)* chr(BS - len(s)% BS)
unpad =lambda s : s[0:-ord(s[-1])]
 
key = os.urandom(16)# the length can be (16, 24, 32)
#key='xxxxx'#32位或者0-f的数值,对应16字节
text ='content==顶你哦,记得回访哦xxxxx'
 
cipher = AES.new(key, AES.MODE_ECB)#ECB模式 
 
encrypted = cipher.encrypt(pad(text)).encode('hex')
print encrypted  # will be something like 'f456a6b0e54e35f2711a9fa078a76d16'
 
decrypted = unpad(cipher.decrypt(encrypted.decode('hex')))
print decrypted  # will be 'to be encrypted'

原文链接:https://blog.csdn.net/jinking01/article/details/80542640

  • 0
    点赞
  • 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) ``` 注意:上面示例代码中使用的是AESECB模式,这种模式不安全,容易被攻击,实际应用中应该使用更安全的模式,比如CBC模式。另外,上面代码中的key和text都是字符串形式,如果需要加密二进制数据,应该将其转换为字节数组。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值