Introduction to the method of implementing DES encryption and decryption in Python (code)

不言
Release: 2019-03-25 10:49:17
forward
6071 people have browsed it

This article brings you an introduction to the method (code) of implementing DES encryption and decryption in Python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

DES (Data Encryption Standard) uses a 64-bit block length and a 56-bit key length. It takes a 64-bit input and undergoes a series of transformations to obtain a 64-bit output. Decryption uses the same steps and the same keys, the only difference is that the key order is reversed from the encryption process.

DES encryption:

The input of this algorithm includes the plaintext to be encrypted and the key used for encryption, both of which are 64 bits in length. The 8th, 16th, 24th, 32nd, 40th, 48th, 56th, and 64th bits of the key are parity bits.

1. Processing of plain text

Read the plain text into the program and convert it into a binary string

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
Copy after login

Perform IP replacement on the plain text and divide it into two substrings, the left and right substrings

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

2. Processing of keys

Read the key into the program and store it in the form of a binary string

Perform PC-1 replacement on the key and divide it into Two substrings

#密钥置换
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
Copy after login

Before generating the key required for iteration, the key needs to be replaced and compressed

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

Generate the subkey required for each iteration of DES so that it can be directly encrypted and decrypted Using

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
Copy after login

3, F function

In each round of transformation, the entire process can be expressed by the following formula:

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

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

The round key Ki is 48 bits long and R is 32 bits long. First, R is replaced and expanded to 48 bits. These 48 bits are XORed with Ki. The result is generated by using the substitution function to generate 32 bits. output. The 32-bit output is XORed with L after P replacement to obtain a new R

replacement function consisting of 8 S boxes, each S box has 6-bit input and 4-bit output. For each S box, the first and last bits of the input form a 2-bit binary number, which is used to select one of the 4 rows of alternative values ​​in the S box, and the middle 4 bits are used to select one of the 16 columns.

#明文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
Copy after login

4. Encryption process

DES encryption requires 16 rounds of iterations. L and R need to be exchanged at the end of each of the first 15 rounds of iterations. The 16th time will not be exchanged.

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
Copy after login

DES decryption:

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
Copy after login

Source code address https://github.com/SuQinghang...

This article is over here. For more other exciting content, you can pay attention to PHP Chinese The python video tutorial column of the website!

The above is the detailed content of Introduction to the method of implementing DES encryption and decryption in Python (code). For more information, please follow other related articles on the PHP Chinese website!

source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template