Reputation: 1
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:
Plaintext: Encryption and Decryption of DES for OFB mode Key: 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'
Decrypted Text: Encryption and Decryption of DES for OFB mode
Upvotes: 0
Views: 1825
Reputation: 19375
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())
.
Upvotes: 2