在Python中使用ASCII 127以下的字符加密字符串

2024-10-02 14:20:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用这对函数对小字符串进行加密和去加密。始终小于键“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 ""

Tags: 函数字符串inforstringreturnjoinc2
1条回答
网友
1楼 · 发布于 2024-10-02 14:20:43

解密必须按照与加密相反的顺序进行

首先,在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

异或运算的逆运算是异或运算本身,即线

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, c2) in zip(s1, 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€

相关问题 更多 >