1 package usecase.auth;
2
3 import javax.crypto.SecretKeyFactory;
4 import javax.crypto.spec.PBEKeySpec;
5 import java.io.Serializable;
6 import java.security.NoSuchAlgorithmException;
7 import java.security.SecureRandom;
8 import java.security.spec.InvalidKeySpecException;
9 import java.security.spec.KeySpec;
10 import java.util.Arrays;
11
12
13
14
15 public class Pbkdf2PasswordHash implements Serializable {
16 public HashedPassword generate(String password, byte[] salt){
17 try {
18 KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 128);
19 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
20 byte[] hash = factory.generateSecret(spec).getEncoded();
21
22 return new HashedPassword(hash, salt);
23 } catch (InvalidKeySpecException | NoSuchAlgorithmException e) {
24 throw new RuntimeException(e);
25 }
26 }
27
28 public HashedPassword generate(String password){
29 return generate(password, generateSalt());
30 }
31
32 public boolean verify(String password, byte[] hashedPassword, byte[] salt){
33 return verify(password, new HashedPassword(hashedPassword, salt));
34 }
35
36 public boolean verify(String password, HashedPassword hashedPassword){
37 return hashedPassword.equals(generate(password, hashedPassword.getSalt()));
38 }
39
40 private static byte[] generateSalt(){
41 SecureRandom ss = new SecureRandom();
42 byte[] salt = new byte[16];
43 ss.nextBytes(salt);
44 return salt;
45 }
46
47 public static class HashedPassword{
48 private byte[] password;
49 private byte[] salt;
50
51 private HashedPassword(byte[] password, byte[] salt) {
52 this.password = password;
53 this.salt = salt;
54 }
55
56 public byte[] getPassword() {
57 return password;
58 }
59
60 public byte[] getSalt() {
61 return salt;
62 }
63
64 @Override
65 public boolean equals(Object o) {
66 if (this == o) return true;
67 if (o == null || getClass() != o.getClass()) return false;
68 HashedPassword that = (HashedPassword) o;
69 return Arrays.equals(password, that.password) && Arrays.equals(salt, that.salt);
70 }
71 }
72 }