1 package org.cacert.gigi.util;
3 import java.io.UnsupportedEncodingException;
4 import java.security.MessageDigest;
5 import java.security.NoSuchAlgorithmException;
7 import com.lambdaworks.crypto.SCryptUtil;
9 public class PasswordHash {
12 * Verifies a password hash.
15 * The password that should result in the given hash.
17 * The hash to verify the password against.
19 * <li><code>null</code>, if the password was valid</li>
20 * <li><code>hash</code>, if the password is valid and the hash
21 * doesn't need to be updated</li>
22 * <li>a new hash, if the password is valid but the hash in the
23 * database needs to be updated.</li>
26 public static String verifyHash(String password, String hash) {
27 if (hash.contains("$")) {
28 if (SCryptUtil.check(password, hash)) {
34 String newhash = sha1(password);
36 if (newhash.length() != hash.length()) {
39 for (int i = 0; i < newhash.length(); i++) {
40 match &= newhash.charAt(i) == hash.charAt(i);
43 return hash(password);
49 public static String sha1(String password) {
51 MessageDigest md = MessageDigest.getInstance("SHA1");
52 byte[] digest = md.digest(password.getBytes("UTF-8"));
53 StringBuffer res = new StringBuffer(digest.length * 2);
54 for (int i = 0; i < digest.length; i++) {
55 res.append(Integer.toHexString((digest[i] & 0xF0) >> 4));
56 res.append(Integer.toHexString(digest[i] & 0xF));
58 return res.toString();
59 } catch (NoSuchAlgorithmException e) {
61 } catch (UnsupportedEncodingException e) {
66 public static String hash(String password) {
67 return SCryptUtil.scrypt(password, 1 << 14, 8, 1);