Learning objectives
After reading this article you will be able to:
- Tell encoding, hashing and encryption apart by what each one guarantees
- Pick the right technique for passwords, data in transit and data at rest
- Spot common mistakes, such as Base64 treated as encryption and MD5 for passwords
Three words show up together in almost every security conversation and get swapped all the time: hashing, encryption and encoding. The mix-up is expensive. It is common to find passwords stored in Base64 as if that protected them, or in MD5 as if any hash would do.
The difference fits in one question: can you get back to the original, and who can? Encoding goes back for anyone. Encryption goes back only for whoever holds the key. A hash goes back for no one.
What is each one?#
Encoding is a change of format, with no secret. It lets binary data pass through places that only accept text: an email attachment, a URL, a JSON field. The most common example is Base64 (RFC 4648), which represents 6 bits per character with a 64-symbol alphabet and pads the end with =. The Base64url variant swaps + and / for - and _ so it fits in URLs, and it is the one JWTs use. The RFC itself warns: encoding hides information from casual view, but it provides no confidentiality at all.
Hashing is a one-way function: it takes any amount of data and returns a fixed-size digest. SHA-256, standardized by NIST in FIPS 180-4, always returns 256 bits (64 hexadecimal characters). The same input always yields the same digest, the smallest change yields a completely different one, and there is no way to compute the input from the digest. It is used to verify integrity (is the downloaded file the one that was published?) and, in its slow form, to store passwords. Add a key and it becomes an HMAC (RFC 2104), which also proves who produced the digest: that is how many services sign webhooks.
Encryption transforms data so that only whoever holds the key can recover it. In symmetric encryption, the same key encrypts and decrypts; AES is the standard, and OWASP recommends a key of at least 128 bits (ideally 256) in an authenticated mode such as GCM, which also detects tampering. In asymmetric encryption (RSA, elliptic curves), the public key encrypts or verifies and the private key decrypts or signs, which solves the problem of agreeing on a key with someone you have never met.
What are the differences, side by side?#
| Encoding | Hashing | Encryption | |
|---|---|---|---|
| Goal | Format compatibility | Integrity, verification | Confidentiality |
| Reversible? | Yes, by anyone | No | Yes, with the key |
| Uses a key? | No | No (HMAC does) | Yes |
| Output size | Grows with input (Base64: about 4/3) | Fixed | Grows with input |
| Examples | Base64, hex, URL encoding | SHA-256, SHA-3, Argon2id | AES-GCM, ChaCha20-Poly1305, RSA |
| Right use | Binary as text, JWT parts | Checksums, passwords (slow hash), HMAC | TLS, sensitive fields, files |
What does each one look like in code?#
The same address going through all three techniques, using only Node.js's built-in crypto module:
import crypto from "node:crypto";
const text = "42 Flower Street";
// 1. Encoding: changes the format, anyone can undo it
const b64 = Buffer.from(text).toString("base64");
console.log(b64); // NDIgRmxvd2VyIFN0cmVldA==
console.log(Buffer.from(b64, "base64").toString()); // 42 Flower Street
// 2. Hashing: fixed-size digest, no way back
console.log(crypto.createHash("sha256").update(text).digest("hex")); // 64 hex characters
// 3. Encryption: back to the original, but only with the key
const key = Buffer.from(process.env.DATA_KEY, "base64"); // 32 bytes, kept out of the code
const iv = crypto.randomBytes(12); // new for every encryption, never reused with the same key
const cipher = crypto.createCipheriv("aes-256-gcm", key, iv);
const encrypted = Buffer.concat([cipher.update(text, "utf8"), cipher.final()]);
const tag = cipher.getAuthTag(); // detects tampering
const decipher = crypto.createDecipheriv("aes-256-gcm", key, iv);
decipher.setAuthTag(tag);
console.log(Buffer.concat([decipher.update(encrypted), decipher.final()]).toString()); // 42 Flower StreetGenerate the key once with node -e "console.log(require('crypto').randomBytes(32).toString('base64'))" and store the result as DATA_KEY. Three AES-GCM details matter. The 12-byte IV must be new for every encryption: NIST SP 800-38D, which defines GCM, requires unique IVs per key, because a repeated one breaks its security. The IV and the tag are not secret and are stored next to the ciphertext. And if anyone changes a single byte, the decipher's final() throws an error instead of returning garbage.
Which one should you use for passwords?#
Hashing, and a slow hash. You never need to read a password back, only to check that the typed one matches, so reversibility is a risk, not a feature: whoever took the database and the key would read every password at once. OWASP recommends adaptive hashing and only accepts encrypting passwords in rare cases where the original text is required.
And not just any hash. SHA-256, SHA-1 and MD5 were built to be fast, and OWASP says fast hashes like SHA-256 are not suitable for password storage for exactly that reason: with a leaked database, the attacker tests guesses at high speed. Password hashing algorithms are slow on purpose, use memory, and each one generates a random salt per password, which makes two identical passwords produce different hashes and defeats precomputed tables. OWASP's order: Argon2id (at least 19 MiB of memory, 2 iterations and parallelism 1), scrypt when it is not available, bcrypt (work factor 10 or more) only for legacy systems, and PBKDF2 with 600,000 iterations when FIPS-140 compliance is required.
// npm install argon2
import argon2 from "argon2";
const hash = await argon2.hash("example passphrase"); // Argon2id, random salt
console.log(hash); // $argon2id$v=19$m=65536,t=3,p=4$<salt>$<hash>
console.log(await argon2.verify(hash, "example passphrase")); // true
console.log(await argon2.verify(hash, "another password")); // false
console.log(hash === (await argon2.hash("example passphrase"))); // false: the salt changesThe salt and the parameters live inside the string itself, so you store a single field and verify knows how to redo the computation. The comparison between Argon2id, scrypt and bcrypt, with each one's memory cost, is in the best way to store passwords.
What about data in transit and at rest?#
In transit, use TLS. TLS 1.3 (RFC 8446) combines all three techniques: asymmetric cryptography to agree on a key and authenticate the server through its certificate, authenticated symmetric encryption for the data, and hash functions to derive keys and check the handshake. You implement none of it: you turn on HTTPS for the site and TLS for the database connection. See what SSL/TLS is and HTTP vs HTTPS.
At rest, TLS no longer helps: the data reaches the server and sits on disk and in the database exactly as you wrote it. For sensitive fields (ID numbers, addresses, third-party tokens), encrypt in the application before writing, with AES-GCM as in the example. The weak point becomes the key. OWASP asks for it to live apart from the data, never in the code or in version control, and prefers a secrets management service (a vault or KMS) over environment variables, which can be exposed by accident. At a minimum, the key stays out of the code and out of the database; the options are in where to store secrets.
Disk encryption protects against someone walking away with the physical disk, not against someone breaking into the application: to the running process, the data looks decrypted. That is why it complements field encryption but does not replace it.
What are the most common mistakes?#
- Base64 as "encryption". A password in Base64 in a database, a config file or a cookie is plain text to anyone who looks. The same goes for the
Authorization: Basicheader (RFC 7617), which is justuser:passwordin Base64 and therefore depends on TLS, and for a JWT payload, which anyone can decode (see JWT vs cookie sessions). - MD5 or SHA-1 for passwords or signatures. Besides being fast, both have known collisions. RFC 6151 says MD5 is no longer acceptable where collision resistance is required, such as digital signatures, and NIST has announced SHA-1's retirement, with SHA-2 and SHA-3 as replacements. They still catch accidental corruption in a file; against an attacker, they don't hold.
- No salt, or a fixed salt. Two people with the same password get the same hash, and ready-made tables crack common passwords in one go. Password hashing libraries generate the salt for you.
- Encrypting passwords. It is reversible by definition. If a system can show you your forgotten password, it stores it in a recoverable way.
- Reusing an IV or rolling your own algorithm. In GCM, a repeated IV with the same key breaks both confidentiality and authenticity. Use the standard library's ready-made primitives, always in an authenticated mode.
- Comparing signatures with
===. For tokens and HMACs, use a constant-time comparison (crypto.timingSafeEqual), so response time does not reveal how many characters matched.
How to do this on Square Cloud#
On Square Cloud, traffic in transit is already encrypted at two points. Every published web application gets HTTPS with automatic TLS: on the *.squareweb.app subdomain on every plan and, from the Standard plan, on a custom domain with a certificate that renews on its own, plus a redirect from HTTP to HTTPS. And connections to hosted databases (MongoDB, PostgreSQL, MySQL and Redis, from the Standard plan) require TLS: the client trusts the CA you download from the dashboard, PostgreSQL and MongoDB clients also present the .pem certificate, and Redis uses rediss://.
What stays in your code is the rest of the table: hashing passwords before the INSERT, encrypting sensitive fields before writing and guarding the key. Put DATA_KEY and the database connection URL in the application's environment variables, never in the code or in the database itself; one application cannot read another one's variables, even in the same account. A slow hash also uses RAM on every concurrent login (with node-argon2's defaults, 64 MiB per hash in progress), and you adjust each application's RAM in its settings.
See database hosting.
Infrastructure
L3/L4/L7 DDoS mitigation and a WAF on every plan
FAQs
Is Base64 encryption?
No. Base64 is encoding: it maps bytes to text with a 64-character alphabet, with no key, and anyone can decode it. RFC 4648 warns that it provides no confidentiality.
Can you decrypt a hash?
No, a hash has no key and no way back. What an attacker does is test guesses: hash each one and compare. That is why passwords use a slow hash, so every guess is expensive.
Why not encrypt passwords instead of hashing them?
Because encryption is reversible: whoever takes the database and the key reads every password. OWASP recommends adaptive hashing, such as Argon2id, and only accepts encrypting passwords in the rare cases where the original text is required.
Is SHA-256 good enough for passwords?
No. SHA-256 is a sound hash, but it was built to be fast, and OWASP says fast hashes like it are not suitable for password storage, because they let attackers test guesses at high speed. Use Argon2id, scrypt or bcrypt.
Does HTTPS encrypt the data in my database?
No. TLS protects data only while it travels over the network. On disk and in the database, it stays as you wrote it, unless you encrypt it at rest.
More in Security
See all 24 articles- Authentication vs authorization: the difference in practiceAuthentication confirms who you are; authorization decides what you can do. Learn 401 vs 403, roles, scopes and the bug of checking only the login, with code.
- JWT vs cookie sessions: which to use for loginWith sessions, state lives on the server and the cookie holds an ID; with JWT, the data travels in the token. Compare logout, CSRF, XSS and multiple instances.
- What is SQL injection and how to prevent itSQL injection happens when user input becomes part of a SQL query. See how the attack works and how to prevent it with parameterized queries in Node.js and Python.
- What is a brute force attack and how to defend against itA brute force attack tests passwords in bulk until one works. Learn the types (spraying, credential stuffing), how they work and the defenses, with code that runs.