網上的教程都他妹的是抄的,抄也就算了,還改抄錯了,害我寫了一兩天都沒找到緣由,直接去官網看,找例子很方便html
官網連接:http://twhiteman.netfirms.com/des.htmlpython
一個小例子:json
採用DES(ECB模式)對稱加密實現,填充方式默認使用PKCS5Padding,能夠使用在線測試工具http://tool.chacuo.net/cryptdesdom
接下來在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加密示例(和網站加密結果不同,可是網站能夠解密個人加密字符串,很奇怪)post
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)
在線測試:http://tool.chacuo.net/crypt3des測試
一個比較好的例子:網站