what is the best way to store passwords in java

Solutions on MaxInterview for what is the best way to store passwords in java by the best coders in the world

showing results for - "what is the best way to store passwords in java"
Zahra
29 Jul 2017
1import java.security.SecureRandom;
2import java.security.spec.KeySpec;
3import java.util.Base64;
4import java.util.HashMap;
5import java.util.Map;
6import java.util.Scanner;
7 
8import javax.crypto.SecretKeyFactory;
9import javax.crypto.spec.PBEKeySpec;
10 
11public class SecurePasswordStorageDemo {
12 
13    // Simulates database of users!
14    private Map<String, UserInfo> userDatabase = new HashMap<String,UserInfo>();
15 
16    public static void main(String[] args) throws Exception {
17        SecurePasswordStorageDemo passManager = new SecurePasswordStorageDemo();
18        String userName = "admin";
19        String password = "password";
20        passManager.signUp(userName, password);
21 
22        Scanner scanner = new Scanner(System.in);
23        System.out.println("Please enter username:");
24        String inputUser = scanner.nextLine();
25 
26        System.out.println("Please enter password:");
27        String inputPass = scanner.nextLine();
28 
29        boolean status = passManager.authenticateUser(inputUser, inputPass);
30        if (status) {
31            System.out.println("Logged in!");
32        } else {
33            System.out.println("Sorry, wrong username/password");
34        }
35        scanner.close();
36    }
37 
38    private boolean authenticateUser(String inputUser, String inputPass) throws Exception {
39        UserInfo user = userDatabase.get(inputUser);
40        if (user == null) {
41            return false;
42        } else {
43            String salt = user.userSalt;
44            String calculatedHash = getEncryptedPassword(inputPass, salt);
45            if (calculatedHash.equals(user.userEncryptedPassword)) {
46                return true;
47            } else {
48                return false;
49            }
50        }
51    }
52 
53    private void signUp(String userName, String password) throws Exception {
54        String salt = getNewSalt();
55        String encryptedPassword = getEncryptedPassword(password, salt);
56        UserInfo user = new UserInfo();
57        user.userEncryptedPassword = encryptedPassword;
58        user.userName = userName;
59        user.userSalt = salt;
60        saveUser(user);
61    }
62 
63    // Get a encrypted password using PBKDF2 hash algorithm
64    public String getEncryptedPassword(String password, String salt) throws Exception {
65        String algorithm = "PBKDF2WithHmacSHA1";
66        int derivedKeyLength = 160; // for SHA1
67        int iterations = 20000; // NIST specifies 10000
68 
69        byte[] saltBytes = Base64.getDecoder().decode(salt);
70        KeySpec spec = new PBEKeySpec(password.toCharArray(), saltBytes, iterations, derivedKeyLength);
71        SecretKeyFactory f = SecretKeyFactory.getInstance(algorithm);
72 
73        byte[] encBytes = f.generateSecret(spec).getEncoded();
74        return Base64.getEncoder().encodeToString(encBytes);
75    }
76 
77    // Returns base64 encoded salt
78    public String getNewSalt() throws Exception {
79        // Don't use Random!
80        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
81        // NIST recommends minimum 4 bytes. We use 8.
82        byte[] salt = new byte[8];
83        random.nextBytes(salt);
84        return Base64.getEncoder().encodeToString(salt);
85    }
86 
87    private void saveUser(UserInfo user) {
88        userDatabase.put(user.userName, user);
89    }
90 
91}
92 
93// Each user has a unique salt
94// This salt must be recomputed during password change!
95class UserInfo {
96    String userEncryptedPassword;
97    String userSalt;
98    String userName;
99}
100