如何在python中加密和解密特定语言



我正在学习如何在python中"加密"one_answers"解密"消息,到目前为止,只有英文消息可以从字母表列表中成功解密。但是,如果我尝试键入特定语言的消息,例如こんにちは在结果与加密语言相同后,我尝试使用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

最新更新