|
|
@@ -0,0 +1,308 @@
|
|
|
+import os
|
|
|
+from typing import List
|
|
|
+import math
|
|
|
+
|
|
|
+# 定义算法的块大小(字节)
|
|
|
+BLOCK_SIZE = 16 # 例如 128 bits
|
|
|
+
|
|
|
+# 定义轮数
|
|
|
+NUM_ROUNDS = 10 # 可以根据需要调整
|
|
|
+
|
|
|
+# 简单的 S-box
|
|
|
+# 在实际应用中,S-box 需要精心设计以防止线性攻击和差分攻击
|
|
|
+S_BOX = [
|
|
|
+ 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
|
|
|
+ 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
|
|
|
+ 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
|
|
|
+ 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
|
|
|
+ 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
|
|
|
+ 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
|
|
|
+ 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
|
|
|
+ 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
|
|
|
+ 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
|
|
|
+ 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
|
|
|
+ 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
|
|
|
+ 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
|
|
|
+ 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
|
|
|
+ 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
|
|
|
+ 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
|
|
|
+ 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16,
|
|
|
+]
|
|
|
+
|
|
|
+# 简单的逆 S-box
|
|
|
+INV_S_BOX = [S_BOX.index(i) for i in range(256)]
|
|
|
+
|
|
|
+# 简单的置换表 (例如,随机打乱 BLOCK_SIZE 的索引)
|
|
|
+# 在实际应用中,置换表也需要精心设计
|
|
|
+PERMUTATION_TABLE = list(range(BLOCK_SIZE))
|
|
|
+# 可以进一步打乱 PERMUTATION_TABLE,例如:
|
|
|
+# import random
|
|
|
+# random.shuffle(PERMUTATION_TABLE)
|
|
|
+
|
|
|
+# 逆置换表
|
|
|
+INV_PERMUTATION_TABLE = [0] * BLOCK_SIZE
|
|
|
+for i, j in enumerate(PERMUTATION_TABLE):
|
|
|
+ INV_PERMUTATION_TABLE[j] = i
|
|
|
+
|
|
|
+def _bytes_to_matrix(data: bytes) -> List[List[int]]:
|
|
|
+ """将字节串转换为 BLOCK_SIZE x BLOCK_SIZE 的矩阵形式 (或其他适合处理的形式)"""
|
|
|
+ # 这里为了简化,直接将字节串视为一个 BLOCK_SIZE 长度的列表
|
|
|
+ # 更复杂的设计可以将其转换为二维矩阵或其他结构
|
|
|
+ if len(data) != BLOCK_SIZE:
|
|
|
+ raise ValueError(f"Data must be exactly {BLOCK_SIZE} bytes.")
|
|
|
+ return list(data)
|
|
|
+
|
|
|
+def _matrix_to_bytes(matrix: List[int]) -> bytes:
|
|
|
+ """将矩阵形式的数据转换回字节串"""
|
|
|
+ if len(matrix) != BLOCK_SIZE:
|
|
|
+ raise ValueError(f"Matrix must have exactly {BLOCK_SIZE} elements.")
|
|
|
+ return bytes(matrix)
|
|
|
+
|
|
|
+def _sub_bytes(state: List[int], s_box: List[int]) -> List[int]:
|
|
|
+ """应用 S-box 替换"""
|
|
|
+ return [s_box[byte] for byte in state]
|
|
|
+
|
|
|
+def _permute_bytes(state: List[int], permutation_table: List[int]) -> List[int]:
|
|
|
+ """应用置换"""
|
|
|
+ return [state[permutation_table[i]] for i in range(BLOCK_SIZE)]
|
|
|
+
|
|
|
+def _xor_bytes(state: List[int], key: bytes) -> List[int]:
|
|
|
+ """与密钥进行异或"""
|
|
|
+ if len(state) != len(key):
|
|
|
+ raise ValueError("State and key must have the same length.")
|
|
|
+ return [state[i] ^ key[i] for i in range(BLOCK_SIZE)]
|
|
|
+
|
|
|
+def _generate_round_keys(key: bytes, num_rounds: int) -> List[bytes]:
|
|
|
+ """简单的密钥扩展(需要更复杂的算法来生成高质量的轮密钥)"""
|
|
|
+ # 这里只是一个占位符,实际应用中需要更强大的密钥调度算法
|
|
|
+ if len(key) != BLOCK_SIZE:
|
|
|
+ raise ValueError(f"Key must be exactly {BLOCK_SIZE} bytes.")
|
|
|
+ round_keys = [key]
|
|
|
+ # 可以根据某种规则从原密钥派生出更多的轮密钥
|
|
|
+ for _ in range(num_rounds):
|
|
|
+ # 这里只是一个简单的例子,可以进行循环移位、与其他常数异或等操作
|
|
|
+ new_key = bytes([ (b + 1) % 256 for b in round_keys[-1]])
|
|
|
+ round_keys.append(new_key)
|
|
|
+ return round_keys
|
|
|
+
|
|
|
+def _encrypt_block(block: bytes, round_keys: List[bytes]) -> bytes:
|
|
|
+ """加密一个数据块"""
|
|
|
+ if len(block) != BLOCK_SIZE:
|
|
|
+ raise ValueError(f"Block must be exactly {BLOCK_SIZE} bytes.")
|
|
|
+
|
|
|
+ state = _bytes_to_matrix(block)
|
|
|
+
|
|
|
+ # 初始轮与第一个轮密钥异或
|
|
|
+ state = _xor_bytes(state, round_keys[0])
|
|
|
+
|
|
|
+ # 多轮加密
|
|
|
+ for i in range(1, NUM_ROUNDS + 1):
|
|
|
+ # S-box 替换
|
|
|
+ state = _sub_bytes(state, S_BOX)
|
|
|
+ # 置换
|
|
|
+ state = _permute_bytes(state, PERMUTATION_TABLE)
|
|
|
+ # 与轮密钥异或
|
|
|
+ state = _xor_bytes(state, round_keys[i])
|
|
|
+
|
|
|
+ # 这里可以添加更多的混合和扩散操作
|
|
|
+
|
|
|
+ return _matrix_to_bytes(state)
|
|
|
+
|
|
|
+def _decrypt_block(block: bytes, round_keys: List[bytes]) -> bytes:
|
|
|
+ """解密一个数据块"""
|
|
|
+ if len(block) != BLOCK_SIZE:
|
|
|
+ raise ValueError(f"Block must be exactly {BLOCK_SIZE} bytes.")
|
|
|
+
|
|
|
+ state = _bytes_to_matrix(block)
|
|
|
+
|
|
|
+ # 逆向进行多轮解密
|
|
|
+ for i in range(NUM_ROUNDS, 0, -1):
|
|
|
+ # 与轮密钥异或 (解密轮密钥是加密轮密钥的逆)
|
|
|
+ state = _xor_bytes(state, round_keys[i])
|
|
|
+ # 逆置换
|
|
|
+ state = _permute_bytes(state, INV_PERMUTATION_TABLE)
|
|
|
+ # 逆 S-box 替换
|
|
|
+ state = _sub_bytes(state, INV_S_BOX)
|
|
|
+
|
|
|
+ # 这里需要添加对应加密时使用的逆向混合和扩散操作
|
|
|
+
|
|
|
+ # 最后与第一个轮密钥异或
|
|
|
+ state = _xor_bytes(state, round_keys[0])
|
|
|
+
|
|
|
+ return _matrix_to_bytes(state)
|
|
|
+
|
|
|
+def encrypt(plaintext: bytes, key: bytes, iv: bytes) -> bytes:
|
|
|
+ """
|
|
|
+ 使用自定义对称加密算法加密数据 (计数器模式)
|
|
|
+
|
|
|
+ Args:
|
|
|
+ plaintext: 要加密的明文 (字节串)
|
|
|
+ key: 秘密密钥 (字节串,长度必须为 BLOCK_SIZE)
|
|
|
+ iv: 初始化向量 (字节串,长度必须为 BLOCK_SIZE),对于计数器模式是初始计数器值
|
|
|
+
|
|
|
+ Returns:
|
|
|
+ 加密后的密文 (字节串)
|
|
|
+ """
|
|
|
+ if len(key) != BLOCK_SIZE:
|
|
|
+ raise ValueError(f"Key length must be {BLOCK_SIZE} bytes.")
|
|
|
+ if len(iv) != BLOCK_SIZE:
|
|
|
+ raise ValueError(f"IV length must be {BLOCK_SIZE} bytes for this mode.")
|
|
|
+
|
|
|
+ round_keys = _generate_round_keys(key, NUM_ROUNDS)
|
|
|
+ ciphertext = b""
|
|
|
+ plaintext_len = len(plaintext)
|
|
|
+
|
|
|
+ # 计算需要处理的完整块数
|
|
|
+ num_blocks = math.ceil(plaintext_len / BLOCK_SIZE)
|
|
|
+
|
|
|
+ for i in range(num_blocks):
|
|
|
+ # 准备当前明文块
|
|
|
+ start_index = i * BLOCK_SIZE
|
|
|
+ end_index = min(start_index + BLOCK_SIZE, plaintext_len)
|
|
|
+ current_block = plaintext[start_index:end_index]
|
|
|
+
|
|
|
+ # 填充最后一个块(如果需要)
|
|
|
+ if len(current_block) < BLOCK_SIZE:
|
|
|
+ # 使用零填充,实际应用中可以使用其他填充方案(如 PKCS#7)
|
|
|
+ current_block += b"\x00" * (BLOCK_SIZE - len(current_block))
|
|
|
+
|
|
|
+ # 计算当前轮的计数器值 (作为伪随机流的输入)
|
|
|
+ # Incrementing the IV for each block
|
|
|
+ current_counter = int.from_bytes(iv, byteorder='big') + i
|
|
|
+ counter_block = current_counter.to_bytes(BLOCK_SIZE, byteorder='big')
|
|
|
+
|
|
|
+ # 使用计数器值作为输入加密,生成伪随机流
|
|
|
+ keystream_block = _encrypt_block(counter_block, round_keys)
|
|
|
+
|
|
|
+ # 将明文块与伪随机流进行异或
|
|
|
+ encrypted_block = bytes([current_block[j] ^ keystream_block[j] for j in range(BLOCK_SIZE)])
|
|
|
+
|
|
|
+ ciphertext += encrypted_block
|
|
|
+
|
|
|
+ # 在这个简单的计数器模式实现中,密文的长度总是 BLOCK_SIZE 的倍数
|
|
|
+ return ciphertext
|
|
|
+
|
|
|
+def decrypt(ciphertext: bytes, key: bytes, iv: bytes) -> bytes:
|
|
|
+ """
|
|
|
+ 使用自定义对称加密算法解密数据 (计数器模式)
|
|
|
+
|
|
|
+ Args:
|
|
|
+ ciphertext: 要解密的密文 (字节串)
|
|
|
+ key: 秘密密钥 (字节串,长度必须为 BLOCK_SIZE)
|
|
|
+ iv: 初始化向量 (字节串,长度必须为 BLOCK_SIZE),与加密时使用的相同
|
|
|
+
|
|
|
+ Returns:
|
|
|
+ 解密后的明文 (字节串)
|
|
|
+ """
|
|
|
+ if len(key) != BLOCK_SIZE:
|
|
|
+ raise ValueError(f"Key length must be {BLOCK_SIZE} bytes.")
|
|
|
+ if len(iv) != BLOCK_SIZE:
|
|
|
+ raise ValueError(f"IV length must be {BLOCK_SIZE} bytes for this mode.")
|
|
|
+ if len(ciphertext) % BLOCK_SIZE != 0:
|
|
|
+ raise ValueError(f"Ciphertext length must be a multiple of {BLOCK_SIZE}.")
|
|
|
+
|
|
|
+ round_keys = _generate_round_keys(key, NUM_ROUNDS)
|
|
|
+ plaintext = b""
|
|
|
+ ciphertext_len = len(ciphertext)
|
|
|
+ num_blocks = ciphertext_len // BLOCK_SIZE
|
|
|
+
|
|
|
+ for i in range(num_blocks):
|
|
|
+ # 准备当前密文块
|
|
|
+ start_index = i * BLOCK_SIZE
|
|
|
+ end_index = start_index + BLOCK_SIZE
|
|
|
+ current_block = ciphertext[start_index:end_index]
|
|
|
+
|
|
|
+ # 计算当前轮的计数器值 (作为伪随机流的输入)
|
|
|
+ current_counter = int.from_bytes(iv, byteorder='big') + i
|
|
|
+ counter_block = current_counter.to_bytes(BLOCK_SIZE, byteorder='big')
|
|
|
+
|
|
|
+ # 使用计数器值作为输入加密,生成与加密时相同的伪随机流
|
|
|
+ keystream_block = _encrypt_block(counter_block, round_keys)
|
|
|
+
|
|
|
+ # 将密文块与伪随机流进行异或
|
|
|
+ decrypted_block = bytes([current_block[j] ^ keystream_block[j] for j in range(BLOCK_SIZE)])
|
|
|
+
|
|
|
+ plaintext += decrypted_block
|
|
|
+
|
|
|
+ # 在解密后需要移除填充(如果使用了填充)
|
|
|
+ # 这里假设使用了零填充,需要找到最后一个非零字节的位置(如果适用)
|
|
|
+ # 这是一个简单的去零填充方法,实际应用中需要根据填充方案进行处理
|
|
|
+ # 假设最后一个块可能包含填充,需要检查最后一个块的字节,并根据填充方案移除
|
|
|
+ # 这里为了简化,不去填充
|
|
|
+
|
|
|
+ return plaintext
|
|
|
+
|
|
|
+# --- 示例用法 ---
|
|
|
+
|
|
|
+if __name__ == "__main__":
|
|
|
+ print("--- 自创对称加密算法演示 ---")
|
|
|
+
|
|
|
+ # --- 加密部分:用户手动输入明文 ---
|
|
|
+ print("\n--- 加密 ---")
|
|
|
+ user_plaintext_str = input("请输入要加密的明文: ")
|
|
|
+ user_plaintext_data = user_plaintext_str.encode('utf-8') # 将字符串编码为字节串
|
|
|
+
|
|
|
+ # 加密时生成随机的密钥和 IV
|
|
|
+ generated_key = os.urandom(BLOCK_SIZE)
|
|
|
+ generated_iv = os.urandom(BLOCK_SIZE)
|
|
|
+
|
|
|
+ print(f"\n生成的密钥 Secret Key (hex): {generated_key.hex()}")
|
|
|
+ print(f"生成的初始化向量 Initial Vector (hex): {generated_iv.hex()}")
|
|
|
+
|
|
|
+ try:
|
|
|
+ ciphertext_data = encrypt(user_plaintext_data, generated_key, generated_iv)
|
|
|
+ print(f"\n生成的密文 Ciphertext (hex): {ciphertext_data.hex()}")
|
|
|
+ except ValueError as e:
|
|
|
+ print(f"加密错误: {e}")
|
|
|
+ exit() # 加密失败则退出
|
|
|
+
|
|
|
+ # # --- 解密部分:用户手动输入密钥、IV 和密文 ---
|
|
|
+ # print("\n--- 解密 ---")
|
|
|
+
|
|
|
+ # while True:
|
|
|
+ # user_key_hex = input(f"请输入 Secret Key (hex, {BLOCK_SIZE*2}位): ")
|
|
|
+ # try:
|
|
|
+ # user_key_bytes = bytes.fromhex(user_key_hex)
|
|
|
+ # if len(user_key_bytes) == BLOCK_SIZE:
|
|
|
+ # break # 长度正确,跳出循环
|
|
|
+ # else:
|
|
|
+ # print(f"错误:密钥长度必须是 {BLOCK_SIZE} 字节(即 {BLOCK_SIZE*2} 位十六进制字符)。请重新输入。")
|
|
|
+ # except ValueError:
|
|
|
+ # print("错误:请输入有效的十六进制字符串。")
|
|
|
+
|
|
|
+ # while True:
|
|
|
+ # user_iv_hex = input(f"请输入 Initial Vector (hex, {BLOCK_SIZE*2}位): ")
|
|
|
+ # try:
|
|
|
+ # user_iv_bytes = bytes.fromhex(user_iv_hex)
|
|
|
+ # if len(user_iv_bytes) == BLOCK_SIZE:
|
|
|
+ # break # 长度正确,跳出循环
|
|
|
+ # else:
|
|
|
+ # print(f"错误:IV 长度必须是 {BLOCK_SIZE} 字节(即 {BLOCK_SIZE*2} 位十六进制字符)。请重新输入。")
|
|
|
+ # except ValueError:
|
|
|
+ # print("错误:请输入有效的十六进制字符串。")
|
|
|
+
|
|
|
+ # while True:
|
|
|
+ # user_ciphertext_hex = input("请输入 Ciphertext (hex): ")
|
|
|
+ # try:
|
|
|
+ # user_ciphertext_bytes = bytes.fromhex(user_ciphertext_hex)
|
|
|
+ # if len(user_ciphertext_bytes) % BLOCK_SIZE == 0:
|
|
|
+ # break # 长度是块大小的倍数,跳出循环
|
|
|
+ # else:
|
|
|
+ # print(f"错误:密文长度必须是块大小 {BLOCK_SIZE} 字节的倍数。请重新输入。")
|
|
|
+ # except ValueError:
|
|
|
+ # print("错误:请输入有效的十六进制字符串。")
|
|
|
+
|
|
|
+ # try:
|
|
|
+ # decrypted_data = decrypt(user_ciphertext_bytes, user_key_bytes, user_iv_bytes)
|
|
|
+
|
|
|
+ # # 尝试将解密后的字节串解码为字符串并打印
|
|
|
+ # try:
|
|
|
+ # decrypted_str = decrypted_data.decode('utf-8')
|
|
|
+ # print(f"\n解密后的明文: {decrypted_str}")
|
|
|
+ # except UnicodeDecodeError:
|
|
|
+ # # 如果解码失败,说明解密可能不正确,或者原明文不是UTF-8编码的文本
|
|
|
+ # print("\n解密后的数据无法以 UTF-8 格式解码,可能解密不正确或原数据格式不同。")
|
|
|
+ # print(f"解密后的字节串 (hex): {decrypted_data.hex()}")
|
|
|
+
|
|
|
+ # except ValueError as e:
|
|
|
+ # print(f"\n解密错误: {e}")
|