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;
9 import javax.crypto.SecretKeyFactory;
10 import javax.crypto.spec.PBEKeySpec;
12 public class SecurityManager {
14 private static SecurityManager secMan = null;
16 private SecurityManager() {
19 public static SecurityManager getInstance() {
21 return new SecurityManager();
26 public byte[] generateSalt() {
27 SecureRandom random = new SecureRandom();
28 byte bytes[] = new byte[20];
29 random.nextBytes(bytes);
33 public byte[] calculateHash(String password) {
36 MessageDigest md = MessageDigest.getInstance("SHA1");
37 md.update(password.getBytes());
39 } catch (Exception e) {
40 System.out.println("Exception: " + e);
45 public byte[] calculateSaltedHash(char[] password, byte[] salt) {
46 PBEKeySpec spec = new PBEKeySpec(password, salt, 10000, 256);
47 Arrays.fill(password, Character.MIN_VALUE);
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: "
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)
66 for (int i = 0; i < pwdHash.length; i++) {
67 if (pwdHash[i] != expectedHash[i])