def message_encrypt(): encrypted_lines = "" # 读取 DES 密钥 with open('sandbox_sender/desPassword.txt', 'r') as des_password_gotcha: des_pwd = des_password_gotcha.readline().strip() # 移除可能存在的换行符 # 确保 DES 密钥长度为 8 字节 if len(des_pwd) != 8: raise ValueError("DES 密钥长度必须是 8 字节") # 读取原始消息 with open('sandbox_sender/sample.txt', 'r') as original_file: original = original_file.read() # 使用 PKCS#7 填充,使文本长度为 DES 块大小的倍数 (8 字节) original_length = len(original) if original_length % 8 != 0: padding_length = 8 - (original_length % 8) original = original + chr(padding_length) * padding_length # 创建 DES 加密器 des_cipher = DES.new(des_pwd.encode(), DES.MODE_ECB) # 使用 ECB 模式 # 加密文本 encrypted_lines = "" for i in range(0, len(original), 8): block = original[i:i + 8].encode() # 取每个 8 字节块 encrypted_block = des_cipher.encrypt(block) # 加密块 encrypted_lines += encrypted_block.hex() # 将加密结果转换为十六进制字符串 # 将加密后的消息保存到文件 with open('outbox/encrypted_msg.txt', 'w') as container_of_encrypted_contents: container_of_encrypted_contents.write(encrypted_lines) print("Message has been encrypted.")