我正在使用这对函数来加密和解密小字符串。始终小于键“s2”。
这些函数适用于所有字符都低于 ascii 127 的任何字符串,但是当我将它们与诸如“¡hola!”之类的字符串一起使用时会失败 或“坎西翁”。
编码“¡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 ""