注意点
一、秘钥必须是8位
二、待加密的明文长度必须是8的倍数,不足则补空字符
from Crypto.Cipher import DES
import base64
def encrypt_des(cipher):
if cipher is None:
return ""
try:
key = '1234A#CD'
# ECB方式
generator = DES.new(key, DES.MODE_ECB)
# 非8整数倍明文补位
pad = 8 - len(cipher) % 8
pad_str = ""
for i in range(pad):
pad_str = pad_str + chr(pad)
# 加密
encrypted = generator.encrypt(cipher + pad_str)
# 编码得密文
result = base64.b64encode(encrypted)
print "cipher : "+str(cipher)+" encrypted : "+result
return result
except Exception, e:
print Exception, ":", e
return ""
测试
print encrypt_des("1234567890")
输出
cipher : 1234567890 encrypted : jHgeV9zr6EVnSM7n7LG63g==
def decrypt_des(encrypted):
if encrypted is None:
return ""
try:
key = '1234A#CD'
# ECB方式
generator = DES.new(key, DES.MODE_ECB)
# 解码
crypted_str = base64.b64decode(encrypted)
# 解密
result = generator.decrypt(crypted_str)
# 替换非空格字符(诡异的串)
result = result.strip("�����")
result = result.strip("������")
print "encrypted : "+str(encrypted)+" cipher :"+result
return result
except Exception, e:
print Exception, ":", e
return ""
测试
print decrypt_des("jHgeV9zr6EVnSM7n7LG63g==")
输出
encrypted : jHgeV9zr6EVnSM7n7LG63g== cipher :1234567890
为什么要说第二种,因为我在本地Python2.7通过pip安装Crypto始终安装不上. 遇到和我同样问题的朋友可以用该方式解决DES加解密
pip install pyDes
from pyDes import des, ECB, PAD_PKCS5
import base64
def des_encrypt(s):
secret_key = '1234A#CD'
iv = secret_key
k = des(secret_key, ECB, iv, pad=None, padmode=PAD_PKCS5)
en = k.encrypt(s.encode('utf-8'), padmode=PAD_PKCS5)
return str(base64.b64encode(en), 'utf-8')
def des_descrypt(s):
secret_key = '1234A#CD'
iv = secret_key
k = des(secret_key, ECB, iv, pad=None, padmode=PAD_PKCS5)
de = k.decrypt(base64.b64decode(s), padmode=PAD_PKCS5)
return de