python-pyDes-ECB加密-DES-DES3加密

网上的教程都他妹的是抄的,抄也就算了,还改抄错了,害我写了一两天都没找到原因,直接去官网看,找例子很方便

官网链接:http://twhiteman.netfirms.com/des.html

一个小例子:

采用DES(ECB模式)对称加密实现,填充方式默认使用PKCS5Padding,可以使用在线测试工具http://tool.chacuo.net/cryptdes

接下来在python中的代码里实现一下:(py3必须使用bytes类型)

Des_Key = b"f2155bca" # 相当于加密盐
Des_IV = b"x22x33x35x81xBCx38x5AxE7" # 自定IV向量(不知道什么用,官网例子就是这么写的)
def desencrypt(s):
    k = pyDes.des(Des_Key, pyDes.ECB, Des_IV, pad=None, padmode=pyDes.PAD_PKCS5)
    encrystr = k.encrypt(s)
    return base64.b64encode(encrystr)

print('===========>', desencrypt(phone))

有问题欢迎留言,看到会尽快回复

Cryptodome模块针对DES3加密示例(和网站加密结果不一样,但是网站可以解密我的加密字符串,很奇怪)

from Cryptodome.Cipher import DES3
from binascii import b2a_base64, a2b_base64

class PrpCrypt(object):
    def __init__(self, key, iv):
        self.key = key.encode('utf-8')
        self.mode = DES3.MODE_CBC
        self.iv = iv

    # 加密函数,如果text不足16位就用空格补足为16位,
    # 如果大于16当时不是16的倍数,那就补足为16的倍数。
    def encrypt(self, text):
        text = text.encode('utf-8')
        cryptor = DES3.new(self.key, self.mode, self.iv)
        # 这里密钥key 长度必须为16(AES-128),
        # 24(AES-192),或者32 (AES-256)Bytes 长度
        # 目前AES-128 足够目前使用
        length = 16
        count = len(text)
        if count < length:
            add = (length - count)
            text = text + ('7' * add).encode('utf-8')
            print(text)
        elif count > length:
            add = (length - (count % length))
            text = text + ('7' * add).encode('utf-8')
            print(text)
        self.ciphertext = cryptor.encrypt(text)
        # return base64.b64encode(self.ciphertext)
        return b2a_base64(self.ciphertext)


    # EDS3解密
    def decrypt(self, text):
        cryptor = DES3.new(self.key, self.mode, self.iv)
        plain_text = cryptor.decrypt(a2b_base64(text))
        return plain_text.decode("utf-8").rstrip("7")


pc = PrpCrypt(key=keys, iv=iv)  # 初始化密钥
e = pc.encrypt(json.dumps(Json))  # 加密
print("源数据:", json.dumps(Json))
print("加密:", e)
d = pc.decrypt(e)
print("解密:", d)
params = {
    "param": e.decode("utf8")
}
print(params["param"])
res = requests.post(url=url, data=params)
print("============>", res.text)

在线测试:http://tool.chacuo.net/crypt3des

一个比较好的例子:

https://juejin.im/entry/5b46cf6a5188251ac60bf932

 

原文地址:https://www.cnblogs.com/52-qq/p/9516256.html