Sobes.tech
Junior
249

What is the difference between hashing and encryption?

Answer from AI

sobes.tech AI

Hashing transforms input data into a fixed hash code, an irreversible process. Encryption transforms data into unreadable ciphertext, reversible with a key.

The main differences are shown in the table:

Characteristic Hashing Encryption
Purpose Integrity verification, quick identification Ensuring confidentiality
Reversibility Irreversible Reversible (with a key)
Output size Fixed size (hash) Variable size (often larger/equal to input)
Requires a key No Yes (for encryption and/or decryption)

Example of hashing (SHA-256):

import hashlib

data = b"Secret data"
hash_object = hashlib.sha256(data)
hex_digest = hash_object.hexdigest()
// print(hex_digest) // Prints hash in hexadecimal format

Example of symmetric encryption (AES with cryptography):

from cryptography.fernet import Fernet

// Generate key
key = Fernet.generate_key()
cipher_suite = Fernet(key)

// Encryption
plain_text = b"Confidential message"
cipher_text = cipher_suite.encrypt(plain_text)
// print(cipher_text)

// Decryption
decrypted_text = cipher_suite.decrypt(cipher_text)
// print(decrypted_text) // b'Confidential message'