在Python中使用低于ASCII 127的字符加密字符串

问题描述

我正在使用这对函数来加密和解密小字符串。始终小于键“ s2”。

函数适用于所有字符都低于ASCII 127的任何字符串,但是当我将它们与诸如“¡hola!”之类的字符串一起使用时,该函数将失败。或“canción”。

编码“哦!”得到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,s2)])   # reverts XOR
    return j                               # the original string
  except:
    return ""

解决方法

解密必须与加密相反。

首先,在encrypt_str行中:

j = "".join(carac.encode('utf-8').hex() for carac in j) 

在功能上等同于:

j = j.encode('utf-8').hex()

其逆是:

s1 = bytes.fromhex(s1).decode('utf-8')

使用desencrypt_str s1中的标签代替j

XOR运算的反函数是XOR运算本身,即行

j = "".join([chr(ord(c1) ^ ord(c2)) for (c1,c2) in zip(s1,s2)])    

对于加密和解密是相同的。对于解密,s1表示密文,s2表示密钥。

这将导致以下解密:

def desencrypt_str(s1):
    try:
        s1 = bytes.fromhex(s1).decode('utf-8')                         
        j = "".join([chr(ord(c1) ^ ord(c2)) for (c1,s2)])    
        return j                               
    except:
        return ""

此处的纯文本和键可以包含任何Unicode字符,例如

s2 = "€9ΩS0αJDJS9375MFJ498DJSWL59S"
ciphertext = encrypt_str("¡hola!canción€")
plaintext = desencrypt_str(ciphertext)
print(plaintext)

显示¡hola!canción€