python3 3des des aes 加密 PKCS7 填充

本文介绍如何使用PyCrypto库实现AES和3DES的加密与解密操作,包括填充、CBC模式设置及Base64编码,并提供了一个完整的Python示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先感谢 孤影惆怅 大佬的文章 得以完美安装好了PyCrypto
文章地址:http://blog.youkuaiyun.com/a624806998/article/details/78596543

使用PyCrypto包的 AES 加密
3des des 和 aes 没什么差别
把 import的 AES改成 3DES 或者你想要的加密方式 记得把加密mode 改了

from Crypto.Cipher import AES
import base64
BS = AES.block_size


def pad(s): 
	return s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
#定义 padding 即 填充 为PKCS7

def unpad(s): 
	return s[0:-ord(s[-1])]


class prpcrypt():  
    def __init__(self, key):
        self.key = key
        self.mode = AES.MODE_CBC
	# AES的加密模式为CBC
    def encrypt(self, text):
        text = pad(text)
        cryptor = AES.new(self.key, self.mode, self.key)
        #第二个self.key 为 IV 即偏移量
        x = len(text) % 8
        if x != 0:
            text = text + '\0' * (8 - x)  # 不满16,32,64位补0
        print(text)
        self.ciphertext = cryptor.encrypt(text)
        return base64.standard_b64encode(self.ciphertext).decode("utf-8")

    def decrypt(self, text):
        cryptor = AES.new(self.key, self.mode, self.key)
        de_text = base64.standard_b64decode(text)
        plain_text = cryptor.decrypt(de_text)
        st = str(plain_text.decode("utf-8")).rstrip('\0')
        out = unpad(st)
        return out


pc = prpcrypt('ningbozhihuirend')  # 自己设定的密钥
e = pc.encrypt("hello")  # 加密内容
d = pc.decrypt(e)
print("加密后%s,解密后%s" % (e, d))

3DES DES 可以参照 stackoverflow 上大佬的给的解决方案
用的不是pycrypto 而是pydes

https://stackoverflow.com/questions/2435283/using-des-3des-with-python

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值