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"\x22\x33\x35\x81\xBC\x38\x5A\xE7" # 自定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 + ('\07' * add).encode('utf-8')
            print(text)
        elif count > length:
            add = (length - (count % length))
            text = text + ('\07' * 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("\07")


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)

 

# -*- coding: utf-8 -*-

"""
@author: Mr_zhang
@software: PyCharm
@file: encryption.py
@time: 2022/9/9 08:18
"""

import base64
import binascii
import time

from pyDes import des, triple_des, CBC, PAD_PKCS5
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad


class DesCrypt:
    """
    Des加解密
    des_type: 1 表示DES加解密 3 表示3DES加解密 默认为1
    """

    def __init__(self, des_type=1):
        self.des_type = des_type
        self.key = "Key!@#$%" if self.des_type == 1 else "Key!@#$%Key!@#$%"
        self.iv = "Iv!@#$%."
        self.mode = CBC
        self.pad = None
        self.pad_mode = PAD_PKCS5
        self.encoding = "utf-8"

    def __des_obj(self):
        """des对象"""
        if self.des_type == 3:
            return triple_des(key=self.key, mode=self.mode, IV=self.iv, pad=self.pad, padmode=self.pad_mode)
        return des(key=self.key, mode=self.mode, IV=self.iv, pad=self.pad, padmode=self.pad_mode)

    def encrypt(self, data):
        """
        DES加密
        :param data: 原始字符串
        :return: 加密后16进制字符串
        """
        _des_obj = self.__des_obj()
        try:
            secret_bytes = _des_obj.encrypt(data=data.encode(self.encoding), padmode=self.pad_mode)
            return True, binascii.b2a_hex(secret_bytes).decode(self.encoding)
        except Exception as e:
            return False, e

    def decrypt(self, data):
        """
        DES解密
        :param data: 加密后的16进制字符串
        :return: 解密后字符串
        """
        _des_obj = self.__des_obj()
        try:
            decrypt_str = _des_obj.decrypt(binascii.a2b_hex(data), padmode=self.pad_mode)
            return True, decrypt_str.decode(self.encoding)
        except Exception as e:
            return False, e


class AesCrypt:
    """
    Aes加解密
    """

    def __init__(self):
        self.key = "Key!@#$%Key!@#$%"
        self.mode = AES.MODE_ECB
        self.block_size = AES.block_size
        self.pad = "pkcs7"
        self.encoding = "utf-8"

    def __aes_obj(self):
        """aes对象"""
        key_bytes = self.key.encode(self.encoding)
        return AES.new(key=key_bytes, mode=self.mode)

    def encrypt(self, data):
        """
        AES加密
        :param data: 原始字符串
        :return: 加密字符串
        """
        _aes_obj = self.__aes_obj()
        data_bytes = data.encode(self.encoding)
        try:
            cipher_base64_bytes = base64.b64encode(_aes_obj.encrypt(pad(data_to_pad=data_bytes, block_size=self.block_size, style=self.pad)))
            return True, cipher_base64_bytes.decode(self.encoding)
        except Exception as e:
            return False, e

    def decrypt(self, data):
        """
        AES解密
        :param data: 待解密字符串
        :return: 原始字符串
        """
        _aes_obj = self.__aes_obj()
        data_base64_bytes = data.encode(self.encoding)
        try:
            data_bytes = unpad(padded_data=_aes_obj.decrypt(base64.b64decode(data_base64_bytes)), block_size=AES.block_size, style=self.pad)
            return True, data_bytes.decode(self.encoding)
        except Exception as e:
            return False, e


if __name__ == '__main__':
    start_des_time = time.time()

    des_obj = DesCrypt()
    print(des_obj.encrypt("张建平"))
    print(des_obj.decrypt("e6318ae03abec76ca3e0dea7ff6d0aa7"))

    print(time.time() - start_des_time)  # 0.0039119720458984375

    print("=" * 20)
    start_aes_time = time.time()
    aes_obj = AesCrypt()
    print(aes_obj.encrypt("张建平"))
    print(aes_obj.decrypt("U+uUlNjnndUsKKRUb4u1Fg=="))
    print(time.time() - start_aes_time)  # 0.002752065658569336

 

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

 

一个比较好的例子:

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

 

posted @ 2018-08-22 10:44  一石数字欠我15w!!!  阅读(6345)  评论(0编辑  收藏  举报