Username is saved hashed and password hashed and salted
[RRRRHHHH_Code] / ruralHouses / src / businessLogic / SecurityManager.java
1 package businessLogic;
2
3 import java.security.MessageDigest;
4 import java.security.NoSuchAlgorithmException;
5 import java.security.SecureRandom;
6 import java.security.spec.InvalidKeySpecException;
7 import java.util.Arrays;
8
9 import javax.crypto.SecretKeyFactory;
10 import javax.crypto.spec.PBEKeySpec;
11
12 public class SecurityManager {
13
14         private static SecurityManager secMan = null;
15
16         private SecurityManager() {
17         }
18
19         public static SecurityManager getInstance() {
20                 if (secMan == null)
21                         return new SecurityManager();
22                 else
23                         return secMan;
24         }
25
26         public byte[] generateSalt() {
27                 SecureRandom random = new SecureRandom();
28                 byte bytes[] = new byte[20];
29                 random.nextBytes(bytes);
30                 return bytes;
31         }
32
33         public byte[] calculateHash(String password) {
34                 byte[] hash = {};
35                 try {
36                         MessageDigest md = MessageDigest.getInstance("SHA1");
37                         md.update(password.getBytes());
38                         hash = md.digest();
39                 } catch (Exception e) {
40                         System.out.println("Exception: " + e);
41                 }
42                 return hash;
43         }
44
45         public byte[] calculateSaltedHash(char[] password, byte[] salt) {
46                 PBEKeySpec spec = new PBEKeySpec(password, salt, 10000, 256);
47                 Arrays.fill(password, Character.MIN_VALUE);
48                 try {
49                         SecretKeyFactory skf = SecretKeyFactory
50                                         .getInstance("PBKDF2WithHmacSHA1");
51                         return skf.generateSecret(spec).getEncoded();
52                 } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
53                         throw new AssertionError("Error while hashing a password: "
54                                         + e.getMessage(), e);
55                 } finally {
56                         spec.clearPassword();
57                 }
58         }
59
60         public boolean isExpectedPassword(char[] password, byte[] salt,
61                         byte[] expectedHash) {
62                 byte[] pwdHash = calculateSaltedHash(password, salt);
63                 Arrays.fill(password, Character.MIN_VALUE);
64                 if (pwdHash.length != expectedHash.length)
65                         return false;
66                 for (int i = 0; i < pwdHash.length; i++) {
67                         if (pwdHash[i] != expectedHash[i])
68                                 return false;
69                 }
70                 return true;
71         }
72 }