01: /*
02: * (C) Copyright 2000 - 2006 Nabh Information Systems, Inc.
03: *
04: * All copyright notices regarding Nabh's products MUST remain
05: * intact in the scripts and in the outputted HTML.
06: * This program is free software; you can redistribute it and/or
07: * modify it under the terms of the GNU Lesser General Public License
08: * as published by the Free Software Foundation; either version 2.1
09: * of the License, or (at your option) any later version.
10: *
11: * This program is distributed in the hope that it will be useful,
12: * but WITHOUT ANY WARRANTY; without even the implied warranty of
13: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14: * GNU Lesser General Public License for more details.
15: *
16: * You should have received a copy of the GNU Lesser General Public License
17: * along with this program; if not, write to the Free Software
18: * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19: *
20: */
21: package com.nabhinc.util.md;
22:
23: import java.security.MessageDigest;
24:
25: import org.apache.commons.logging.Log;
26: import org.apache.commons.logging.LogFactory;
27:
28: /**
29: *
30: *
31: * @author Padmanabh Dabke
32: * (c) 2006 Nabh Information Systems, Inc. All Rights Reserved.
33: */
34: public class DigestUtil {
35: public static Log log = LogFactory.getLog(DigestUtil.class);
36:
37: /**
38: * Digest password using the algorithm especificied and
39: * convert the result to a corresponding hex string.
40: * If exception, the plain credentials string is returned
41: *
42: * @param credentials Password or other credentials to use in
43: * authenticating this username
44: * @param algorithm Algorithm used to do the digest
45: * @param encoding Character encoding of the string to digest
46: */
47: public final static String Digest(String credentials,
48: String algorithm, String encoding) {
49:
50: try {
51: // Obtain a new message digest with "digest" encryption
52: MessageDigest md = (MessageDigest) MessageDigest
53: .getInstance(algorithm).clone();
54:
55: // encode the credentials
56: // Should use the digestEncoding, but that's not a static field
57: if (encoding == null) {
58: md.update(credentials.getBytes());
59: } else {
60: md.update(credentials.getBytes(encoding));
61: }
62:
63: // Digest the credentials and return as hexadecimal
64: return (HexUtils.convert(md.digest()));
65: } catch (Exception ex) {
66: log.error("Failed to create digest.", ex);
67: return credentials;
68: }
69: }
70:
71: }
|