In: Computer Science
I need the code in python where I can encrypt and decrypt any plaintext. For example, the plaintext "hello" from each of these Block Cipher modes of Operation.
Electronic Code Block Mode (ECB)
Cipher block Mode (CBC)
Cipher Feedback Mode (CFB)
Output feedback Mode (OFB)
Counter Mode (CTR)
Here is an example, Affine cipher expressed in C.
Encryption:
char cipher(unsigned char block, char key) {
return (key+11*block) }
Decryption:
char invcipher(unsigned char block, char key) {
return (163*(block-key+256)) }
Python supports many encryption algorithms. I have provided an
example using one of the simplest Data Encryption Standard (DES)
algorithm in Python.
DES Algorithm is supported in the DES module which is a part of
Pycrypto package.
#This line of code imports the module DES
#Alternatively you can also use: from Crypto.Cipher import
DES
import DES
#This line of code creates an object of type DES
#The first parameter to new function is the key used for
encryption.
# In the second parameter you can select the mode which can be
either of
# the six block cipher modes as follows
# MODE_ECB, MODE_CBC, MODE_CFB, MODE_OFB, MODE_CTR
# if the CBC or CFB modes are used, the new function will have a
third parameter
# The third parameter should be same length as the block
size.
obj = DES.new('key', DES.MODE_ECB)
plaintext = "hello"
# Append string 'PPP' to convert the length of plaintext string
hello into multiple of 8
# for DES algorithm strings are required to be in multiples of
8
#encrypt the block cipher text
ciphertext = obj.encrypt(plaintext+'PPP')
#Decrypt the block cipher text
obj.decrypt(ciphertext)