1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * This library is free software; you can redistribute it and/or modify it under
5    * the terms of the GNU Lesser General Public License as published by the Free
6    * Software Foundation; either version 2.1 of the License, or (at your option)
7    * any later version.
8    *
9    * This library is distributed in the hope that it will be useful, but WITHOUT
10   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11   * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
12   * details.
13   */
14  
15  package com.liferay.portal.util;
16  
17  import com.liferay.portal.kernel.log.Log;
18  import com.liferay.portal.kernel.log.LogFactoryUtil;
19  import com.liferay.portal.kernel.util.Base64;
20  import com.liferay.portal.kernel.util.Digester;
21  
22  import java.io.UnsupportedEncodingException;
23  
24  import java.security.MessageDigest;
25  import java.security.NoSuchAlgorithmException;
26  
27  import org.apache.commons.codec.binary.Hex;
28  
29  /**
30   * <a href="DigesterImpl.java.html"><b><i>View Source</i></b></a>
31   *
32   * @author Brian Wing Shun Chan
33   */
34  public class DigesterImpl implements Digester {
35  
36      public String digest(String text) {
37          return digest(Digester.DIGEST_ALGORITHM, text);
38      }
39  
40      public String digest(String algorithm, String text) {
41          MessageDigest digester = null;
42  
43          try{
44              digester = MessageDigest.getInstance(algorithm);
45  
46              digester.update(text.getBytes(Digester.ENCODING));
47          }
48          catch (NoSuchAlgorithmException nsae) {
49              _log.error(nsae, nsae);
50          }
51          catch (UnsupportedEncodingException uee) {
52              _log.error(uee, uee);
53          }
54  
55          byte[] bytes = digester.digest();
56  
57          if (_BASE_64) {
58              return Base64.encode(bytes);
59          }
60          else {
61              return new String(Hex.encodeHex(bytes));
62          }
63      }
64  
65      private static final boolean _BASE_64 =
66          PropsValues.PASSWORDS_DIGEST_ENCODING.equals("base64");
67  
68      private static Log _log = LogFactoryUtil.getLog(Digester.class);
69  
70  }