When storing passwords in a database, hashing is the preferred method over encryption due to its security advantages. Let’s dive into the differences and see examples of both approaches.
1. Hashing the Password
Hashing is a one-way function that converts input (password) into a fixed-length string. It is irreversible, meaning you cannot derive the original password from the hash.
What is BCrypt?
BCrypt stands for Blowfish Crypt. It is a password-hashing function designed to include a salt to protect against rainbow table attacks and brute-force attempts.
Why Use Hashing?
- Secure: Even if the database is compromised, hashed passwords are hard to reverse.
- Irreversible: Cannot retrieve original data from the hash.
Example of Password Hashing (Java using BCrypt):
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
public class PasswordHasher {
public static void main(String[] args) {
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
String rawPassword = "mySecurePassword";
String hashedPassword = encoder.encode(rawPassword);
System.out.println("Hashed Password: " + hashedPassword);
// Verify the password
boolean isMatch = encoder.matches(rawPassword, hashedPassword);
System.out.println("Password matches: " + isMatch);
}
}
Output Example:
Hashed Password: $2a$10$D4G5f18o7a97yF/Q1S3bKuU8Q2hX0W6P5a4CkPZ9uRhXl2eLq3E2O Password matches: true
Storing Hashed Password in Database
When saving hashed passwords to a database, store them in a VARCHAR(255) or TEXT column.
Example SQL schema:
CREATE TABLE users (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(100) NOT NULL UNIQUE,
password_hash VARCHAR(255) NOT NULL
);
INSERT INTO users (username, password_hash) VALUES ('user1', '$2a$10$D4G5f...');
Best Practices for Hashing:
- Use a strong hashing algorithm like BCrypt, PBKDF2, or Argon2.
- Never store plain-text passwords.
- Always use a salt (automatically handled by BCrypt) to prevent rainbow table attacks.
2. Encrypting the Password
Encryption is a reversible process where data is encoded and can be decrypted using a secret key.
What is AES?
AES stands for Advanced Encryption Standard. It is a symmetric encryption algorithm widely used to securely encrypt data using a shared key.
Why Use Encryption?
- Useful when you need to retrieve the original password (e.g., for legacy systems or password recovery).
- Less secure for password storage because decrypting is always possible.
Example of Password Encryption (Java using AES):
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.util.Base64;
public class PasswordEncryptor {
public static void main(String[] args) throws Exception {
String rawPassword = "mySecurePassword";
// Generate AES Key
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256);
SecretKey secretKey = keyGen.generateKey();
// Encrypt password
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encrypted = cipher.doFinal(rawPassword.getBytes());
String encryptedPassword = Base64.getEncoder().encodeToString(encrypted);
System.out.println("Encrypted Password: " + encryptedPassword);
// Decrypt password
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(encryptedPassword));
System.out.println("Decrypted Password: " + new String(decrypted));
}
}
Output Example:
Encrypted Password: bG2KvA9hWmUQ2T8p5uJ... (truncated) Decrypted Password: mySecurePassword
Storing Encrypted Password in Database
For encrypted passwords, also use a VARCHAR(255) or TEXT column.
Example SQL schema:
CREATE TABLE encrypted_users (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(100) NOT NULL UNIQUE,
encrypted_password TEXT NOT NULL,
encryption_key TEXT NOT NULL
);
INSERT INTO encrypted_users (username, encrypted_password, encryption_key)
VALUES ('user1', 'bG2KvA9h...', 'your-secret-key');
Best Practices for Encryption:
- Use AES-256 for strong encryption.
- Keep the encryption key secure.
- Avoid encrypting passwords unless absolutely necessary.
3. When to Use Hashing vs Encryption
| Feature | Hashing | Encryption |
|---|---|---|
| Purpose | Secure password storage | Data retrieval or recovery |
| Reversibility | Irreversible (One-way) | Reversible (Two-way) |
| Security | Strong (with salt & iterations) | Depends on key protection |
| Use Case | User password storage | Securing data for later use |
Recommendation: Always hash passwords for storage. Use encryption only when you need to retrieve the original password (which is rare).