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.
20 * <li><code>null</code>, if the password was valid</li>
21 * <li><code>hash</code>, if the password is valid and the hash
22 * doesn't need to be updated</li>
23 * <li>a new hash, if the password is valid but the hash in the
24 * database needs to be updated.</li>
27 public static String verifyHash(String password, String hash) {
28 if (password == null || password.isEmpty()) {
31 if (hash.contains("$")) {
32 if (SCryptUtil.check(password, hash)) {
38 String newhash = sha1(password);
40 if (newhash.length() != hash.length()) {
43 for (int i = 0; i < newhash.length(); i++) {
44 match &= newhash.charAt(i) == hash.charAt(i);
47 return hash(password);
53 public static String sha1(String password) {
55 MessageDigest md = MessageDigest.getInstance("SHA1");
56 byte[] digest = md.digest(password.getBytes("UTF-8"));
57 StringBuffer res = new StringBuffer(digest.length * 2);
58 for (int i = 0; i < digest.length; i++) {
59 res.append(Integer.toHexString((digest[i] & 0xF0) >> 4));
60 res.append(Integer.toHexString(digest[i] & 0xF));
62 return res.toString();
63 } catch (NoSuchAlgorithmException e) {
65 } catch (UnsupportedEncodingException e) {
70 public static String hash(String password) {
71 return SCryptUtil.scrypt(password, 1 << 14, 8, 1);