Python使用Crypto/pyDes,DES并Base64编码

注意点

一、秘钥必须是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

第二种pyDes

为什么要说第二种,因为我在本地Python2.7通过pip安装Crypto始终安装不上. 遇到和我同样问题的朋友可以用该方式解决DES加解密

安装

pip install pyDes

引入

from pyDes import des, ECB, PAD_PKCS5
import base64

 

加密代码(注意输出结果要encode,不然打印出来是b'' 字节输出)

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

 

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值