Padding (3DES) with HazmatIn the following code we use 3DES 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 16 bytes to make 128 bits): |
Presentation
Sample
If we use "hello", then we must pad to 5 bytes, this means there are 3 padding bytes (0x3) to give:
Before padding: hello After padding (CMS): b'68656c6c6f030303' Cipher (ECB): b'8f770898ddb9fb38' decrypt: hello
Code
The code generates a 112-bit key by taking the first 8 bytes of a SHA-256 hash value:
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.primitives import padding from cryptography.hazmat.backends import default_backend import hashlib import binascii val='hello' password='hello123' plaintext=val def encrypt(plaintext,key, mode): method=algorithms.TripleDES(key) cipher = Cipher(method,mode, default_backend()) encryptor = cipher.encryptor() ct = encryptor.update(plaintext) + encryptor.finalize() return(ct) def decrypt(ciphertext,key, mode): method=algorithms.TripleDES(key) cipher = Cipher(method, mode, default_backend()) decryptor = cipher.decryptor() pl = decryptor.update(ciphertext) + decryptor.finalize() return(pl) def pad(data,size=64): padder = padding.PKCS7(size).padder() padded_data = padder.update(data) padded_data += padder.finalize() return(padded_data) def unpad(data,size=64): padder = padding.PKCS7(size).unpadder() unpadded_data = padder.update(data) unpadded_data += padder.finalize() return(unpadded_data) key = hashlib.sha256(password.encode()).digest()[:16] print("Before padding: ",plaintext) plaintext=pad(plaintext.encode()) print("After padding (CMS): ",binascii.hexlify(bytearray(plaintext))) ciphertext = encrypt(plaintext,key,modes.ECB()) print("Cipher (ECB): ",binascii.hexlify(bytearray(ciphertext))) plaintext = decrypt(ciphertext,key,modes.ECB()) plaintext = unpad(plaintext) print(" decrypt: ",plaintext.decode())