当前位置:   article > 正文

DES加密算法实现

des加密算法实现

编写DES算法实现程序,运行DES程序,演示DES加密与解密的过程。

DES算法的完整过程:

每一步实现的过程参考:DES算法过程

完整代码:
  1. import binascii
  2. import os
  3. class DES():
  4. ip = [
  5. 58, 50, 42, 34, 26, 18, 10, 2,
  6. 60, 52, 44, 36, 28, 20, 12, 4,
  7. 62, 54, 46, 38, 30, 22, 14, 6,
  8. 64, 56, 48, 40, 32, 24, 16, 8,
  9. 57, 49, 41, 33, 25, 17, 9, 1,
  10. 59, 51, 43, 35, 27, 19, 11, 3,
  11. 61, 53, 45, 37, 29, 21, 13, 5,
  12. 63, 55, 47, 39, 31, 23, 15, 7
  13. ] # IP置换表
  14. ip1 = [
  15. 40, 8, 48, 16, 56, 24, 64, 32,
  16. 39, 7, 47, 15, 55, 23, 63, 31,
  17. 38, 6, 46, 14, 54, 22, 62, 30,
  18. 37, 5, 45, 13, 53, 21, 61, 29,
  19. 36, 4, 44, 12, 52, 20, 60, 28,
  20. 35, 3, 43, 11, 51, 19, 59, 27,
  21. 34, 2, 42, 10, 50, 18, 58, 26,
  22. 33, 1, 41, 9, 49, 17, 57, 25
  23. ] # IP逆置换表
  24. E = [
  25. 32, 1, 2, 3, 4, 5,
  26. 4, 5, 6, 7, 8, 9,
  27. 8, 9, 10, 11, 12, 13,
  28. 12, 13, 14, 15, 16, 17,
  29. 16, 17, 18, 19, 20, 21,
  30. 20, 21, 22, 23, 24, 25,
  31. 24, 25, 26, 27, 28, 29,
  32. 28, 29, 30, 31, 32, 1
  33. ] # E扩展置换表
  34. P = [
  35. 16, 7, 20, 21, 29, 12, 28, 17,
  36. 1, 15, 23, 26, 5, 18, 31, 10,
  37. 2, 8, 24, 14, 32, 27, 3, 9,
  38. 19, 13, 30, 6, 22, 11, 4, 25,
  39. ] # P盒置换表
  40. K = '0111011101101000011010010111001101101001011100110110100001110010'
  41. k1 = [
  42. 57, 49, 41, 33, 25, 17, 9,
  43. 1, 58, 50, 42, 34, 26, 18,
  44. 10, 2, 59, 51, 43, 35, 27,
  45. 19, 11, 3, 60, 52, 44, 36,
  46. 63, 55, 47, 39, 31, 23, 15,
  47. 7, 62, 54, 46, 38, 30, 22,
  48. 14, 6, 61, 53, 45, 37, 29,
  49. 21, 13, 5, 28, 20, 12, 4,
  50. ] # 密钥初始置换表
  51. k2 = [
  52. 14, 17, 11, 24, 1, 5, 3, 28,
  53. 15, 6, 21, 10, 23, 19, 12, 4,
  54. 26, 8, 16, 7, 27, 20, 13, 2,
  55. 41, 52, 31, 37, 47, 55, 30, 40,
  56. 51, 45, 33, 48, 44, 49, 39, 56,
  57. 34, 53, 46, 42, 50, 36, 29, 32,
  58. ]
  59. k0 = [1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1, ] # 循环左移表
  60. S = [ # S盒的8个盒
  61. # S1
  62. [14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7,
  63. 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8,
  64. 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0,
  65. 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13],
  66. # S2
  67. [15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10,
  68. 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5,
  69. 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15,
  70. 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9],
  71. # S3
  72. [10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8,
  73. 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1,
  74. 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7,
  75. 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12],
  76. # S4
  77. [7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15,
  78. 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9,
  79. 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4,
  80. 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14],
  81. # S5
  82. [2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9,
  83. 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6,
  84. 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14,
  85. 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3],
  86. # S6
  87. [12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11,
  88. 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8,
  89. 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6,
  90. 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13],
  91. # S7
  92. [4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1,
  93. 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6,
  94. 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2,
  95. 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12],
  96. # S8
  97. [13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7,
  98. 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2,
  99. 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8,
  100. 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11],
  101. ]
  102. def replace(self, string: str, self_table: list):
  103. """
  104. :param string: 需要进行置换的列表,是一个01字符串
  105. :param self_table: 置换表
  106. """
  107. rep_result = ""
  108. for i in self_table:
  109. rep_result += string[i - 1]
  110. return rep_result
  111. def bit_encode(self, string: str):
  112. """
  113. 将明文转为二进制字符串
  114. """
  115. plaintext_list = list(bytes(string, 'utf8')) # 将字符串转成bytes类型,再转成list
  116. result = []
  117. for num in plaintext_list:
  118. result.append(bin(num)[2:].zfill(8)) # 将列表的每个元素转成二进制字符串,8位宽度
  119. return "".join(result)
  120. def str_encode(self, binary: str):
  121. """
  122. 二进制字符串转成字符串
  123. """
  124. list_bin = [binary[i:i + 8] for i in range(0, len(binary), 8)] # 对二进制字符串进行切分,每8位为一组
  125. list_int = []
  126. for b in list_bin:
  127. list_int.append(int(b, 2)) # 二进制转成int
  128. result = bytes(list_int).decode() # 将列表转成bytes,解码,得到字符串
  129. return result
  130. def __bin2int(self, binary: str):
  131. """
  132. 将二进制字符串每8位转成int型号列表->bytes->hex
  133. """
  134. list_bin = [binary[i:i + 8] for i in range(0, len(binary), 8)] # 对二进制字符串进行分组,每8位为一组
  135. list_int = []
  136. for b in list_bin:
  137. list_int.append(int(b, 2))
  138. return list_int
  139. def __int2bin(self, list_int: list):
  140. result = []
  141. for num in list_int:
  142. result.append(bin(num)[2:].zfill(8))
  143. return ''.join(result)
  144. def group_by_64bit(self, binary: str):
  145. """
  146. 对01字符串进行分组,64位一组,不够的在末位补0
  147. """
  148. len_binary = len(binary)
  149. if len_binary % 64 != 0:
  150. binary_block = binary + ("0" * (64 - (len_binary % 64)))
  151. return [binary_block[i:i + 64] for i in range(0, len(binary_block), 64)]
  152. else:
  153. return [binary[j:j + 64] for j in range(0, len(binary), 64)]
  154. def modify_default_k(self):
  155. """
  156. 修改默认密钥函数
  157. """
  158. print(f'默认密钥的01字符串为:{self.K}', ' ', len(self.K), '位')
  159. print(f'默认密钥的字符串为:{self.str_encode(self.K)}')
  160. newkey = input('输入新的长度为8的密钥:')
  161. if len(newkey) != 8:
  162. print('密钥长度不合法,请重新输入:')
  163. self.modify_default_k()
  164. else:
  165. bin_key = self.bit_encode(newkey)
  166. self.K = bin_key
  167. print(f'当前密钥的01字符串为:{self.K}', ' ', len(self.K), '位')
  168. def f_func(self, right: str, key: str):
  169. """
  170. :param right: 明文二进制的字符串加密过程的右半部分
  171. :param key: 当前轮数的密钥
  172. """
  173. e_result = self.replace(right, self.E) # E扩展置换,对right
  174. xor_result = self.xor_func(e_result, key) # 与本轮子密钥key异或
  175. s_result = self.s_box(xor_result) # 进行S盒压缩置换
  176. p_result = self.replace(s_result, self.P) # P盒置换
  177. return p_result
  178. def get_key_list(self):
  179. key = self.replace(self.K, self.k1)
  180. left_key = key[0:28]
  181. right_key = key[28:56]
  182. keys = []
  183. for i in range(1, 17):
  184. move = self.k0[i - 1]
  185. move_left = left_key[move:28] + left_key[0:move]
  186. move_right = right_key[move:28] + right_key[0:move]
  187. left_key = move_left
  188. right_key = move_right
  189. move_key = left_key + right_key
  190. ki = self.replace(move_key, self.k2)
  191. keys.append(ki)
  192. # print(f'第{i}轮的子密钥为:{ki}')
  193. return keys
  194. def xor_func(self, xor1: str, xor2: str):
  195. """
  196. :return: 异或操作返回的结果
  197. """
  198. size = len(xor1)
  199. result = ""
  200. for i in range(0, size):
  201. result += '0' if xor1[i] == xor2[i] else '1'
  202. return result
  203. def s_box(self, xor_result: str):
  204. """
  205. :param xor_result: 48位01字符串
  206. :return: 48位比特串分为8组,每组6位,将6位变4位,每6位首尾做行号,其余4位做列号,在表中查找对应数值
  207. """
  208. result = ""
  209. for i in range(0, 8): # 将48位数据分为6组,循环进行
  210. block = xor_result[i * 6:(i + 1) * 6] # 切片
  211. line = int(block[0] + block[5], 2)
  212. colmn = int(block[1:4], 2)
  213. res = bin(self.S[i][line * 16 + colmn])[2:]
  214. if len(res) < 4:
  215. res = '0' * (4 - len(res)) + res
  216. result += res
  217. return result
  218. def iteration(self, bin_plaintext: str, key_list: list):
  219. """
  220. :param bin_plaintext: 待加密的64位01字符串
  221. :param key_list: 子密钥列表,共有16个48bit的
  222. """
  223. left = bin_plaintext[0:32]
  224. right = bin_plaintext[32:64]
  225. for i in range(0, 16):
  226. next_lift = right # 本轮的right为下一轮的left
  227. f_result = self.f_func(right, key_list[i])
  228. next_right = self.xor_func(left, f_result) # 下一轮的right由本轮的left与f函数结果异或所得
  229. left = next_lift
  230. right = next_right
  231. print(f'第{i + 1}轮加密/解密的结果为:{left + right}')
  232. bin_plaintext_result = left + right # 准备进行下一轮
  233. return bin_plaintext_result[32:] + bin_plaintext_result[:32]
  234. def encode(self, plaintext):
  235. """
  236. :param plaintext: 明文字符串
  237. :return: 密文字符串
  238. """
  239. bin_plaintext = self.bit_encode(plaintext)
  240. bin_plaintext_block = self.group_by_64bit(bin_plaintext)
  241. ciphertext_bin_list = []
  242. key_list = self.get_key_list()
  243. for i in range(16):
  244. print(f'第{i + 1}轮的加密子密钥为:{key_list[i]}', ' ', len(key_list[i]), '位')
  245. for block in bin_plaintext_block:
  246. # 初代ip置换
  247. sub_ip = self.replace(block, self.ip)
  248. ite_result = self.iteration(sub_ip, key_list)
  249. # ip逆置换
  250. sub_ip1 = self.replace(ite_result, self.ip1)
  251. ciphertext_bin_list.append(sub_ip1)
  252. ciphertext_bin = ''.join(ciphertext_bin_list)
  253. result = self.__bin2int(ciphertext_bin)
  254. return bytes(result).hex().upper()
  255. def decode(self, ciphertext):
  256. '''
  257. :param ciphertext: 密文字符串
  258. :return: 明文字符串
  259. '''
  260. b_ciphertext = binascii.a2b_hex(ciphertext)
  261. bin_ciphertext = self.__int2bin(list(b_ciphertext))
  262. bin_plaintext_list = []
  263. key_list = self.get_key_list()
  264. key_list = key_list[::-1]
  265. for i in range(16):
  266. print(f'第{i + 1}轮的解密子密钥为:{key_list[i]}', ' ', len(key_list[i]), '位')
  267. bin_ciphertext_block = [bin_ciphertext[i:i + 64] for i in range(0, len(bin_ciphertext), 64)]
  268. for block in bin_ciphertext_block:
  269. sub_ip = self.replace(block, self.ip)
  270. ite = self.iteration(sub_ip, key_list)
  271. sub_ip1 = self.replace(ite, self.ip1)
  272. bin_plaintext_list.append(sub_ip1)
  273. bin_plaintext = ''.join(bin_plaintext_list).replace('00000000', '')
  274. return self.str_encode(bin_plaintext)
  275. def main(self):
  276. select = input('请选择想要进行的操作:\n1、加密\t 2、解密\t 3、退出程序\n选择:')
  277. if select == '1':
  278. plaintext = input('请输入要加密的明文:')
  279. ciphertext = self.encode(plaintext)
  280. print(f'生成的密文为:{ciphertext}')
  281. elif select == '2':
  282. plaintext = input('请输入要解密的密文:')
  283. plaintext = self.decode(plaintext)
  284. print(f'对应的明文为:{plaintext}')
  285. # print(len(plaintext))
  286. elif select == '3':
  287. raise SystemExit(0) # 退出程序,返回状态码0
  288. else:
  289. input('输入不合法,请重新选择!')
  290. self.main()
  291. if __name__ == '__main__':
  292. MyDes = DES()
  293. MyDes.modify_default_k()
  294. while True:
  295. MyDes.main()
  296. print("")
实验结果展示:

可以改进的地方:DES算法加密和解密的过程是一样的,因此在encode()与decode()两个代码块中出现了大量的重合,可以把重合的部分单独写一个公共部分的函数,在加密解密时直接调用。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/471539
推荐阅读
相关标签
  

闽ICP备14008679号