1 package org.cacert.gigi.util;
3 import java.security.MessageDigest;
4 import java.security.NoSuchAlgorithmException;
6 import com.lambdaworks.crypto.SCryptUtil;
8 public class PasswordHash {
11 * Verifies a password hash.
14 * The password that should result in the given hash.
16 * The hash to verify the password against.
18 * <li><code>null</code>, if the password was valid</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 (hash.contains("$")) {
27 if (SCryptUtil.check(password, hash)) {
33 String newhash = sha1(password);
35 if (newhash.length() != hash.length()) {
38 for (int i = 0; i < newhash.length(); i++) {
39 match &= newhash.charAt(i) == hash.charAt(i);
42 return hash(password);
48 private static String sha1(String password) {
50 MessageDigest md = MessageDigest.getInstance("SHA1");
51 byte[] digest = md.digest(password.getBytes());
52 StringBuffer res = new StringBuffer(digest.length * 2);
53 for (int i = 0; i < digest.length; i++) {
54 res.append(Integer.toHexString((digest[i] & 0xF0) >> 4));
55 res.append(Integer.toHexString(digest[i] & 0xF));
57 return res.toString();
58 } catch (NoSuchAlgorithmException e) {
63 public static String hash(String password) {
64 return SCryptUtil.scrypt(password, 1 << 14, 8, 1);