package businessLogic; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException; import java.util.Arrays; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; public class SecurityManager { private static SecurityManager secMan = null; private SecurityManager() { } public static SecurityManager getInstance() { if (secMan == null) return new SecurityManager(); else return secMan; } public byte[] generateSalt() { SecureRandom random = new SecureRandom(); byte bytes[] = new byte[20]; random.nextBytes(bytes); return bytes; } public byte[] calculateHash(String password) { byte[] hash = {}; try { MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(password.getBytes()); hash = md.digest(); } catch (Exception e) { System.out.println("Exception: " + e); } return hash; } public byte[] calculateSaltedHash(char[] password, byte[] salt) { PBEKeySpec spec = new PBEKeySpec(password, salt, 10000, 256); Arrays.fill(password, Character.MIN_VALUE); try { SecretKeyFactory skf = SecretKeyFactory .getInstance("PBKDF2WithHmacSHA1"); return skf.generateSecret(spec).getEncoded(); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { throw new AssertionError("Error while hashing a password: " + e.getMessage(), e); } finally { spec.clearPassword(); } } public boolean isExpectedPassword(char[] password, byte[] salt, byte[] expectedHash) { byte[] pwdHash = calculateSaltedHash(password, salt); Arrays.fill(password, Character.MIN_VALUE); if (pwdHash.length != expectedHash.length) return false; for (int i = 0; i < pwdHash.length; i++) { if (pwdHash[i] != expectedHash[i]) return false; } return true; } }