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