[英]How to encrypt and decrypt image using DES using pycrypto library in python 3?
This is the code that I have tried for text encryption and decryption:这是我尝试用于文本加密和解密的代码:
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)
This is the output for above code:这是上述代码的 output:
Plaintext: Encryption and Decryption of DES for OFB mode Key: hellokey明文:OFB模式下DES的加解密密钥:hellokey
Encrypted Text: 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'加密文本: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'
Decrypted Text: Encryption and Decryption of DES for OFB mode解密文本:OFB模式下DES的加解密
Regardless of whether you have to use DES, DES.new(key, ...)
expects a bytes key
and cipher.encrypt(plaintext)
expects a bytes plaintext
rather than str
ones, so use bytes literals key = b'hellokey'
or encode to bytes msg = iv + cipher.encrypt(plaintext.encode())
.无论您是否必须使用 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.