]> WPIA git - gigi.git/blob - src/org/cacert/gigi/util/PasswordHash.java
upd: convert to PostgreSQL
[gigi.git] / src / org / cacert / gigi / util / PasswordHash.java
1 package org.cacert.gigi.util;
2
3 import java.io.UnsupportedEncodingException;
4 import java.security.MessageDigest;
5 import java.security.NoSuchAlgorithmException;
6
7 import com.lambdaworks.crypto.SCryptUtil;
8
9 public class PasswordHash {
10
11     /**
12      * Verifies a password hash.
13      * 
14      * @param password
15      *            The password that should result in the given hash.
16      * @param hash
17      *            The hash to verify the password against.
18      * @return <ul>
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>
24      *         </ul>
25      */
26     public static String verifyHash(String password, String hash) {
27         if (hash.contains("$")) {
28             if (SCryptUtil.check(password, hash)) {
29                 return hash;
30             } else {
31                 return null;
32             }
33         }
34         String newhash = sha1(password);
35         boolean match = true;
36         if (newhash.length() != hash.length()) {
37             match = false;
38         }
39         for (int i = 0; i < newhash.length(); i++) {
40             match &= newhash.charAt(i) == hash.charAt(i);
41         }
42         if (match) {
43             return hash(password);
44         } else {
45             return null;
46         }
47     }
48
49     public static String sha1(String password) {
50         try {
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));
57             }
58             return res.toString();
59         } catch (NoSuchAlgorithmException e) {
60             throw new Error(e);
61         } catch (UnsupportedEncodingException e) {
62             throw new Error(e);
63         }
64     }
65
66     public static String hash(String password) {
67         return SCryptUtil.scrypt(password, 1 << 14, 8, 1);
68     }
69 }