簡體   English   中英

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

[英]How to encrypt and decrypt image using DES using pycrypto library in python 3?

這是我嘗試用於文本加密和解密的代碼:

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, DES.MODE_OFB, msg[:DES.block_size])
msgback = decCipher.decrypt(msg[DES.block_size:])
dmsg = removepad(msgback.decode("utf-8"))
print("Decrypted Text: ")
print(dmsg)

這是上述代碼的 output:

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

加密文本:b'\xd5\xc5$\xdc\xac=4*\x91\xfa\x8c\x14\xe7\xbf\xb8\xd6a\x99<\xca\x132\x8d\xa3Q\xfd\xdf\x9cDQ \xd4\xd4e\xc3\xde"4x<\xa0\x8d\x11\x80\x97g:\xdam\x8a\xdfl\xcbaxu\xbe'

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

無論您是否必須使用 DES, DES.new(key, ...)都需要字節key ,而cipher.encrypt(plaintext)需要字節plaintext而不是str ,因此請使用字節文字key = b'hellokey'或編碼為字節msg = iv + cipher.encrypt(plaintext.encode())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM