01: /**********************************************************************************
02: * $HeadURL: https://source.sakaiproject.org/svn/util/tags/sakai_2-4-1/util-util/util/src/java/org/sakaiproject/util/PathHashUtil.java $
03: * $Id: PathHashUtil.java 18350 2006-11-21 19:47:05Z jimeng@umich.edu $
04: ***********************************************************************************
05: *
06: * Copyright (c) 2006 The Sakai Foundation.
07: *
08: * Licensed under the Educational Community License, Version 1.0 (the "License");
09: * you may not use this file except in compliance with the License.
10: * You may obtain a copy of the License at
11: *
12: * http://www.opensource.org/licenses/ecl1.php
13: *
14: * Unless required by applicable law or agreed to in writing, software
15: * distributed under the License is distributed on an "AS IS" BASIS,
16: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17: * See the License for the specific language governing permissions and
18: * limitations under the License.
19: *
20: **********************************************************************************/package org.sakaiproject.util;
21:
22: import java.security.MessageDigest;
23: import java.security.NoSuchAlgorithmException;
24: import org.apache.commons.logging.Log;
25: import org.apache.commons.logging.LogFactory;
26:
27: /**
28: *
29: * A utility class to generate a SHA1 hash based on a full path to a resource/entity.
30: *
31: */
32: public class PathHashUtil {
33: private static final Log log = LogFactory
34: .getLog(PathHashUtil.class);
35:
36: private static char[] encode = { '0', '1', '2', '3', '4', '5', '6',
37: '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
38:
39: private static ThreadLocal digest = new ThreadLocal();
40:
41: /**
42: * create a SHA1 hash of the path
43: *
44: * @param nodePath
45: * @param encode
46: * @return
47: * @throws NoSuchAlgorithmException
48: */
49: public static String hash(String nodePath) {
50: MessageDigest mdigest = (MessageDigest) digest.get();
51: if (mdigest == null) {
52: try {
53: mdigest = MessageDigest.getInstance("SHA1");
54: } catch (NoSuchAlgorithmException e) {
55: log.error("Cant find Hash Algorithm ", e);
56: }
57: digest.set(mdigest);
58: }
59: byte[] b = mdigest.digest(nodePath.getBytes());
60: char[] c = new char[b.length * 2];
61: for (int i = 0; i < b.length; i++) {
62: c[i * 2] = encode[b[i] & 0x0f];
63: c[i * 2 + 1] = encode[(b[i] >> 4) & 0x0f];
64: }
65: String encoded = new String(c);
66: log.debug("Encoded " + nodePath + " as " + encoded);
67: return encoded;
68: }
69:
70: }
|