DEV Community

Tony Sterlin Cantave
Tony Sterlin Cantave

Posted on Originally published at tonycantave.com

Hashing, Encryption and Encoding: My Security+ Notes With Python Examples

When I studied for CompTIA Security+, one idea took me longer than it should have to really own: the difference between hashing, encryption and encoding. All three turn readable data into something that looks scrambled, so it is easy to treat them as the same thing. They are not, and mixing them up leads to real mistakes in code, like "protecting" a password with base64 or trying to "decrypt" a hash. These are the notes I wish I had on day one, with small Python examples you can run yourself.

The one question that separates them

Ask yourself: who is supposed to be able to get the original data back?

  • Encoding: anyone. It changes the format so data can travel or be stored safely. There is no secret involved.
  • Encryption: only someone with the key. It protects confidentiality.
  • Hashing: nobody. It produces a fixed size fingerprint and is designed to work in one direction only. It protects integrity.

Once I framed it that way, most exam questions and most code reviews got easier.

Encoding: format, not security

Base64 is the example everyone runs into. It turns raw bytes into plain text characters so they survive email, JSON or URLs.

import base64

raw = "report ready".encode("utf8")
encoded = base64.b64encode(raw)
print(encoded)                    # b'cmVwb3J0IHJlYWR5'
print(base64.b64decode(encoded))  # b'report ready'
Enter fullscreen mode Exit fullscreen mode

No key, no secret. If you ever see a password stored as base64 in a config file, treat it as plain text, because anyone can decode it in one line. URL encoding and character encodings like UTF8 belong to the same family. They exist so systems read the data correctly, not to hide it.

Hashing: a fingerprint you cannot reverse

A hash function takes input of any size and returns a fixed size digest. Change one character and the digest changes completely. You cannot run it backwards to recover the input.

import hashlib

print(hashlib.sha256(b"invoice total 120").hexdigest())
print(hashlib.sha256(b"invoice total 121").hexdigest())
Enter fullscreen mode Exit fullscreen mode

The two outputs share nothing recognizable, even though the inputs differ by a single digit. That property is what makes hashes useful for integrity checks.

The way I use this most often is verifying a download. Many projects publish a SHA256 checksum next to the file. This small function hashes a large file in chunks so it never loads the whole thing into memory:

import hashlib
from pathlib import Path

def file_sha256(path, chunk_size=65536):
    digest = hashlib.sha256()
    with Path(path).open("rb") as f:
        for chunk in iter(lambda: f.read(chunk_size), b""):
            digest.update(chunk)
    return digest.hexdigest()

expected = "paste the published checksum here"
actual = file_sha256("installer.iso")
print("match" if actual == expected.strip().lower() else "MISMATCH, do not use this file")
Enter fullscreen mode Exit fullscreen mode

For the exam, remember the older algorithms: MD5 and SHA1 have known collision weaknesses, so they should not be trusted for security decisions. SHA256 and newer members of the SHA2 and SHA3 families are the safe defaults.

Passwords need a slow hash with a salt

Plain SHA256 is fast, and fast is bad for passwords, because an attacker can try billions of guesses. Passwords should be stored with a salted, deliberately slow function. Python's standard library includes PBKDF2:

import hashlib, hmac, os

def hash_password(password, salt=None, rounds=600_000):
    salt = salt or os.urandom(16)
    key = hashlib.pbkdf2_hmac("sha256", password.encode(), salt, rounds)
    return salt, key

def check_password(password, salt, stored_key, rounds=600_000):
    _, key = hash_password(password, salt, rounds)
    return hmac.compare_digest(key, stored_key)
Enter fullscreen mode Exit fullscreen mode

The salt is random for each user, so two people with the same password end up with different stored values, which defeats precomputed rainbow tables. hmac.compare_digest compares in constant time, so the check does not leak timing hints. In a production application I would use a maintained library such as bcrypt or Argon2, but this shows all the moving parts.

Encryption: confidentiality with a key

Encryption is reversible, but only with the right key. Security+ splits it into two kinds:

  • Symmetric: one shared key encrypts and decrypts. It is fast and good for bulk data. AES is the standard example.
  • Asymmetric: a public key and a private key. It is slower, but it solves the problem of sharing keys and makes digital signatures possible. RSA and elliptic curve cryptography are the common examples.

Real systems combine them. TLS uses asymmetric cryptography to agree on a session key, then switches to symmetric encryption for the actual traffic.

Here is symmetric encryption in Python using the widely used cryptography package, installed with pip:

from cryptography.fernet import Fernet

key = Fernet.generate_key()   # keep this secret
box = Fernet(key)

token = box.encrypt(b"schedule for Monday")
print(box.decrypt(token))     # b'schedule for Monday'
Enter fullscreen mode Exit fullscreen mode

Lose the key and the data is gone. Leak the key and the encryption no longer protects anything. That is why key management shows up so often on the exam.

Where digital signatures fit

A digital signature uses both ideas. The sender hashes the message, then signs that hash with their private key. Anyone with the matching public key can verify two things: the message was not changed (integrity), and it came from whoever holds the private key (authenticity and non repudiation). If a question asks how to prove who sent something, think signatures, not plain encryption.

My quick review list

  • Make data safe to transmit or store as text: encoding such as base64. Reversible by anyone.
  • Keep data secret: encryption such as AES or RSA. Reversible only with the key.
  • Detect changes: hashing such as SHA256. Not reversible.
  • Store passwords: salted slow hashing such as PBKDF2, bcrypt or Argon2. Not reversible.
  • Prove who sent it: digital signature. Verified with the public key.

The habit that stuck with me after the exam is simple. Before I write code that touches sensitive data, I name which of the three I actually need. Most of the bad patterns I have seen came from skipping that one question.

Originally published at tonycantave.com by Tony Sterlin Cantave, a Connecticut software developer.

Top comments (0)