搜索
首页后端开发Python教程Python实现DES加密解密的方法介绍(代码)

Python实现DES加密解密的方法介绍(代码)

Mar 25, 2019 am 10:49 AM
python加密算法密码学

本篇文章给大家带来的内容是关于Python实现DES加密解密的方法介绍(代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

DES(Data Encryption Standard)采用64位的分组长度和56位的密钥长度。它将64位的输入经过一系列变换得到64为的输出。解密使用相同的步骤和相同的密钥,唯一不同的是密钥顺序与加密过程相反。

DES加密:

该算法的输入有需要加密的明文和加密使用的密钥,二者长度都为64位。其中密钥的第8,16,24,32,40,48,56,64位为奇偶校验位。

1、明文的处理

将明文读入程序并将其化为二进制串

def inputText(filename):
    with open(filename,'r')as f:
        text = f.read()
    text = text.split('\n')
    text = [eval(x) for x in text]
    text = ['{:08b}'.format(x) for x in text]
    text = ''.join(text)
    
    return text

对明文进行IP置换,并划分为左右两个子串

def IP_Transposition(plaintext):
    LR = []
    for i in IP:
        LR.append(int(plaintext[i-1]))
    L = LR[:32]
    R = LR[32:]
    return L,R

2、对密钥的处理

将密钥读入程序并以二进制串的形式存储

对密钥进行PC-1置换,并划分为两个子串

#密钥置换
def Key_Transposition(key):
    CD = []
    for i in PC_1:
        CD.append(int(key[i-1]))
    C = CD[:28]
    D = CD[28:]
    return C,D

在生成迭代所需要的密钥之前需要对密钥进行置换压缩

#密钥压缩
def Key_Compress(C,D):
    key = C+D
    new_key = []
    for i in PC_2:
        new_key.append(key[i-1])
    return new_key

生成DES每轮迭代所需要的子密钥,以便加密解密时直接使用

def generateKset(key):
    key = inputKey(key)
    C,D = Key_Transposition(key)
    K = []
    for i in LeftRotate:
        C = Key_LeftRotate(C,i)
        C = Key_LeftRotate(D,i)
        K.append(Key_Compress(C,D))
    return K

3、F函数

在每轮变换中,整个过程可以用以下公式表示:

$$ L_i = R_{i-1} $$

$$ R_i = L_{i-1}\bigoplus F(R_{i-1},K_i) $$

其中轮密钥 Ki长48位,R长32位,首先将R置换扩展为48位,这48位与Ki异或,得到的结果用替代函数作用产生32位的输出。这32位的输出经P置换后与L异或得到新的R

代替函数由8个S盒来组成,每个S盒都有6位的输入和4位的输出。对每个S盒,输入的第一位和最后一位组成一个2位的二进制数,用来选择S盒4行替代值中的一行,中间4位用来选择16列中的某一列。

#明文R扩展为48位
def R_expand(R):
    new_R = []
    for i in E:
        new_R.append(R[i-1])
    return new_R

#将两列表元素异或
def xor(input1,input2):
    xor_result = []
    for i in range(0,len(input1)):
        xor_result.append(int(input1[i])^int(input2[i]))
    return xor_result

#将异或的结果进行S盒代替
def S_Substitution(xor_result):
    s_result = []
    for i in range(0,8):
        tmp = xor_result[i*6:i*6+5]
        row = tmp[0]*2+tmp[-1]
        col = tmp[1]*8+tmp[2]*4+tmp[3]*2+tmp[4]
        s_result.append('{:04b}'.format(S[i][row][col]))
    s_result = ''.join(s_result)
    return s_result
#F函数
def F(R,K):
    new_R = R_expand(R)
    R_Kxor= xor(new_R,K)
    s_result = S_Substitution(R_Kxor)
    p_result = P_Transposition(s_result)
    return p_result

#将S盒代替的结果进行P置换
def P_Transposition(s_result):
    p_result = []
    for i in P:
        p_result.append(int(s_result[i-1]))
    return p_result

4、加密过程

DES加密需要经过16轮迭代,前15轮迭代每次结束需要交换L和R,第16次不交换

def DES_encrypt(filename,key,outputFile):
    #从文件中读取明文
    plaintext = inputText(filename)
    #将明文进行置换分离
    L,R = IP_Transposition(plaintext)
    #生成Kset
    K = generateKset(key)
    for i in range(0,15):
        oldR = R
        #F函数
        p_result = F(R,K[i])
        R = xor(L,p_result)
        L = oldR
    p_result = F(R,K[15])
    L = xor(L,p_result)
    #IP逆置换
    reversedP = IP_reverseTransp(L+R)
    #生成16进制表示的密文
    Cipher = generateHex(reversedP)
    #将密文写入outputFile文件
    writeFile(outputFile,Cipher)
    return Cipher

DES解密:

def DES_decrypt(filename,key,outputFile):
    #文件中读取密文
    Ciphertext = inputText(filename)
    #将密文进行置换分离
    L,R = IP_Transposition(Ciphertext)
    #生成Kset
    K = generateKset(key)
    for i in range(15,0,-1):
        oldR = R
        #F函数
        p_result = F(R,K[i])
        R = xor(L,p_result)
        L = oldR
    
    p_result = F(R,K[0])
    L = xor(L,p_result)
    reversedP = IP_reverseTransp(L+R)
    plaintext = generateHex(reversedP)
    writeFile(outputFile,plaintext)
    return plaintext

源码地址 https://github.com/SuQinghang...

本篇文章到这里就已经全部结束了,更多其他精彩内容可以关注PHP中文网的python视频教程栏目!

以上是Python实现DES加密解密的方法介绍(代码)的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:segmentfault。如有侵权,请联系admin@php.cn删除
Python:编译器还是解释器?Python:编译器还是解释器?May 13, 2025 am 12:10 AM

Python是解释型语言,但也包含编译过程。1)Python代码先编译成字节码。2)字节码由Python虚拟机解释执行。3)这种混合机制使Python既灵活又高效,但执行速度不如完全编译型语言。

python用于循环与循环时:何时使用哪个?python用于循环与循环时:何时使用哪个?May 13, 2025 am 12:07 AM

useeAforloopWheniteratingOveraseQuenceOrforAspecificnumberoftimes; useAwhiLeLoopWhenconTinuingUntilAcIntiment.ForloopSareIdeAlforkNownsences,而WhileLeleLeleLeleLoopSituationSituationSituationsItuationSuationSituationswithUndEtermentersitations。

Python循环:最常见的错误Python循环:最常见的错误May 13, 2025 am 12:07 AM

pythonloopscanleadtoerrorslikeinfiniteloops,modifyingListsDuringteritation,逐个偏置,零indexingissues,andnestedloopineflinefficiencies

对于循环和python中的循环时:每个循环的优点是什么?对于循环和python中的循环时:每个循环的优点是什么?May 13, 2025 am 12:01 AM

forloopsareadvantageousforknowniterations and sequests,供应模拟性和可读性;而LileLoopSareIdealFordyNamicConcitionSandunknowniterations,提供ControloperRoverTermination.1)forloopsareperfectForeTectForeTerToratingOrtratingRiteratingOrtratingRitterlistlistslists,callings conspass,calplace,cal,ofstrings ofstrings,orstrings,orstrings,orstrings ofcces

Python:深入研究汇编和解释Python:深入研究汇编和解释May 12, 2025 am 12:14 AM

pythonisehybridmodelofcompilationand interpretation:1)thepythoninterspretercompilesourcececodeintoplatform- interpententbybytecode.2)thepytythonvirtualmachine(pvm)thenexecuteCutestestestesteSteSteSteSteSteSthisByTecode,BelancingEaseofuseWithPerformance。

Python是一种解释或编译语言,为什么重要?Python是一种解释或编译语言,为什么重要?May 12, 2025 am 12:09 AM

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允许fordingfordforderynamictynamictymictymictymictyandrapiddefupment,尽管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

对于python中的循环时循环与循环:解释了关键差异对于python中的循环时循环与循环:解释了关键差异May 12, 2025 am 12:08 AM

在您的知识之际,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations则youneedtoloopuntilaconditionismet

循环时:实用指南循环时:实用指南May 12, 2025 am 12:07 AM

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。