1   /**
2    * Copyright (c) 2000-2009 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.log.Log;
26  import com.liferay.portal.kernel.log.LogFactoryUtil;
27  import com.liferay.portal.kernel.util.Base64;
28  import com.liferay.portal.kernel.util.Digester;
29  import com.liferay.portal.kernel.util.DigesterUtil;
30  import com.liferay.portal.kernel.util.GetterUtil;
31  import com.liferay.portal.kernel.util.ServerDetector;
32  
33  import java.security.Key;
34  import java.security.Provider;
35  import java.security.SecureRandom;
36  import java.security.Security;
37  
38  import javax.crypto.Cipher;
39  import javax.crypto.KeyGenerator;
40  
41  /**
42   * <a href="Encryptor.java.html"><b><i>View Source</i></b></a>
43   *
44   * @author Brian Wing Shun Chan
45   *
46   */
47  public class Encryptor {
48  
49      public static final String ENCODING = Digester.ENCODING;
50  
51      public static final String KEY_ALGORITHM = "DES";
52  
53      public static final String SUN_PROVIDER_CLASS =
54          "com.sun.crypto.provider.SunJCE";
55  
56      public static final String IBM_PROVIDER_CLASS =
57          "com.ibm.crypto.provider.IBMJCE";
58  
59      public static final String PROVIDER_CLASS = GetterUtil.getString(
60          SystemProperties.get(Encryptor.class.getName() + ".provider.class"),
61          SUN_PROVIDER_CLASS);
62  
63      public static Key generateKey() throws EncryptorException {
64          return generateKey(KEY_ALGORITHM);
65      }
66  
67      public static Key generateKey(String algorithm) throws EncryptorException {
68          try {
69              Security.addProvider(getProvider());
70  
71              KeyGenerator generator = KeyGenerator.getInstance(algorithm);
72              generator.init(56, new SecureRandom());
73  
74              Key key = generator.generateKey();
75  
76              return key;
77          }
78          catch (Exception e) {
79              throw new EncryptorException(e);
80          }
81      }
82  
83      public static Provider getProvider()
84          throws ClassNotFoundException, IllegalAccessException,
85                 InstantiationException {
86  
87          Class<?> providerClass = null;
88  
89          try {
90              providerClass = Class.forName(PROVIDER_CLASS);
91          }
92          catch (ClassNotFoundException cnfe) {
93              if ((ServerDetector.isWebSphere()) &&
94                  (PROVIDER_CLASS.equals(SUN_PROVIDER_CLASS))) {
95  
96                  if (_log.isWarnEnabled()) {
97                      _log.warn(
98                          "WebSphere does not have " + SUN_PROVIDER_CLASS +
99                              ", using " + IBM_PROVIDER_CLASS + " instead");
100                 }
101 
102                 providerClass = Class.forName(IBM_PROVIDER_CLASS);
103             }
104             else if (System.getProperty("java.vm.vendor").equals(
105                         "IBM Corporation")) {
106 
107                 if (_log.isWarnEnabled()) {
108                     _log.warn(
109                         "IBM JVM does not have " + SUN_PROVIDER_CLASS +
110                             ", using " + IBM_PROVIDER_CLASS + " instead");
111                 }
112 
113                 providerClass = Class.forName(IBM_PROVIDER_CLASS);
114             }
115             else {
116                 throw cnfe;
117             }
118         }
119 
120         return (Provider)providerClass.newInstance();
121     }
122 
123     public static String decrypt(Key key, String encryptedString)
124         throws EncryptorException {
125 
126         byte[] encryptedBytes = Base64.decode(encryptedString);
127 
128         return decryptUnencodedAsString(key, encryptedBytes);
129     }
130 
131     public static byte[] decryptUnencodedAsBytes(Key key, byte[] encryptedBytes)
132         throws EncryptorException {
133 
134         try {
135             Security.addProvider(getProvider());
136 
137             Cipher cipher = Cipher.getInstance(key.getAlgorithm());
138 
139             cipher.init(Cipher.DECRYPT_MODE, key);
140 
141             return cipher.doFinal(encryptedBytes);
142         }
143         catch (Exception e) {
144             throw new EncryptorException(e);
145         }
146     }
147 
148     public static String decryptUnencodedAsString(
149             Key key, byte[] encryptedBytes)
150         throws EncryptorException {
151 
152         try {
153             byte[] decryptedBytes = decryptUnencodedAsBytes(
154                 key, encryptedBytes);
155 
156             return new String(decryptedBytes, ENCODING);
157         }
158         catch (Exception e) {
159             throw new EncryptorException(e);
160         }
161     }
162 
163     public static String digest(String text) {
164         return DigesterUtil.digest(text);
165     }
166 
167     public static String digest(String algorithm, String text) {
168         return DigesterUtil.digest(algorithm, text);
169     }
170 
171     public static String encrypt(Key key, String plainText)
172         throws EncryptorException {
173 
174         byte[] encryptedBytes = encryptUnencoded(key, plainText);
175 
176         return Base64.encode(encryptedBytes);
177     }
178 
179     public static byte[] encryptUnencoded(Key key, byte[] plainBytes)
180         throws EncryptorException {
181 
182         try {
183             Security.addProvider(getProvider());
184 
185             Cipher cipher = Cipher.getInstance(key.getAlgorithm());
186 
187             cipher.init(Cipher.ENCRYPT_MODE, key);
188 
189             return cipher.doFinal(plainBytes);
190         }
191         catch (Exception e) {
192             throw new EncryptorException(e);
193         }
194     }
195 
196     public static byte[] encryptUnencoded(Key key, String plainText)
197         throws EncryptorException {
198 
199         try {
200             byte[] decryptedBytes = plainText.getBytes(ENCODING);
201 
202             return encryptUnencoded(key, decryptedBytes);
203         }
204         catch (Exception e) {
205             throw new EncryptorException(e);
206         }
207     }
208 
209     private static Log _log = LogFactoryUtil.getLog(Encryptor.class);
210 
211 }