Padding (DES)Padding is used in a block cipher where we fill up the blocks with padding bytes. DES uses 64-bits with a 64-bit encryption key. The main padding methods are:
In the following code we use DES to encrypt and pad the input string. The key is generated by taking a SHA-256 hash of the password (and then taking the first 8 bytes to make 64-bits):
|
Presentation
Sample
If we use "hello", then we must pad to 5 bytes, this means there are 3 padding bytes (0x3) to give:
After padding (CMS): 68656c6c6f030303 Cipher (ECB): 8f770898ddb9fb38 decrypt: hello
If we use "hello1", then we must pad to 6 bytes, this means there are 2 padding bytes (0x2) to give:
After padding (CMS): 68656c6c6f310202 Cipher (ECB): 602743be4d9c6f17 decrypt: hello1
Code
The code generates a 64-bit key by taking the first 8 bytes of a SHA-256 hash value:
# https://asecuritysite.com/encryption/padding_des from Crypto.Cipher import DES import hashlib import sys import binascii import Padding val='hello' password='hello' plaintext=val def encrypt(plaintext,key, mode): encobj = DES.new(key,mode) return(encobj.encrypt(plaintext)) def decrypt(ciphertext,key, mode): encobj = DES.new(key,mode) return(encobj.decrypt(ciphertext)) print("\nDES") key = hashlib.sha256(password.encode()).digest()[:8] plaintext = Padding.appendPadding(plaintext,blocksize=Padding.DES_blocksize,mode='CMS') print("After padding (CMS): ",binascii.hexlify(bytearray(plaintext.encode()))) ciphertext = encrypt(plaintext.encode(),key,DES.MODE_ECB) print("Cipher (ECB): ",binascii.hexlify(bytearray(ciphertext))) plaintext = decrypt(ciphertext,key,DES.MODE_ECB) plaintext = Padding.removePadding(plaintext.decode(),mode='CMS') print(" decrypt: ",plaintext)