How to avoid backspace/delete/null when print cipher text?

Viewed 34

I am testing a substitution cipher. I'm using the 256 standard ASCII. Here's my code:

def Encrypt(psw, key):
    res = ""
    for i in psw:
        new_letter = chr((ord(i)+key)%255) 
        if new_letter == '\n':
            new_letter = '。'
        res += new_letter
    return res

def Decrypt(psw, key):
    res = ""
    for i in psw:
        if i == '。':
            i = '\n'
        old_letter = chr((ord(i)-key)%255)
        res += old_letter
    return res

if __name__ == "__main__": 
    try:
        while True:
            i = input("1 for encryption, 2 for decryption")
            s = "";k = 0 
            if i == '1':
                s = input("Input Plaintext:")
                k = (int)(input("Input Key:"))
                print("Ciphertext is:"+Encrypt(s, k))
            elif i == '2':
                s = input("Input Ciphertext:")
                k = (int)(input("Input Key:"))
                print("Plaintext is:"+Decrypt(s, k))
            else:
                break
    except:
        print("Error")

When I test some keys, such as 6012, the ciphertext is ãøôøø³ø³ûº³ú I used this result to restore the plaintext, but failed, and it became Peasee me wh's wrong

I think this is due to special operators such as Delete, Backspace, and Null in the encryption process. It caused me to be unable to recover. Is there any way to solve this problem?

1 Answers

Most of the time, you should not print binary data (ciphertext) in a human-text channel (stdout) because it will interpret the non-printable data instead of displaying it.
If what you want is just to be able to copy-paste, you should escape the non-printable bits. One simple way to do it is to use urllib.parse.quote and unquote :

import urllib.parse

[...]

print("Ciphertext is: "+urllib.parse.quote(Encrypt(s, k)))

[...]

s = urllib.parse.unquote(input("Input Ciphertext:"))

Example :

1 for encryption, 2 for decryption
1
Input Plaintext:hello
Input Key:6012
Ciphertext is:%C3%BB%C3%B8%00%00%03

1 for encryption, 2 for decryption
2
Input Ciphertext:%C3%BB%C3%B8%00%00%03
Input Key:6012
Plaintext is:hello
Related