栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python des加密

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python des加密

题目:

DES加密。生成8个字节(64位)的DES密钥,对原始文件进行DES加密,存入密文文件中。用相同的密钥对DES密文解密,恢复原始的明文。

这里使用python的第三方库 pyDes 完成des加密

代码段仅支持输入数据为 数字和字母,不换行

直接上代码:

(des明文.txt :记录你要加密的数据,支持任何字符,支持换行记录

des密钥.txt :记录生成的密钥

des密文.txt : 记录加密后生成的密文)

from pyDes import des, CBC, PAD_PKCS5
import secrets
import binascii
import os

#写入文件
def write_txt1(name, content):
    path = os.getcwd() + '\' + name + '.txt'
    if os.path.exists(path):
        print(name + '文件存在,覆盖原文件')
    else:
        print(name + '文件不存在,创建文件')
    with open(path, 'w', encoding='utf8') as f:  # 写入新文件
        for i in content:
            f.write(i + 'n')
        f.close()

# 打开文件
def read_txt1(name):
    content=[]
    # with open(os.getcwd()+"\"+name+".txt","r",encoding='utf8') as f:
    with open(name, "r", encoding='utf8') as f:
        for i in f.readlines():
            # i = i.strip('n')
            i = i.rstrip('n')
            content.append(i)
    f.close()
    return content

# 从指定序列中随机生成密钥
def pro_secretkey1():
    secretkey = ''
    for i in range(8):
        secretkey += secrets.choice('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ')

    write_txt1('des密钥',[secretkey])
    return secretkey


# des加密
def des_encrypt(plaintext, secretkey):

    iv = secretkey
    k = des(secretkey, CBC, iv, pad=None, padmode=PAD_PKCS5)
    en = k.encrypt(plaintext, padmode=PAD_PKCS5)
    write_txt1('des密文', [binascii.b2a_hex(en).decode()])

    #binascii.b2a_hex 将输入a转为2进制并以16进制显示返回b
    return binascii.b2a_hex(en).decode()


# des解密
def des_descrypt(ciphertext, secretkey):
    iv = secretkey
    k = des(secretkey, CBC, iv, pad=None, padmode=PAD_PKCS5)
    ciphertext = k.decrypt(binascii.a2b_hex(ciphertext), padmode=PAD_PKCS5)
    return ciphertext

if __name__ == "__main__":
    name='des明文'
    path = os.getcwd()+"\"+name+".txt"
    plaintext = read_txt1(path)[0]
    print('明文为:', plaintext)
    secretkey = pro_secretkey1()
    print('密钥为:', secretkey)
    #加密原文
    ciphertext = des_encrypt(plaintext, secretkey)
    print('密文为:', ciphertext)
    #解密密文
    des = des_descrypt(ciphertext, secretkey)
    print('解密后:', des.decode())

运行截图:

如果对你有帮助,开源不易,请多支持点赞

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/488582.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号