Key Concepts: Encryption Vocabulary
Hashing vs Encryption
These are often confused. Know the difference.Passwords must be HASHED, not encrypted. If you encrypt passwords, the encryption key becomes the single point of failure. If hashed with bcrypt, even the server admin cannot read the original password.
Password Hashing with bcrypt
bcrypt is the industry-standard library for hashing passwords in Node.js.How bcrypt Works
- Generates a random salt
- Combines salt + password
- Runs the combination through a slow hashing algorithm N times (controlled by
saltRounds) - Returns a single string containing the algorithm, salt, and hash
Hashing a Password
Comparing a Password
Complete Login Example
Salt Rounds: What They Mean
Salt rounds control how many times bcrypt iterates. Each increment roughly doubles the time.Symmetric Encryption: AES-256 with crypto
Node.js has a built-incrypto module. Use it for encrypting sensitive data at rest (credit card numbers, PII, tokens to store in DB).
Asymmetric Encryption: Public/Private Keys
Used in HTTPS (TLS), JWT signing with RS256, and SSL certificates. The public key encrypts or verifies; the private key decrypts or signs.In JWT with RS256 algorithm, the server signs tokens with the PRIVATE key and clients verify with the PUBLIC key. This allows clients to validate tokens without ever knowing the private key.
Generating Secure Random Tokens
Usecrypto.randomBytes() for password reset tokens, email verification tokens, and API keys.
HTTPS/TLS: Encryption in Transit
HTTPS encrypts all data between client and server using TLS. Without HTTPS, passwords sent in login requests can be intercepted on public networks. For development (self-signed cert):Key Terms
Common Mistakes
Using MD5 or SHA-1 for passwords
Using MD5 or SHA-1 for passwords
MD5 and SHA-1 are fast cryptographic hashes, not password hashing algorithms. Fast = bad for passwords. Always use bcrypt, Argon2, or scrypt for password storage.
Storing the encryption key in the same database as the encrypted data
Storing the encryption key in the same database as the encrypted data
If an attacker dumps your database and also finds the encryption key there, encryption provides no protection. Store keys in environment variables or a key management service.
Using the same IV for every encryption
Using the same IV for every encryption
AES requires a unique Initialization Vector for every encryption operation. Reusing IVs leaks information about the plaintext. Always generate a new IV with
crypto.randomBytes(16).Not using HTTPS in production
Not using HTTPS in production
Without HTTPS, credentials sent in login forms are plaintext on the network. Always configure SSL/TLS before going live.