pythonDES加密與解密以及hex輸出和bs64格式輸出
阿新 • • 發佈:2021-02-06
import pyDes
import base64
Key = "1" #加密的key
Iv = None #偏移量
def bytesToHexString(bs):
'''
bytes轉16進位制
'''
return ''.join(['%02X ' % b for b in bs])
def hexStringTobytes(str):
'''
16進位制轉bytes
'''
str = str.replace(" ", "" )
return bytes.fromhex(str)
# 加密
def encrypt_str(data):
# 加密方法
#padmode填充方式
#pyDes.ECB模式
method = pyDes.des(Key, pyDes.ECB, Iv, pad=None, padmode=pyDes.PAD_PKCS5)
# 執行加密碼 hex輸出
k = method.encrypt(data)
data = bytesToHexString(k).replace(' ','')
#bs64手粗
#data =base64.b64encode(k)
return data
# 解密
def decrypt_str(data):
method = pyDes.des(Key, pyDes.ECB, Iv, pad=None, padmode=pyDes.PAD_PKCS5)
k =hexStringTobytes(data)
#bs64
#k = base64.b64decode(data)
return method.decrypt(k)
Encrypt = encrypt_str("aaa")
print(Encrypt)
Decrypt = decrypt_str (Encrypt)
print(Decrypt)
作者:小小鹹魚YwY
出處c#教程:https://www.cnblogs.com/pythonywy/p/12690762.html