encode_decode.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. import os
  2. from typing import List
  3. import math
  4. # 定义算法的块大小(字节)
  5. BLOCK_SIZE = 16 # 例如 128 bits
  6. # 定义轮数
  7. NUM_ROUNDS = 10 # 可以根据需要调整
  8. # 简单的 S-box
  9. # 在实际应用中,S-box 需要精心设计以防止线性攻击和差分攻击
  10. S_BOX = [
  11. 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
  12. 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
  13. 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
  14. 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
  15. 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
  16. 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
  17. 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
  18. 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
  19. 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
  20. 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
  21. 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
  22. 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
  23. 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
  24. 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
  25. 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
  26. 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16,
  27. ]
  28. # 简单的逆 S-box
  29. INV_S_BOX = [S_BOX.index(i) for i in range(256)]
  30. # 简单的置换表 (例如,随机打乱 BLOCK_SIZE 的索引)
  31. # 在实际应用中,置换表也需要精心设计
  32. PERMUTATION_TABLE = list(range(BLOCK_SIZE))
  33. # 可以进一步打乱 PERMUTATION_TABLE,例如:
  34. # import random
  35. # random.shuffle(PERMUTATION_TABLE)
  36. # 逆置换表
  37. INV_PERMUTATION_TABLE = [0] * BLOCK_SIZE
  38. for i, j in enumerate(PERMUTATION_TABLE):
  39. INV_PERMUTATION_TABLE[j] = i
  40. def _bytes_to_matrix(data: bytes) -> List[List[int]]:
  41. """将字节串转换为 BLOCK_SIZE x BLOCK_SIZE 的矩阵形式 (或其他适合处理的形式)"""
  42. # 这里为了简化,直接将字节串视为一个 BLOCK_SIZE 长度的列表
  43. # 更复杂的设计可以将其转换为二维矩阵或其他结构
  44. if len(data) != BLOCK_SIZE:
  45. raise ValueError(f"Data must be exactly {BLOCK_SIZE} bytes.")
  46. return list(data)
  47. def _matrix_to_bytes(matrix: List[int]) -> bytes:
  48. """将矩阵形式的数据转换回字节串"""
  49. if len(matrix) != BLOCK_SIZE:
  50. raise ValueError(f"Matrix must have exactly {BLOCK_SIZE} elements.")
  51. return bytes(matrix)
  52. def _sub_bytes(state: List[int], s_box: List[int]) -> List[int]:
  53. """应用 S-box 替换"""
  54. return [s_box[byte] for byte in state]
  55. def _permute_bytes(state: List[int], permutation_table: List[int]) -> List[int]:
  56. """应用置换"""
  57. return [state[permutation_table[i]] for i in range(BLOCK_SIZE)]
  58. def _xor_bytes(state: List[int], key: bytes) -> List[int]:
  59. """与密钥进行异或"""
  60. if len(state) != len(key):
  61. raise ValueError("State and key must have the same length.")
  62. return [state[i] ^ key[i] for i in range(BLOCK_SIZE)]
  63. def _generate_round_keys(key: bytes, num_rounds: int) -> List[bytes]:
  64. """简单的密钥扩展(需要更复杂的算法来生成高质量的轮密钥)"""
  65. # 这里只是一个占位符,实际应用中需要更强大的密钥调度算法
  66. if len(key) != BLOCK_SIZE:
  67. raise ValueError(f"Key must be exactly {BLOCK_SIZE} bytes.")
  68. round_keys = [key]
  69. # 可以根据某种规则从原密钥派生出更多的轮密钥
  70. for _ in range(num_rounds):
  71. # 这里只是一个简单的例子,可以进行循环移位、与其他常数异或等操作
  72. new_key = bytes([ (b + 1) % 256 for b in round_keys[-1]])
  73. round_keys.append(new_key)
  74. return round_keys
  75. def _encrypt_block(block: bytes, round_keys: List[bytes]) -> bytes:
  76. """加密一个数据块"""
  77. if len(block) != BLOCK_SIZE:
  78. raise ValueError(f"Block must be exactly {BLOCK_SIZE} bytes.")
  79. state = _bytes_to_matrix(block)
  80. # 初始轮与第一个轮密钥异或
  81. state = _xor_bytes(state, round_keys[0])
  82. # 多轮加密
  83. for i in range(1, NUM_ROUNDS + 1):
  84. # S-box 替换
  85. state = _sub_bytes(state, S_BOX)
  86. # 置换
  87. state = _permute_bytes(state, PERMUTATION_TABLE)
  88. # 与轮密钥异或
  89. state = _xor_bytes(state, round_keys[i])
  90. # 这里可以添加更多的混合和扩散操作
  91. return _matrix_to_bytes(state)
  92. def _decrypt_block(block: bytes, round_keys: List[bytes]) -> bytes:
  93. """解密一个数据块"""
  94. if len(block) != BLOCK_SIZE:
  95. raise ValueError(f"Block must be exactly {BLOCK_SIZE} bytes.")
  96. state = _bytes_to_matrix(block)
  97. # 逆向进行多轮解密
  98. for i in range(NUM_ROUNDS, 0, -1):
  99. # 与轮密钥异或 (解密轮密钥是加密轮密钥的逆)
  100. state = _xor_bytes(state, round_keys[i])
  101. # 逆置换
  102. state = _permute_bytes(state, INV_PERMUTATION_TABLE)
  103. # 逆 S-box 替换
  104. state = _sub_bytes(state, INV_S_BOX)
  105. # 这里需要添加对应加密时使用的逆向混合和扩散操作
  106. # 最后与第一个轮密钥异或
  107. state = _xor_bytes(state, round_keys[0])
  108. return _matrix_to_bytes(state)
  109. def encrypt(plaintext: bytes, key: bytes, iv: bytes) -> bytes:
  110. """
  111. 使用自定义对称加密算法加密数据 (计数器模式)
  112. Args:
  113. plaintext: 要加密的明文 (字节串)
  114. key: 秘密密钥 (字节串,长度必须为 BLOCK_SIZE)
  115. iv: 初始化向量 (字节串,长度必须为 BLOCK_SIZE),对于计数器模式是初始计数器值
  116. Returns:
  117. 加密后的密文 (字节串)
  118. """
  119. if len(key) != BLOCK_SIZE:
  120. raise ValueError(f"Key length must be {BLOCK_SIZE} bytes.")
  121. if len(iv) != BLOCK_SIZE:
  122. raise ValueError(f"IV length must be {BLOCK_SIZE} bytes for this mode.")
  123. round_keys = _generate_round_keys(key, NUM_ROUNDS)
  124. ciphertext = b""
  125. plaintext_len = len(plaintext)
  126. # 计算需要处理的完整块数
  127. num_blocks = math.ceil(plaintext_len / BLOCK_SIZE)
  128. for i in range(num_blocks):
  129. # 准备当前明文块
  130. start_index = i * BLOCK_SIZE
  131. end_index = min(start_index + BLOCK_SIZE, plaintext_len)
  132. current_block = plaintext[start_index:end_index]
  133. # 填充最后一个块(如果需要)
  134. if len(current_block) < BLOCK_SIZE:
  135. # 使用零填充,实际应用中可以使用其他填充方案(如 PKCS#7)
  136. current_block += b"\x00" * (BLOCK_SIZE - len(current_block))
  137. # 计算当前轮的计数器值 (作为伪随机流的输入)
  138. # Incrementing the IV for each block
  139. current_counter = int.from_bytes(iv, byteorder='big') + i
  140. counter_block = current_counter.to_bytes(BLOCK_SIZE, byteorder='big')
  141. # 使用计数器值作为输入加密,生成伪随机流
  142. keystream_block = _encrypt_block(counter_block, round_keys)
  143. # 将明文块与伪随机流进行异或
  144. encrypted_block = bytes([current_block[j] ^ keystream_block[j] for j in range(BLOCK_SIZE)])
  145. ciphertext += encrypted_block
  146. # 在这个简单的计数器模式实现中,密文的长度总是 BLOCK_SIZE 的倍数
  147. return ciphertext
  148. def decrypt(ciphertext: bytes, key: bytes, iv: bytes) -> bytes:
  149. """
  150. 使用自定义对称加密算法解密数据 (计数器模式)
  151. Args:
  152. ciphertext: 要解密的密文 (字节串)
  153. key: 秘密密钥 (字节串,长度必须为 BLOCK_SIZE)
  154. iv: 初始化向量 (字节串,长度必须为 BLOCK_SIZE),与加密时使用的相同
  155. Returns:
  156. 解密后的明文 (字节串)
  157. """
  158. if len(key) != BLOCK_SIZE:
  159. raise ValueError(f"Key length must be {BLOCK_SIZE} bytes.")
  160. if len(iv) != BLOCK_SIZE:
  161. raise ValueError(f"IV length must be {BLOCK_SIZE} bytes for this mode.")
  162. if len(ciphertext) % BLOCK_SIZE != 0:
  163. raise ValueError(f"Ciphertext length must be a multiple of {BLOCK_SIZE}.")
  164. round_keys = _generate_round_keys(key, NUM_ROUNDS)
  165. plaintext = b""
  166. ciphertext_len = len(ciphertext)
  167. num_blocks = ciphertext_len // BLOCK_SIZE
  168. for i in range(num_blocks):
  169. # 准备当前密文块
  170. start_index = i * BLOCK_SIZE
  171. end_index = start_index + BLOCK_SIZE
  172. current_block = ciphertext[start_index:end_index]
  173. # 计算当前轮的计数器值 (作为伪随机流的输入)
  174. current_counter = int.from_bytes(iv, byteorder='big') + i
  175. counter_block = current_counter.to_bytes(BLOCK_SIZE, byteorder='big')
  176. # 使用计数器值作为输入加密,生成与加密时相同的伪随机流
  177. keystream_block = _encrypt_block(counter_block, round_keys)
  178. # 将密文块与伪随机流进行异或
  179. decrypted_block = bytes([current_block[j] ^ keystream_block[j] for j in range(BLOCK_SIZE)])
  180. plaintext += decrypted_block
  181. # 在解密后需要移除填充(如果使用了填充)
  182. # 这里假设使用了零填充,需要找到最后一个非零字节的位置(如果适用)
  183. # 这是一个简单的去零填充方法,实际应用中需要根据填充方案进行处理
  184. # 假设最后一个块可能包含填充,需要检查最后一个块的字节,并根据填充方案移除
  185. # 这里为了简化,不去填充
  186. return plaintext
  187. # --- 示例用法 ---
  188. if __name__ == "__main__":
  189. print("--- 自创对称加密算法演示 ---")
  190. # --- 加密部分:用户手动输入明文 ---
  191. print("\n--- 加密 ---")
  192. user_plaintext_str = input("请输入要加密的明文: ")
  193. user_plaintext_data = user_plaintext_str.encode('utf-8') # 将字符串编码为字节串
  194. # 加密时生成随机的密钥和 IV
  195. generated_key = os.urandom(BLOCK_SIZE)
  196. generated_iv = os.urandom(BLOCK_SIZE)
  197. print(f"\n生成的密钥 Secret Key (hex): {generated_key.hex()}")
  198. print(f"生成的初始化向量 Initial Vector (hex): {generated_iv.hex()}")
  199. try:
  200. ciphertext_data = encrypt(user_plaintext_data, generated_key, generated_iv)
  201. print(f"\n生成的密文 Ciphertext (hex): {ciphertext_data.hex()}")
  202. except ValueError as e:
  203. print(f"加密错误: {e}")
  204. exit() # 加密失败则退出
  205. # # --- 解密部分:用户手动输入密钥、IV 和密文 ---
  206. # print("\n--- 解密 ---")
  207. # while True:
  208. # user_key_hex = input(f"请输入 Secret Key (hex, {BLOCK_SIZE*2}位): ")
  209. # try:
  210. # user_key_bytes = bytes.fromhex(user_key_hex)
  211. # if len(user_key_bytes) == BLOCK_SIZE:
  212. # break # 长度正确,跳出循环
  213. # else:
  214. # print(f"错误:密钥长度必须是 {BLOCK_SIZE} 字节(即 {BLOCK_SIZE*2} 位十六进制字符)。请重新输入。")
  215. # except ValueError:
  216. # print("错误:请输入有效的十六进制字符串。")
  217. # while True:
  218. # user_iv_hex = input(f"请输入 Initial Vector (hex, {BLOCK_SIZE*2}位): ")
  219. # try:
  220. # user_iv_bytes = bytes.fromhex(user_iv_hex)
  221. # if len(user_iv_bytes) == BLOCK_SIZE:
  222. # break # 长度正确,跳出循环
  223. # else:
  224. # print(f"错误:IV 长度必须是 {BLOCK_SIZE} 字节(即 {BLOCK_SIZE*2} 位十六进制字符)。请重新输入。")
  225. # except ValueError:
  226. # print("错误:请输入有效的十六进制字符串。")
  227. # while True:
  228. # user_ciphertext_hex = input("请输入 Ciphertext (hex): ")
  229. # try:
  230. # user_ciphertext_bytes = bytes.fromhex(user_ciphertext_hex)
  231. # if len(user_ciphertext_bytes) % BLOCK_SIZE == 0:
  232. # break # 长度是块大小的倍数,跳出循环
  233. # else:
  234. # print(f"错误:密文长度必须是块大小 {BLOCK_SIZE} 字节的倍数。请重新输入。")
  235. # except ValueError:
  236. # print("错误:请输入有效的十六进制字符串。")
  237. # try:
  238. # decrypted_data = decrypt(user_ciphertext_bytes, user_key_bytes, user_iv_bytes)
  239. # # 尝试将解密后的字节串解码为字符串并打印
  240. # try:
  241. # decrypted_str = decrypted_data.decode('utf-8')
  242. # print(f"\n解密后的明文: {decrypted_str}")
  243. # except UnicodeDecodeError:
  244. # # 如果解码失败,说明解密可能不正确,或者原明文不是UTF-8编码的文本
  245. # print("\n解密后的数据无法以 UTF-8 格式解码,可能解密不正确或原数据格式不同。")
  246. # print(f"解密后的字节串 (hex): {decrypted_data.hex()}")
  247. # except ValueError as e:
  248. # print(f"\n解密错误: {e}")