Python3替换加密解密函数开发:基于密码生成密钥及去空格处理
实现替换加密与解密的Python方案
嘿,我来帮你搞定这个替换加密解密的实现!按照你的需求,我们需要三个核心函数:genKeyFromPass(用密码生成密钥)、substitutionEncrypt(加密)和substitutionDecrypt(解密),下面一步步来写:
1. 密码转密钥函数:genKeyFromPass
替换加密需要一个26个字母的唯一排列作为密钥,这个函数的作用就是把任意密码转换成符合要求的密钥。我们用SHA-256哈希生成随机序列,再去重补全剩余字母:
import hashlib def genKeyFromPass(psw): # 对密码进行哈希,生成足够随机的字节序列 hash_obj = hashlib.sha256(psw.encode('utf-8')) hash_str = hash_obj.hexdigest() # 筛选哈希字符串中的字母,去重 key_chars = [] seen = set() for char in hash_str: if char.isalpha() and char not in seen: seen.add(char.lower()) key_chars.append(char.lower()) # 补全剩下未出现的字母,按顺序添加 for char in 'abcdefghijklmnopqrstuvwxyz': if char not in seen: key_chars.append(char) # 取前26个字符作为密钥(确保长度正好26) return ''.join(key_chars[:26])
2. 加密函数:substitutionEncrypt
按照要求,这个函数会先移除明文所有空格,再用密码生成密钥,最后完成替换加密:
def substitutionEncrypt(plainText, psw): # 第一步:移除明文所有空格 plainText_no_space = plainText.replace(" ", "") # 第二步:用密码生成加密密钥 key = genKeyFromPass(psw) # 创建明文到密文的映射表(小写字母) encrypt_map = {chr(ord('a') + i): key[i] for i in range(26)} cipherText = [] for char in plainText_no_space: if char.islower(): cipherText.append(encrypt_map[char]) elif char.isupper(): # 处理大写字母,映射后转成大写 cipherText.append(encrypt_map[char.lower()].upper()) else: # 如果有非字母字符,直接保留(根据需求可调整) cipherText.append(char) return ''.join(cipherText)
3. 解密函数:substitutionDecrypt
这个函数接收密文和密码,生成密钥后反向映射,还原出无空格的原始明文:
def substitutionDecrypt(cipherText, psw): # 用密码生成密钥(和加密用同一个密钥生成逻辑) key = genKeyFromPass(psw) # 创建密文到明文的反向映射表 decrypt_map = {key[i]: chr(ord('a') + i) for i in range(26)} plainText = [] for char in cipherText: if char.islower(): plainText.append(decrypt_map[char]) elif char.isupper(): # 处理大写密文,映射后转成大写 plainText.append(decrypt_map[char.lower()].upper()) else: # 非字母字符直接保留 plainText.append(char) return ''.join(plainText)
测试一下整个流程
我们可以用一段测试文本验证加密解密是否正常:
# 测试示例 original_plain = "Hello World This Is Substitution Cipher" password = "MySecurePass123" # 加密 cipher = substitutionEncrypt(original_plain, password) print(f"加密后的密文:{cipher}") # 解密 decrypted_plain = substitutionDecrypt(cipher, password) print(f"解密后的明文:{decrypted_plain}") print(f"解密结果是否匹配原始无空格明文:{decrypted_plain == original_plain.replace(' ', '')}")
运行这段代码后,你会看到解密后的明文和原始明文移除空格后的结果完全一致,说明整个流程是正确的。
内容的提问来源于stack exchange,提问作者Emma Steele
相关产品推荐
相关产品推荐

