1   /**
2    * Copyright (c) 2000-2008 Liferay, Inc. All rights reserved.
3    *
4    * Permission is hereby granted, free of charge, to any person obtaining a copy
5    * of this software and associated documentation files (the "Software"), to deal
6    * in the Software without restriction, including without limitation the rights
7    * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8    * copies of the Software, and to permit persons to whom the Software is
9    * furnished to do so, subject to the following conditions:
10   *
11   * The above copyright notice and this permission notice shall be included in
12   * all copies or substantial portions of the Software.
13   *
14   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20   * SOFTWARE.
21   */
22  
23  package com.liferay.util;
24  
25  import com.liferay.portal.kernel.util.Base64;
26  import com.liferay.portal.kernel.util.Digester;
27  import com.liferay.portal.kernel.util.DigesterUtil;
28  import com.liferay.portal.kernel.util.GetterUtil;
29  import com.liferay.portal.kernel.util.ServerDetector;
30  
31  import java.security.Key;
32  import java.security.Provider;
33  import java.security.SecureRandom;
34  import java.security.Security;
35  
36  import javax.crypto.Cipher;
37  import javax.crypto.KeyGenerator;
38  
39  import org.apache.commons.logging.Log;
40  import org.apache.commons.logging.LogFactory;
41  
42  /**
43   * <a href="Encryptor.java.html"><b><i>View Source</i></b></a>
44   *
45   * @author Brian Wing Shun Chan
46   *
47   */
48  public class Encryptor {
49  
50      public static final String ENCODING = Digester.ENCODING;
51  
52      public static final String KEY_ALGORITHM = "DES";
53  
54      public static final String SUN_PROVIDER_CLASS =
55          "com.sun.crypto.provider.SunJCE";
56  
57      public static final String IBM_PROVIDER_CLASS =
58          "com.ibm.crypto.provider.IBMJCE";
59  
60      public static final String PROVIDER_CLASS = GetterUtil.getString(
61          SystemProperties.get(Encryptor.class.getName() + ".provider.class"),
62          SUN_PROVIDER_CLASS);
63  
64      public static Key generateKey() throws EncryptorException {
65          return generateKey(KEY_ALGORITHM);
66      }
67  
68      public static Key generateKey(String algorithm) throws EncryptorException {
69          try {
70              Security.addProvider(getProvider());
71  
72              KeyGenerator generator = KeyGenerator.getInstance(algorithm);
73              generator.init(56, new SecureRandom());
74  
75              Key key = generator.generateKey();
76  
77              return key;
78          }
79          catch (Exception e) {
80              throw new EncryptorException(e);
81          }
82      }
83  
84      public static Provider getProvider()
85          throws ClassNotFoundException, IllegalAccessException,
86                 InstantiationException {
87  
88          Class<?> providerClass = null;
89  
90          try {
91              providerClass = Class.forName(PROVIDER_CLASS);
92          }
93          catch (ClassNotFoundException cnfe) {
94              if ((ServerDetector.isWebSphere()) &&
95                  (PROVIDER_CLASS.equals(SUN_PROVIDER_CLASS))) {
96  
97                  if (_log.isWarnEnabled()) {
98                      _log.warn(
99                          "WebSphere does not have " + SUN_PROVIDER_CLASS +
100                             ", using " + IBM_PROVIDER_CLASS + " instead");
101                 }
102 
103                 providerClass = Class.forName(IBM_PROVIDER_CLASS);
104             }
105             else if (System.getProperty("java.vm.vendor").equals(
106                         "IBM Corporation")) {
107 
108                 if (_log.isWarnEnabled()) {
109                     _log.warn(
110                         "IBM JVM does not have " + SUN_PROVIDER_CLASS +
111                             ", using " + IBM_PROVIDER_CLASS + " instead");
112                 }
113 
114                 providerClass = Class.forName(IBM_PROVIDER_CLASS);
115             }
116             else {
117                 throw cnfe;
118             }
119         }
120 
121         return (Provider)providerClass.newInstance();
122     }
123 
124     public static String decrypt(Key key, String encryptedString)
125         throws EncryptorException {
126 
127         byte[] encryptedBytes = Base64.decode(encryptedString);
128 
129         return decryptRaw(key, encryptedBytes);
130     }
131 
132     public static String decryptRaw(Key key, byte[] encryptedBytes)
133         throws EncryptorException {
134 
135         try {
136             Security.addProvider(getProvider());
137 
138             Cipher cipher = Cipher.getInstance(key.getAlgorithm());
139 
140             cipher.init(Cipher.DECRYPT_MODE, key);
141 
142             byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
143 
144             String decryptedString = new String(decryptedBytes, ENCODING);
145 
146             return decryptedString;
147         }
148         catch (Exception e) {
149             throw new EncryptorException(e);
150         }
151     }
152 
153     public static String digest(String text) {
154         return DigesterUtil.digest(text);
155     }
156 
157     public static String digest(String algorithm, String text) {
158         return DigesterUtil.digest(algorithm, text);
159     }
160 
161     public static String encrypt(Key key, String plainText)
162         throws EncryptorException {
163 
164         byte[] encryptedBytes = encryptRaw(key, plainText);
165 
166         return Base64.encode(encryptedBytes);
167     }
168 
169     public static byte[] encryptRaw(Key key, String plainText)
170         throws EncryptorException {
171 
172         try {
173             Security.addProvider(getProvider());
174 
175             Cipher cipher = Cipher.getInstance(key.getAlgorithm());
176 
177             cipher.init(Cipher.ENCRYPT_MODE, key);
178 
179             byte[] decryptedBytes = plainText.getBytes(ENCODING);
180             byte[] encryptedBytes = cipher.doFinal(decryptedBytes);
181 
182             return encryptedBytes;
183         }
184         catch (Exception e) {
185             throw new EncryptorException(e);
186         }
187     }
188 
189     private static Log _log = LogFactory.getLog(Encryptor.class);
190 
191 }