[英]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.