Junior — Middle
Do you use cryptographic methods for hashing passwords in Java Security?
sobes.tech AI
Answer from AI
In Java Security, it is recommended to use cryptographically secure algorithms with salt and iterations for password hashing, such as PBKDF2, bcrypt, or scrypt. Simply using MessageDigest (e.g., SHA-256) without salt and iterations does not provide sufficient protection.
Example of using PBKDF2 with Java standard tools:
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.security.SecureRandom;
import java.util.Base64;
public class PasswordHasher {
private static final int ITERATIONS = 65536;
private static final int KEY_LENGTH = 256;
public static String hashPassword(char[] password, byte[] salt) throws Exception {
PBEKeySpec spec = new PBEKeySpec(password, salt, ITERATIONS, KEY_LENGTH);
SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
byte[] hash = skf.generateSecret(spec).getEncoded();
return Base64.getEncoder().encodeToString(hash);
}
public static byte[] getSalt() {
SecureRandom sr = new SecureRandom();
byte[] salt = new byte[16];
sr.nextBytes(salt);
return salt;
}
}
Thus, yes — cryptographic methods are used, but it is important to apply them correctly, with salt and a sufficient number of iterations.