如何使用python 3中的pycrypto库使用DES加密和解密图像?

问题描述

这是我尝试过的文本加密和解密代码

from Crypto.Cipher import DES
from Crypto import Random

def pad(text):
    while len(text) % 8 != 0:
        text += " "
    return text

def removepad(text):
    reverse = text[::-1]
    for i in range(len(text)):
        if reverse[i] == ' ':
            pass
        else:
            break
    text = reverse[i:]
    text = text[::-1]
    return text

# plaintext = input("Enter Plaintext: ")
# key = input("Enter Key:")
plaintext = 'Encryption and Decryption of DES for OFB mode'
key = 'hellokey'
print("Plaintext: ",plaintext)
print("Key: ",key)
print()

iv = Random.new().read(DES.block_size)
cipher = DES.new(key,DES.MODE_OFB,iv)

plaintext = pad(plaintext)
msg = iv + cipher.encrypt(plaintext)
print("Encrypted Text: ")
print(msg)
print()

decCipher = DES.new(key,msg[:DES.block_size])
msgback = decCipher.decrypt(msg[DES.block_size:])
dmsg = removepad(msgback.decode("utf-8"))
print("Decrypted Text: ")
print(dmsg)

这是上面代码输出

明文:OFB模式下DES的加解密 密钥:hellokey

加密文本: b'\xd5\xc5$\xdc\xac=4*\x91\xfa\x8c\x14\xe7\xbf\xb8\xd6a\x99

解密文本: OFB模式下DES的加解密

解决方法

无论您是否必须使用 DES,DES.new(key,...) 都需要 bytes keycipher.encrypt(plaintext) 需要 bytes {{ 1}} 而不是 plaintext 的,所以使用 bytes 文字 str 或编码为 bytes key = b'hellokey'