Why can't passwords be stored in plain text?
First, we need to be clear:Passwords can never be stored in a database in plain text。
The reasons are as follows:
- Data breach risk: If the database is attacked, the passwords of all users will be directly exposed.
- User privacy protection: Many users may use the same password on multiple platforms, and plaintext storage will increase the risk of other accounts being compromised.
- Legal and compliance requirements: Many security standards (such as GDPR, OWASP, etc.) explicitly prohibit the storage of passwords in plain text.
Therefore, passwords must be encrypted or hashed before storage. In Spring Boot, the following are several common password secure storage methods.
1. Hash with BCrypt
What is BCrypt?
BCryptIt is a hash function based on the Blowfish encryption algorithm, designed for password storage, with the following features:
- built-inWith saltMechanism to avoid rainbow table attacks.
- Support settingsCalculation complexity, can enhance hash strength.
- The hash result is fixed to 60 characters for easy storage.
How to use
-
Introduce dependencies: If Spring Security is not used, it needs to be introduced separately
spring-security-crypto
<dependency> <groupId></groupId> <artifactId>spring-security-crypto</artifactId> </dependency>
-
Password encryption and verification:use
BCryptPasswordEncoder
Encrypt and verify the password:
import ; public class PasswordUtils { private static final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); // Encryption password public static String encode(String rawPassword) { return (rawPassword); } // Verify password public static boolean matches(String rawPassword, String encodedPassword) { return (rawPassword, encodedPassword); } }
- Example of usage
public static void main(String[] args) { String rawPassword = "mypassword"; String encodedPassword = (rawPassword); ("Encrypted password:" + encodedPassword); boolean isMatch = (rawPassword, encodedPassword); ("Password matching result:" + isMatch); }
Pros and cons
-
advantage
- High safety and built-in salting mechanism.
- Easy to use, Spring Security native support.
-
shortcoming
- Compared with other hashing algorithms, the performance is slightly lower.
2. Hash with PBKDF2
What is PBKDF2?
PBKDF2(Password-Based Key Derivation Function 2) is a password-based key derivation function that supports multiple iterative calculations to further enhance security.
How to use
-
Introduce dependencies: If Spring Security is not used, it needs to be introduced separately
spring-security-crypto
<dependency> <groupId></groupId> <artifactId>spring-security-crypto</artifactId> </dependency>
- Implement password encryption and verification:
import .Pbkdf2PasswordEncoder; public class PasswordUtils { private static final Pbkdf2PasswordEncoder encoder = new Pbkdf2PasswordEncoder(); // Encryption password public static String encode(String rawPassword) { return (rawPassword); } // Verify password public static boolean matches(String rawPassword, String encodedPassword) { return (rawPassword, encodedPassword); } }
- Example of usage:
public static void main(String[] args) { String rawPassword = "mypassword"; String encodedPassword = (rawPassword); ("Encrypted password:" + encodedPassword); boolean isMatch = (rawPassword, encodedPassword); ("Password matching result:" + isMatch); }
Pros and cons
-
advantage
- High security and adjust the number of iterations.
- Widely supported, good compatibility.
-
shortcoming
- Compared with BCrypt, the use is slightly more complicated.
3. Hash with Argon2
What is Argon2?
Argon2It is a password hashing algorithm that won the Password Hashing Competition championship in 2015. It is currently considered one of the most secure password hashing algorithms.
How to use
-
Introduce dependencies: If Spring Security is not used, it is necessary to introduce it
spring-security-crypto
:
<dependency> <groupId></groupId> <artifactId>spring-security-crypto</artifactId> </dependency>
- Implement password encryption and verification
import .argon2.Argon2PasswordEncoder; public class PasswordUtils { private static final Argon2PasswordEncoder encoder = new Argon2PasswordEncoder(); // Encryption password public static String encode(String rawPassword) { return (rawPassword); } // Verify password public static boolean matches(String rawPassword, String encodedPassword) { return (rawPassword, encodedPassword); } }
- Example of usage
public static void main(String[] args) { String rawPassword = "mypassword"; String encodedPassword = (rawPassword); ("Encrypted password:" + encodedPassword); boolean isMatch = (rawPassword, encodedPassword); ("Password matching result:" + isMatch); }
Pros and cons
-
advantage
- Extremely secure, designed for modern hardware.
- Defend GPU-accelerated brute force cracking.
-
shortcoming
- The algorithm is relatively new and some old systems may not support it.
4. SCrypt
What is SCrypt?
SCryptIt is a password-based key derivation function, especially suitable for attacks that limit hardware acceleration (such as GPU-accelerated brute force cracking). It significantly increases cracking costs by increasing memory usage.
Features of SCrypt
- High security: Prevent large-scale hardware-accelerated attacks by increasing memory footprint.
- Adjustable parameters: The calculation intensity and memory usage can be adjusted to meet different performance requirements.
How to use
Spring Security provides support for SCrypt and can be used directlySCryptPasswordEncoder
。
- Implement code
import ; public class PasswordUtils { private static final SCryptPasswordEncoder encoder = new SCryptPasswordEncoder(); // Encryption password public static String encode(String rawPassword) { return (rawPassword); } // Verify password public static boolean matches(String rawPassword, String encodedPassword) { return (rawPassword, encodedPassword); } }
- Example of usage
public static void main(String[] args) { String rawPassword = "mypassword"; String encodedPassword = (rawPassword); ("Encrypted password:" + encodedPassword); boolean isMatch = (rawPassword, encodedPassword); ("Password matching result:" + isMatch); }
Pros and cons
-
advantage:
- Strong anti-GPU attack capability.
- Adjustable parameters and high flexibility.
-
shortcoming
- Low performance and suitable for scenarios with high safety requirements.
5. SHA-256 + Salt
What is SHA-256?
SHA-256It is a widely used hashing algorithm and belongs to the SHA-2 family. It generates a fixed-length 256-bit hash, which is fast in calculations and simple in implementation.SHA-256 alone is not safe, because it cannot resist rainbow table attacks. Therefore, it is usually necessary to matchSalt (random salt value)use.
Implementation principle
- With salt: Generate a random salt value for each password to increase the randomness of the hash result.
- Iteration: Multiple cycles to increase cracking difficulty.
How to use
Need to manually implement salting and iterative logic, you can use Java'sMessageDigest
kind.
- Implement code
import ; import ; import .Base64; public class PasswordUtils { // Generate random salt values public static String generateSalt() { byte[] salt = new byte[16]; new SecureRandom().nextBytes(salt); return ().encodeToString(salt); } // Encryption with SHA-256 public static String hashPassword(String password, String salt) { try { MessageDigest digest = ("SHA-256"); String saltedPassword = salt + password; byte[] hash = (()); for (int i = 0; i < 1000; i++) { // Multiple iterations hash = (hash); } return ().encodeToString(hash); } catch (Exception e) { throw new RuntimeException("Encryption failed", e); } } // Verify password public static boolean matches(String rawPassword, String salt, String hashedPassword) { return hashPassword(rawPassword, salt).equals(hashedPassword); } }
- Example of usage
public static void main(String[] args) { String rawPassword = "mypassword"; String salt = (); String hashedPassword = (rawPassword, salt); ("Random salt value:" + salt); ("Encrypted password:" + hashedPassword); boolean isMatch = (rawPassword, salt, hashedPassword); ("Password matching result:" + isMatch); }
Pros and cons
-
advantage
- Simple to implement and fast speed.
- Can be used in scenarios that are compatible with older systems.
-
shortcoming
- The safety is relatively low and the salt value needs to be handled with caution.
Summarize
Encryption method | Security | performance | Applicable scenarios |
---|---|---|---|
BCrypt | high | medium | Common scenarios, good compatibility |
PBKDF2 | high | medium | High-strength password storage |
Argon2 | Extremely high | Lower | Scenarios with extremely high safety requirements |
SCrypt | Extremely high | Lower | Anti-hardware acceleration attack scenarios |
SHA-256 + Salt | medium | high | Security-insensitive projects, such as internal projects |
Recommended choice
-
General Scenario: Recommended
BCrypt
, it strikes a good balance between performance and security. -
High security requirements: It is recommended to use
Argon2
orSCrypt
。 -
Security-insensitive systems: Can consider
SHA-256 + Salt
。
The above is the detailed content of the five ways to implement password secure storage in SpringBoot. For more information about SpringBoot password storage, please follow my other related articles!