1
1
package com .vip .saturn .job .console .utils ;
2
2
3
- import org .apache .commons .codec .binary .Base64 ;
3
+ import org .apache .commons .codec .DecoderException ;
4
+ import org .apache .commons .codec .binary .Hex ;
5
+ import org .slf4j .Logger ;
6
+ import org .slf4j .LoggerFactory ;
4
7
5
8
import javax .crypto .SecretKey ;
6
9
import javax .crypto .SecretKeyFactory ;
@@ -15,6 +18,8 @@ public class PasswordUtils {
15
18
16
19
public static final String HASH_METHOD_PBKDF2 = "PBKDF2WithHmacSHA1" ;
17
20
21
+ private static final Logger log = LoggerFactory .getLogger (PasswordUtils .class );
22
+
18
23
private static final int ITERATIONS = 10 * 1000 ;
19
24
20
25
private static final int SALT_LEN = 8 ;
@@ -31,7 +36,7 @@ public static String genPassword(String password, String hashMethod) throws Exce
31
36
}
32
37
33
38
public static String genPassword (String password , byte [] salt , String hashMethod ) throws Exception {
34
- return hash (password , salt , hashMethod ) + "$" + Base64 . encodeBase64String (salt );
39
+ return hash (password , salt , hashMethod ) + "$" + Hex . encodeHexString (salt );
35
40
}
36
41
37
42
public static String hash (String password , byte [] salt , String hashMethod ) throws NoSuchAlgorithmException , InvalidKeySpecException {
@@ -43,21 +48,31 @@ public static String hash(String password, byte[] salt, String hashMethod) throw
43
48
}
44
49
45
50
SecretKey key = secretKeyFactory .generateSecret (new PBEKeySpec (password .toCharArray (), salt , ITERATIONS , KEY_LEN ));
46
- return Base64 . encodeBase64String (key .getEncoded ());
51
+ return Hex . encodeHexString (key .getEncoded ());
47
52
}
48
53
49
- public static boolean validate (String password , String passwordInDB , String hashMethod ) throws Exception {
54
+ public static boolean validate (String password , String passwordInDB , String hashMethod ) {
50
55
if (PasswordUtils .HASH_METHOD_PLANTEXT .equals (hashMethod )) {
51
56
return password .equals (passwordInDB );
52
57
}
53
58
54
59
String [] saltAndPassword = passwordInDB .split ("\\ $" );
55
60
if (saltAndPassword .length != 2 ) {
56
- throw new IllegalArgumentException ("Invalid password stored in DB" );
61
+ log .debug ("malformed password in db" );
62
+ return false ;
57
63
}
58
64
59
- String hashOfRequestPassword = hash (password , Base64 .decodeBase64 (saltAndPassword [1 ]), hashMethod );
65
+ String hashOfRequestPassword = null ;
66
+ try {
67
+ hashOfRequestPassword = hash (password , getSalt (saltAndPassword [1 ]), hashMethod );
68
+ } catch (Exception e ) {
69
+ return false ;
70
+ }
60
71
return hashOfRequestPassword .equals (new String (saltAndPassword [0 ]));
61
72
}
62
73
74
+ private static byte [] getSalt (String s ) throws DecoderException {
75
+ return Hex .decodeHex (s .toCharArray ());
76
+ }
77
+
63
78
}
0 commit comments