001
014
015 package com.liferay.portal.util;
016
017 import com.liferay.portal.kernel.log.Log;
018 import com.liferay.portal.kernel.log.LogFactoryUtil;
019 import com.liferay.portal.kernel.util.Base64;
020 import com.liferay.portal.kernel.util.Digester;
021 import com.liferay.portal.kernel.util.StringBundler;
022 import com.liferay.portal.kernel.util.StringPool;
023
024 import java.io.UnsupportedEncodingException;
025
026 import java.security.MessageDigest;
027 import java.security.NoSuchAlgorithmException;
028
029 import org.apache.commons.codec.binary.Hex;
030
031
035 public class DigesterImpl implements Digester {
036
037 public String digest(String text) {
038 return digest(Digester.DEFAULT_ALGORITHM, text);
039 }
040
041 public String digest(String algorithm, String... text) {
042 if (_BASE_64) {
043 return digestBase64(algorithm, text);
044 }
045 else {
046 return digestHex(algorithm, text);
047 }
048 }
049
050 public String digestBase64(String text) {
051 return digestBase64(Digester.DEFAULT_ALGORITHM, text);
052 }
053
054 public String digestBase64(String algorithm, String... text) {
055 byte[] bytes = digestRaw(algorithm, text);
056
057 return Base64.encode(bytes);
058 }
059
060 public String digestHex(String text) {
061 return digestHex(Digester.DEFAULT_ALGORITHM, text);
062 }
063
064 public String digestHex(String algorithm, String... text) {
065 byte[] bytes = digestRaw(algorithm, text);
066
067 return Hex.encodeHexString(bytes);
068 }
069
070 public byte[] digestRaw(String text) {
071 return digestRaw(Digester.DEFAULT_ALGORITHM, text);
072 }
073
074 public byte[] digestRaw(String algorithm, String... text) {
075 MessageDigest messageDigest = null;
076
077 try{
078 messageDigest = MessageDigest.getInstance(algorithm);
079
080 StringBundler sb = new StringBundler(text.length * 2 - 1);
081
082 for (String t : text) {
083 if (sb.length() > 0) {
084 sb.append(StringPool.COLON);
085 }
086
087 sb.append(t);
088 }
089
090 String s = sb.toString();
091
092 messageDigest.update(s.getBytes(Digester.ENCODING));
093 }
094 catch (NoSuchAlgorithmException nsae) {
095 _log.error(nsae, nsae);
096 }
097 catch (UnsupportedEncodingException uee) {
098 _log.error(uee, uee);
099 }
100
101 return messageDigest.digest();
102 }
103
104 private static final boolean _BASE_64 =
105 PropsValues.PASSWORDS_DIGEST_ENCODING.equals("base64");
106
107 private static Log _log = LogFactoryUtil.getLog(Digester.class);
108
109 }