Online admissions open for the SEO, web development and networking & cybersecurity courses. Enquire for the next batch.

Encryption vs Hashing: Differences, Password Storage and HMAC

5 min read Updated By the SkillNewton team

What is the difference between encryption and hashing?

Encryption is reversible: data is scrambled with a key and anyone holding the right key can turn it back into the original. Hashing is one-way: a function turns any input into a fixed-length digest that cannot be reversed. Use encryption to keep data secret but recoverable, and hashing to check integrity or store passwords.

Reversible vs one-way: the core difference

PropertyEncryptionHashing
DirectionReversible with the keyOne-way, no key to reverse it
Output lengthRoughly the size of the inputFixed, for example 256 bits for SHA-256
Needs a keyYesNo (HMAC adds one)
Main purposeConfidentialityIntegrity checks and password storage
ExamplesAES-GCM, ChaCha20-Poly1305, RSASHA-256, SHA-3, bcrypt, Argon2id

A third term is often confused with both. Encoding, such as Base64 or URL encoding, only changes the format of data so it can travel safely. It uses no key and anyone can decode it, so it provides no security at all.

The wider picture of keys, signatures and TLS is covered in cryptography basics.

How hash functions work: SHA-256

A cryptographic hash function has three essential properties. It is pre-image resistant (you cannot find an input from its hash), collision resistant (you cannot find two inputs with the same hash) and it shows the avalanche effect (a one-character change produces a completely different digest).

$ echo -n "hello" | sha256sum
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824  -

$ echo -n "Hello" | sha256sum
185f8db32271fe25f561a6fc938b2e264306ec304eda518007d1764826381969  -

$ sha256sum kali-linux-installer.iso          # verify a download against the published value
$ openssl dgst -sha256 report.pdf             # the same with OpenSSL

SHA-256 and SHA-3 are current standards. MD5 and SHA-1 are broken for collision resistance and must not be used for signatures or certificates, although you may still see them as simple checksums.

Where hashes are used every day

  • Download verification: publishers list the SHA-256 digest of an installer so you can confirm the file was not corrupted or swapped.
  • Version control: Git identifies every commit and file by its hash, so any change to history is visible.
  • Digital signatures: a signature is made over the hash of a document rather than the whole document.
  • Deduplication and caching: storage systems and build tools spot identical content by comparing digests.
  • Forensics: investigators hash evidence when it is collected, so they can later prove it was not altered.

Encrypting data in practice with OpenSSL and PHP

For files, the openssl enc command derives a key from a passphrase with PBKDF2 and encrypts with AES:

openssl enc -aes-256-cbc -pbkdf2 -iter 600000 -salt -in notes.txt -out notes.txt.enc
openssl enc -d -aes-256-cbc -pbkdf2 -iter 600000 -in notes.txt.enc -out notes-decrypted.txt

The enc command does not support authenticated modes, so it detects tampering poorly. In application code, prefer an authenticated API. PHP includes libsodium:

<?php
$key   = sodium_crypto_secretbox_keygen();                  // store securely, never in code
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);  // new nonce for every message
$box   = sodium_crypto_secretbox('Account: 4021', $nonce, $key);

$plain = sodium_crypto_secretbox_open($box, $nonce, $key);  // returns false if tampered with
var_dump($plain);   // string(13) "Account: 4021"

Store the nonce alongside the ciphertext; it is not secret, but it must never repeat with the same key.

Password hashing: bcrypt, Argon2 and salts

Passwords must be hashed, never encrypted, because the application only needs to check a password, not recover it. Plain SHA-256 is the wrong tool: it is designed to be fast, so an attacker with a stolen database can test billions of guesses. Password hashing functions are deliberately slow and, for Argon2, memory-hard.

  • Argon2id: the first choice in the OWASP Password Storage Cheat Sheet; tunable memory, time and parallelism.
  • bcrypt: widely supported and still acceptable; note that it only uses the first 72 bytes of a password.
  • Salt: a random value stored with each hash, so identical passwords produce different hashes and precomputed rainbow tables are useless.
  • Pepper: an optional extra secret kept outside the database, for example in a secrets manager.
<?php
$hash = password_hash($password, PASSWORD_DEFAULT);   // bcrypt with a random salt built in
// or, where PHP is built with Argon2 support:
$hash = password_hash($password, PASSWORD_ARGON2ID);

if (password_verify($attempt, $hash)) {
    if (password_needs_rehash($hash, PASSWORD_DEFAULT)) {
        $hash = password_hash($attempt, PASSWORD_DEFAULT);  // upgrade on next login
        // save the new hash
    }
    // log the user in
}

password_hash() generates and stores the salt inside the result string, so you never handle it yourself. The login flow around this check is covered in authentication and authorisation.

HMAC: hashing with a key

A plain hash proves data has not changed only if the hash itself is trusted. An attacker who changes a message can simply recompute its hash. An HMAC (hash-based message authentication code, RFC 2104) mixes a secret key into the hash, so only someone with the key can produce a valid tag. Webhooks, signed URLs and API request signing use HMAC to prove a message came from a trusted sender.

$ echo -n '{"order":1043}' | openssl dgst -sha256 -hmac "shared-secret"

<?php
$expected = hash_hmac('sha256', $payload, $secret);
if (!hash_equals($expected, $receivedSignature)) {   // constant-time comparison
    http_response_code(401);
    exit('Invalid signature');
}

Choosing the right tool, step by step

  1. Do you need the original data back later? Use authenticated encryption such as AES-GCM or libsodium.
  2. Are you storing a password? Use Argon2id or bcrypt through password_hash().
  3. Are you checking that a file downloaded correctly? Compare SHA-256 digests.
  4. Are you proving a message came from someone who shares a secret with you? Use HMAC-SHA256.
  5. Are you proving who signed something to anyone, without a shared secret? Use a digital signature.

Practical exercise: hash, encrypt and sign on your own machine

  1. Hash two files that differ by one character with sha256sum and compare the digests.
  2. Encrypt a text file with openssl enc, decrypt it, and confirm the hashes of the original and decrypted files match.
  3. Write a PHP script that hashes the same password twice with password_hash(), prints both results and verifies each with password_verify().
  4. Compute an HMAC of a short JSON string, change one character and show that verification fails.

You are done when you can explain why the two password hashes differ but both verify, and why the HMAC detects a change that an attacker could hide from a plain hash. These skills are applied in the Networking Foundation course security modules.

Common mistakes

  • Storing passwords with encryption, or with a fast hash such as MD5 or plain SHA-256.
  • Calling Base64 encoding "encryption" and relying on it to hide sensitive data.
  • Using one fixed salt for every user, which lets identical passwords share a hash.
  • Comparing HMAC signatures with == instead of a constant-time comparison.
  • Hard-coding encryption keys in source code that is committed to a repository.

Frequently asked questions

Can a SHA-256 hash be decrypted?

No. There is no key and no reverse operation. Websites that claim to "decrypt" hashes simply look them up in tables of hashes of common inputs, which is exactly why passwords need slow, salted hashing.

Is bcrypt still safe in 2026?

Yes, with a suitable cost factor. PHP 8.4 raised the default bcrypt cost from 10 to 12. Argon2id is preferred for new systems where it is available.

Should I encrypt or hash email addresses in a database?

Encrypt them if the application must read or send to them. Hash them, ideally with HMAC, only if you need to check whether a value exists without ever reading it back.

Where should encryption keys be kept?

Outside the code and outside the database they protect: in environment configuration with tight file permissions for small projects, or in a secrets manager or hardware security module for larger systems. Plan how keys will be rotated before you encrypt any data.

Want to Learn This Properly?

The Networking & Cybersecurity: Foundation & Practical Implementation (Online) turns guides like this into practised skills, with projects on real websites.

WhatsApp Call Us Now

Free counselling

Send an Enquiry

Tell us which course you are interested in. We reply by email or phone with the next batch and how to enrol.

Protected by reCAPTCHA. Google Privacy and Terms apply.

We reply by email or phone within working hours. No spam.