繁体   English   中英

python中特定语言如何加解密

[英]How to encrypt and decrypt specific language in python

我正在学习如何“加密”和“解密”python 中的消息,到目前为止,只有英文消息可以从字母列表中成功解密,但是如果我尝试键入特定语言消息,例如 こんニちは,结果与加密语言,我尝试使用 uft-8 和 utf8 进行加密,我可以从字母列表中得到乱码,但如果我尝试解密它,最终结果与我想要的加密消息不同。

alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',]


def casear(start_text, shift_number, cipher_direction):
    
    end_text = ""
    
    if cipher_direction == "d":
        shift_number *= -1
        
    for char in start_text:
        if char in alphabet:
            position = alphabet.index(char)
            new_position = position + shift_number
            end_text += alphabet[new_position]
        else:
            end_text += char
    print(f"Here is the e{cipher_direction} result:---> {end_text}: ")

final = False

while not final:
    direction = input("Enter 'e' to encrypt, Enter 'd' to decrypt: ").lower()

    text = input("Enter massage: ").lower()
    
    shift = int(input("Enter cover number: "))

    shift = shift % 26
    
    casear(start_text=text, shift_number=shift, cipher_direction=direction)    

    restart = input("Enter 'Y' continue, Enter 'e' finish: ")
    if restart == 'e':
        final = True
        print("Bye")

首先,你必须将它(unicode 字符串'こんニちは')转换为字节

s = "こんにちは"
s_bytes = s.encode('utf8')
print(s,"=>",s_bytes)

那么你需要移动每个字节

def shift3(s_bytes):
    for b in s_bytes:
        b += 3
        if b > 255: # wrap if too big for 1 byte
           b = b - 255
        yield b # iterators make it easier to reason imho

encrypted_bytes = bytes(list(shift3(s_bytes)))
print("ENCRYPTED:",encrypted_bytes) # probably you should not try to decode these

然后扭转它你只是......好吧扭转它

def unshift3(encrypted_bytes):
    for b in encrypted_bytes:
        b -= 3 # reverse it
        if b < 0:
           b = 255 + b # wrap it
        yield b

decrypted_bytes = bytes(list(unshift3(encrypted_bytes)))
print("SAME?",decrypted_bytes == s_bytes) # yup!
print(decrypted_bytes.decode("utf8")) # back to unicode sir

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM