我使用这对函数对小字符串进行加密和去加密。始终小于键“s2”
这些函数适用于所有字符都低于ascii 127的任何字符串,但当我将它们与“hola!”或“canción”等字符串一起使用时会失败
编码“hola!”得到b'\xc2\xa1hola!',这种格式正在粉碎desencrypt_str()的结果
我尝试过几种方法,但都无法奏效
关于如何改进功能有什么想法吗
s2 = "A9BS03JJDJS9375MFJ498DJSWL59S" # a string as "key", assume it´s longer than any s1
def encrypt_str(s1):
try:
j = "".join([chr(ord(c1) ^ ord(c2)) for (c1, c2) in zip(s1, s2)]) # XOR
j = "".join(carac.encode('utf-8').hex() for carac in j) # converts to hexa chars
return j # a readable string
except:
return ""
def desencrypt_str(s1):
try:
s1 = bytes.fromhex(s1) # encrypted string with hexa values
j = "".join([chr(c1 ^ ord(c2)) for (c1, c2) in zip(s1, s2)]) # reverts XOR
return j # the original string
except:
return ""
解密必须按照与加密相反的顺序进行
首先,在
encrypt_str
行中:在功能上与:
其反比为:
而关于
desencrypt_str
中的标记,使用s1
代替j
异或运算的逆运算是异或运算本身,即线
对于加密和解密是相同的。对于解密
s1
表示密文s2
表示密钥这将导致以下解密操作:
此处,明文和密钥可以包含任何Unicode字符,例如
显示
¡hola!canción€
相关问题 更多 >
编程相关推荐