1 package club.wpia.gigi.util;
3 import java.util.Properties;
5 import com.lambdaworks.crypto.SCryptUtil;
7 public class PasswordHash {
10 * Verifies a password hash.
13 * The password that should result in the given hash.
15 * The hash to verify the password against.
18 * <li><code>null</code>, if the password was invalid</li>
19 * <li><code>hash</code>, if the password is valid and the hash
20 * doesn't need to be updated</li>
21 * <li>a new hash, if the password is valid but the hash in the
22 * database needs to be updated.</li>
25 public static String verifyHash(String password, String hash) {
26 if (password == null || password.isEmpty()) {
30 if (hash.contains("$")) {
31 if (SCryptUtil.check(password, hash)) {
41 public static String hash(String password) {
42 return SCryptUtil.scrypt(password, N, r, p);
45 private static int N = 1 << 14;
47 private static int r = 8;
49 private static int p = 1;
51 private static boolean initialized = false;
53 public static synchronized void init(Properties prop) {
55 throw new IllegalStateException("Already initialized.");
57 String val = prop.getProperty("scrypt.params", "14;8;1");
58 String[] parts = val.split(";", 3);
59 int N = 1 << Integer.parseInt(parts[0]);
60 int r = Integer.parseInt(parts[1]);
61 int p = Integer.parseInt(parts[2]);
62 checkScryptParams(N, r, p);
69 private static void checkScryptParams(int N, int r, int p) {
70 if (N < 2 || (N & (N - 1)) != 0) {
71 throw new IllegalArgumentException("N must be a power of 2 greater than 1");
74 throw new IllegalArgumentException("Parameter r zero or negative");
77 throw new IllegalArgumentException("Parameter p zero or negative");
80 if (N > Integer.MAX_VALUE / 128 / r) {
81 throw new IllegalArgumentException("Parameter N is too large");
83 if (r > Integer.MAX_VALUE / 128 / p) {
84 throw new IllegalArgumentException("Parameter r is too large");