Photo by Jason D on Unsplash

Symmetric Key, Hazmat and Python

--

Symmetric key methods provide the core foundation of privacy in cybersecurity. With this Bob and Alice have the same encryption key, and this key is used to encrypt and also to decrypt. We normally also add a salt value — known as an IV (Initialization Vector). In this case, we will use the Hazmat primitives in the cryptography library.

For most of the encryption modes we can use the following function:

def go_encrypt(msg,method,mode):
cipher = Cipher(method, mode)
encryptor = cipher.encryptor()
ct = encryptor.update(msg) + encryptor.finalize()
return (ct)


def go_decrypt(ct,method,mode):
cipher = Cipher(method, mode)
decryptor = cipher.decryptor()
return (decryptor.update(ct) + decryptor.finalize())

We can then pass the algorithm with the key, and the mode. In this case, we use the CBC mode with the IV:

cipher=go_encrypt(padded_data,algorithms.AES(key), modes.CBC(iv))

plain=go_decrypt(cipher,algorithms.AES(key), modes.CBC(iv))

Overall we must pad our input data with:

def pad(data,size=128):
padder = padding.PKCS7(size).padder()
padded_data = padder.update(data)
padded_data += padder.finalize()
return(padded_data)

and unpad after decryption with:

def unpad(data,size=128):
padder =…

--

--

Prof Bill Buchanan OBE FRSE
ASecuritySite: When Bob Met Alice

Professor of Cryptography. Serial innovator. Believer in fairness, justice & freedom. Based in Edinburgh. Old World Breaker. New World Creator. Building trust.