Te damos la bienvenida a nuestra página, en este sitio encontrarás la respuesta de lo que buscabas.
Ejemplo: ¿cuál es la mejor manera de almacenar contraseñas en java?
importjava.security.SecureRandom;importjava.security.spec.KeySpec;importjava.util.Base64;importjava.util.HashMap;importjava.util.Map;importjava.util.Scanner;importjavax.crypto.SecretKeyFactory;importjavax.crypto.spec.PBEKeySpec;publicclassSecurePasswordStorageDemo// Simulates database of users!privateMap<String,UserInfo> userDatabase =newHashMap<String,UserInfo>();publicstaticvoidmain(String[] args)throwsExceptionSecurePasswordStorageDemo passManager =newSecurePasswordStorageDemo();String userName ="admin";String password ="password";
passManager.signUp(userName, password);Scanner scanner =newScanner(System.in);System.out.println("Please enter username:");String inputUser = scanner.nextLine();System.out.println("Please enter password:");String inputPass = scanner.nextLine();boolean status = passManager.authenticateUser(inputUser, inputPass);if(status)System.out.println("Logged in!");elseSystem.out.println("Sorry, wrong username/password");
scanner.close();privatebooleanauthenticateUser(String inputUser,String inputPass)throwsExceptionUserInfo user = userDatabase.get(inputUser);if(user ==null)returnfalse;elseString salt = user.userSalt;String calculatedHash =getEncryptedPassword(inputPass, salt);if(calculatedHash.equals(user.userEncryptedPassword))returntrue;elsereturnfalse;privatevoidsignUp(String userName,String password)throwsExceptionString salt =getNewSalt();String encryptedPassword =getEncryptedPassword(password, salt);UserInfo user =newUserInfo();
user.userEncryptedPassword = encryptedPassword;
user.userName = userName;
user.userSalt = salt;saveUser(user);// Get a encrypted password using PBKDF2 hash algorithmpublicStringgetEncryptedPassword(String password,String salt)throwsExceptionString algorithm ="PBKDF2WithHmacSHA1";int derivedKeyLength =160;// for SHA1int iterations =20000;// NIST specifies 10000byte[] saltBytes =Base64.getDecoder().decode(salt);KeySpec spec =newPBEKeySpec(password.toCharArray(), saltBytes, iterations, derivedKeyLength);SecretKeyFactory f =SecretKeyFactory.getInstance(algorithm);byte[] encBytes = f.generateSecret(spec).getEncoded();returnBase64.getEncoder().encodeToString(encBytes);// Returns base64 encoded saltpublicStringgetNewSalt()throwsException// Don't use Random!SecureRandom random =SecureRandom.getInstance("SHA1PRNG");// NIST recommends minimum 4 bytes. We use 8.byte[] salt =newbyte[8];
random.nextBytes(salt);returnBase64.getEncoder().encodeToString(salt);privatevoidsaveUser(UserInfo user)
userDatabase.put(user.userName, user);// Each user has a unique salt// This salt must be recomputed during password change!classUserInfoString userEncryptedPassword;String userSalt;String userName;
Nos puedes añadir valor a nuestra información añadiendo tu veteranía en las interpretaciones.
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)