1
14
15 package com.liferay.portal.cache.key;
16
17 import com.liferay.portal.kernel.cache.key.CacheKeyGenerator;
18 import com.liferay.portal.kernel.log.Log;
19 import com.liferay.portal.kernel.log.LogFactoryUtil;
20 import com.liferay.portal.kernel.util.StringBundler;
21
22 import java.security.MessageDigest;
23
24
29 public class JavaMD5CacheKeyGenerator implements CacheKeyGenerator {
30
31 public String getCacheKey(String key) {
32 try {
33 return doGetCacheKey(key);
34 }
35 catch (Exception e) {
36 _log.error(e, e);
37
38 return key;
39 }
40 }
41
42 public void setMaxLength(int maxLength) {
43 _maxLength = maxLength;
44 }
45
46 protected String doGetCacheKey(String key) throws Exception {
47 if ((_maxLength > -1) && (key.length() < _maxLength)) {
48 return key;
49 }
50
51 MessageDigest messageDigest = MessageDigest.getInstance(_ALGORITHM_MD5);
52
53 messageDigest.update(key.getBytes());
54
55 byte[] bytes = messageDigest.digest();
56
57 StringBundler sb = new StringBundler(2 * bytes.length);
58
59 for (int i = 0; i < bytes.length; i++) {
60 int value = bytes[i] & 0xff;
61
62 sb.append((char)_HEX_CHARACTERS[value >> 4]);
63 sb.append((char)_HEX_CHARACTERS[value & 0xf]);
64 }
65
66 return sb.toString();
67 }
68
69 private static final String _ALGORITHM_MD5 = "MD5";
70
71 private static final byte[] _HEX_CHARACTERS = {
72 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
73 'e', 'f'
74 };
75
76 private static Log _log = LogFactoryUtil.getLog(
77 JavaMD5CacheKeyGenerator.class);
78
79 private int _maxLength = -1;
80
81 }