1 /* Copyright (2007) Schibsted Søk AS
2 * This file is part of SESAT.
3 *
4 * SESAT is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU Affero General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * SESAT is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU Affero General Public License for more details.
13 *
14 * You should have received a copy of the GNU Affero General Public License
15 * along with SESAT. If not, see <http://www.gnu.org/licenses/>.
16 */
17 package no.sesat.search.security;
18
19 import org.apache.commons.codec.binary.Hex;
20
21 import java.security.MessageDigest;
22 import java.security.NoSuchAlgorithmException;
23
24 /**
25 *
26 * @version <tt>$Revision: 6596 $</tt>
27 */
28 public final class MD5Generator {
29
30 private static final byte[] EMPTY_STRING = new byte[0];
31
32 private final String secret;
33
34 public MD5Generator(final String secret) {
35
36 this.secret = secret;
37 }
38
39 public String generateMD5(final String s) {
40
41 final MessageDigest digest = getDigest("MD5");
42
43 digest.update(null != s ? s.getBytes() : EMPTY_STRING);
44 digest.update(secret.getBytes());
45
46 return String.valueOf(Hex.encodeHex(digest.digest()));
47 }
48
49 public boolean validate(final String s, final String hash) {
50
51 return generateMD5(s).equals(hash);
52
53 }
54
55 /**
56 * Returns a MessageDigest for the given <code>algorithm</code>.
57 *
58 * @param algorithm The MessageDigest algorithm name.
59 * @return An digest instance.
60 * @throws RuntimeException when a {@link java.security.NoSuchAlgorithmException} is caught,
61 */
62 static MessageDigest getDigest(String algorithm) {
63
64 try {
65 return MessageDigest.getInstance(algorithm);
66 } catch (NoSuchAlgorithmException e) {
67 throw new RuntimeException(e.getMessage());
68 }
69 }
70 }