python - 使用自己的字母字符串解密密文时遇到问题(python)

标签 python python-3.x encryption

我将其设置为询问用户一个要加密的单词,使用我自己的字母表可以正常工作。

我的问题是试图让它返回解密的文本。

到目前为止,我要么返回加密消息两次,要么发回不同版本的加密消息。

我尝试在 for char 中使用 - 而不是 +,它给了我一个错误,我认为这是正确的方法。

alphabet = "abcdefghijklmnopqrstuvwxyz"
key      = "zjrekydnqoluaxmicvpgtfbhws"


def decryptMessage(ciphertext, key):
    
    plaintext = ""
    for char in ciphertext:
        
        if alphabet.find(char) < +1:
             plaintext += key[alphabet.find(char)]
        else:
                 plaintext += char
    
    
    return plaintext


def encryptMessage(plaintext, key):
   
    ciphertext = ""

    
    for char in plaintext:
       
        if alphabet.find(char) > -1:
            ciphertext += key[alphabet.find(char)]
        else:
            ciphertext += char
    
    
    return ciphertext


message = input("Type a message to encrypt: ")


encrypted = encryptMessage(message, key)


decrypted = decryptMessage(encrypted, key)


print("Plaintext message: " + message)
print("Encrypted message: " + encrypted)
print("Decrypted message: " + decrypted)

最佳答案

你应该使用内置的str.translate

message = "hello world"
alphabet = b"abcdefghijklmnopqrstuvwxyz"
key      = b"zjrekydnqoluaxmicvpgtfbhws"
encrypted = message.translate(dict(zip(alphabet,key)))
print("E:",encrypted)
decrypted = encrypted.translate(dict(zip(key,alphabet)))
print("D:",decrypted)

关于python - 使用自己的字母字符串解密密文时遇到问题(python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74008889/

相关文章:

python - 比较列表中的相邻变量并重新格式化输入

java - 在没有应用程序策略的情况下对 JBoss 中的数据源密码进行加密

Python:这种 {} 格式如何提取正确的数据?

python - 快速排序中间列表打印Python

python - python中的"Unknown problem while loading the specified device driver."错误

java - 写入我的 CipherStream 不会写入我的 ByteArrayOutputStream

python - 如何将 AES 模式从一种迁移到另一种?

python - 如何让游戏中的零食以随机颜色出现?

python - 我可以将计数器反转为没有倍数的列表列表吗?

python - 如何在多个条件下更新值