Junior — Middle
How can you verify the correctness of a password entered?
sobes.tech AI
Answer from AI
Checking the correctness of a password entered in Java usually involves several steps:
- Obtaining the password from the user (for example, through a form).
- Hashing the entered password using the same algorithm and salt as when it was stored.
- Comparing the obtained hash with the hash stored in the database.
Example using MessageDigest for password hashing:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
public class PasswordChecker {
public static byte[] hashPassword(String password) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
return md.digest(password.getBytes());
}
public static boolean checkPassword(String inputPassword, byte[] storedHash) throws NoSuchAlgorithmException {
byte[] inputHash = hashPassword(inputPassword);
return Arrays.equals(inputHash, storedHash);
}
public static void main(String[] args) throws NoSuchAlgorithmException {
String correctPassword = "secret123";
byte[] storedHash = hashPassword(correctPassword);
String userInput = "secret123";
if (checkPassword(userInput, storedHash)) {
System.out.println("Password is correct");
} else {
System.out.println("Incorrect password");
}
}
}
In real applications, it is recommended to use specialized libraries for password hashing, such as BCrypt, which take into account salts and make hashing more secure.