Ciphering, Deciphering, Hashing and HMAC’ing In Python
Entering Python
3 min readMar 5
--
Configuration
hash_algorithm = "sha256"
timestamp_epoch_time_start = 0
timestamp_epoch_time_end = 10*365*24*60*60
key_length_RSA = 2048
message = b"Hello, world!"
Ciphering, Deciphering, Hashing And HMAC’ing Of Messages (Symmetric)
import os
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.hazmat.primitives import hashes, hmackey = os.urandom(32) # Generate a 256-bit encryption key
nonce = os.urandom(12) # Generate a random 96-bit nonceplaintext = message # message to encrypt# Encrypt the message using AES-GCM
object_aesgcm = AESGCM(key)
ciphertext = object_aesgcm.encrypt(nonce, plaintext, None)"""
key = b"\x98\xe5\xe6\x5a\x1e\xf6\x13\x6e\xdc\xef\xbc\x9d\x6e\x3a\xfd\x5c\xc6\xf8\x32\x41\x84\xab\x84\x10\x1a\x5d\xfd\x07\x2d\xf8\x96\x15"
nonce = b"\xc3\x23\x35\x12\x4a\xb4\x7e\x4b\x00\x7c\x9e\xa2"
"""plaintext_recovered = object_aesgcm.decrypt(nonce, ciphertext, None)print(plaintext_recovered)
print(plaintext_recovered.decode("utf-8"))# Compute the SHA-256 hash of the ciphertext
digest = hashes.Hash(hashes.SHA256())
digest.update(ciphertext)
hash_value = digest.finalize()print("Key:", key.hex())
print("Nonce:", nonce.hex())
print("Ciphertext:", ciphertext.hex())
print("Hash:", hash_value.hex())# Compute an HMAC-SHA256 of the ciphertext using a separate key
hmac_key = os.urandom(32)
hmac_obj = hmac.HMAC(hmac_key, hashes.SHA256())
hmac_obj.update(ciphertext)
hmac_value = hmac_obj.finalize()print("Key:", key.hex())
print("Nonce:", nonce.hex())
print("Ciphertext:", ciphertext.hex())
print("Hash:", hash_value.hex())
print("HMAC:", hmac_value.hex())
_
Ciphering, Deciphering, Hashing And HMAC’ing Of Messages (Asymmetric)
#!pip install pycryptodome
from Crypto.Cipher import PKCS1_OAEP
from Crypto.PublicKey import RSA
import randomkey_length_RSA_in_bits = 2048
key_length_session_in_bytes = 32# Generate a new RSA key pair
a_key_pair = RSA.generate(key_length_RSA_in_bits)
""" to use…