Sobes.tech
Middle+

Как правильно хранить и обрабатывать пароли, используя Java?

sobes.tech AI

Answer from AI

Passwords should be stored as hashes, not in plain text. When verifying a password, hash the entered password and compare it with the stored hash.

Recommendations for storing and handling passwords:

  1. Hashing: Use strong cryptographic hash functions such as BCrypt, SCrypt, or Argon2. They are specifically designed for hashing passwords and are resistant to brute-force attacks.
  2. Salt: Use a unique, random salt for each password. The salt should be stored along with the hash. This prevents dictionary attacks and rainbow table attacks.
  3. Number of iterations: For PBKDF2 (Password-Based Key Derivation Function 2), use a sufficiently large number of iterations to slow down the hashing process, making brute-force attacks more difficult. For BCrypt, SCrypt, and Argon2, adjust parameters that control computational complexity.
  4. Do not store passwords in plain text: Never store passwords in the database or files in their original ( unhashed) form.
  5. During login: When authenticating a user, hash the entered password using the stored salt and the same hash function as during registration, then compare the resulting hash with the stored hash.
  6. Changing passwords: When changing a password, generate a new salt and hash the new password with this salt, then store the new hash and salt.

Example of using Spring Security library with BCrypt:

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

public class PasswordHashingExample {

    public static void main(String[] args) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

        String rawPassword = "mysecretpassword";

        // Hashing the password
        String hashedPassword = encoder.encode(rawPassword);
        System.out.println("Hashed password: " + hashedPassword);

        // Verifying the password
        String inputPassword = "mysecretpassword";
        boolean isPasswordMatch = encoder.matches(inputPassword, hashedPassword);
        System.out.println("Password match: " + isPasswordMatch);

        String wrongPassword = "wrongpassword";
        boolean isWrongPasswordMatch = encoder.matches(wrongPassword, hashedPassword);
        System.out.println("Wrong password match: " + isWrongPasswordMatch);
    }
}

Avoid outdated or insecure hash functions such as MD5 or SHA-1 for hashing passwords.