1   /**
2    * Copyright (c) 2000-2009 Liferay, Inc. All rights reserved.
3    *
4    * The contents of this file are subject to the terms of the Liferay Enterprise
5    * Subscription License ("License"). You may not use this file except in
6    * compliance with the License. You can obtain a copy of the License by
7    * contacting Liferay, Inc. See the License for the specific language governing
8    * permissions and limitations under the License, including but not limited to
9    * distribution rights of the Software.
10   *
11   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
12   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
13   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
14   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
15   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
16   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
17   * SOFTWARE.
18   */
19  
20  package com.liferay.util;
21  
22  import com.liferay.portal.kernel.log.Log;
23  import com.liferay.portal.kernel.log.LogFactoryUtil;
24  import com.liferay.portal.kernel.util.Base64;
25  import com.liferay.portal.kernel.util.Digester;
26  import com.liferay.portal.kernel.util.DigesterUtil;
27  import com.liferay.portal.kernel.util.GetterUtil;
28  import com.liferay.portal.kernel.util.ServerDetector;
29  
30  import java.security.Key;
31  import java.security.Provider;
32  import java.security.SecureRandom;
33  import java.security.Security;
34  
35  import javax.crypto.Cipher;
36  import javax.crypto.KeyGenerator;
37  
38  /**
39   * <a href="Encryptor.java.html"><b><i>View Source</i></b></a>
40   *
41   * @author Brian Wing Shun Chan
42   *
43   */
44  public class Encryptor {
45  
46      public static final String ENCODING = Digester.ENCODING;
47  
48      public static final String KEY_ALGORITHM = "DES";
49  
50      public static final String SUN_PROVIDER_CLASS =
51          "com.sun.crypto.provider.SunJCE";
52  
53      public static final String IBM_PROVIDER_CLASS =
54          "com.ibm.crypto.provider.IBMJCE";
55  
56      public static final String PROVIDER_CLASS = GetterUtil.getString(
57          SystemProperties.get(Encryptor.class.getName() + ".provider.class"),
58          SUN_PROVIDER_CLASS);
59  
60      public static Key generateKey() throws EncryptorException {
61          return generateKey(KEY_ALGORITHM);
62      }
63  
64      public static Key generateKey(String algorithm) throws EncryptorException {
65          try {
66              Security.addProvider(getProvider());
67  
68              KeyGenerator generator = KeyGenerator.getInstance(algorithm);
69              generator.init(56, new SecureRandom());
70  
71              Key key = generator.generateKey();
72  
73              return key;
74          }
75          catch (Exception e) {
76              throw new EncryptorException(e);
77          }
78      }
79  
80      public static Provider getProvider()
81          throws ClassNotFoundException, IllegalAccessException,
82                 InstantiationException {
83  
84          Class<?> providerClass = null;
85  
86          try {
87              providerClass = Class.forName(PROVIDER_CLASS);
88          }
89          catch (ClassNotFoundException cnfe) {
90              if ((ServerDetector.isWebSphere()) &&
91                  (PROVIDER_CLASS.equals(SUN_PROVIDER_CLASS))) {
92  
93                  if (_log.isWarnEnabled()) {
94                      _log.warn(
95                          "WebSphere does not have " + SUN_PROVIDER_CLASS +
96                              ", using " + IBM_PROVIDER_CLASS + " instead");
97                  }
98  
99                  providerClass = Class.forName(IBM_PROVIDER_CLASS);
100             }
101             else if (System.getProperty("java.vm.vendor").equals(
102                         "IBM Corporation")) {
103 
104                 if (_log.isWarnEnabled()) {
105                     _log.warn(
106                         "IBM JVM does not have " + SUN_PROVIDER_CLASS +
107                             ", using " + IBM_PROVIDER_CLASS + " instead");
108                 }
109 
110                 providerClass = Class.forName(IBM_PROVIDER_CLASS);
111             }
112             else {
113                 throw cnfe;
114             }
115         }
116 
117         return (Provider)providerClass.newInstance();
118     }
119 
120     public static String decrypt(Key key, String encryptedString)
121         throws EncryptorException {
122 
123         byte[] encryptedBytes = Base64.decode(encryptedString);
124 
125         return decryptUnencodedAsString(key, encryptedBytes);
126     }
127 
128     public static byte[] decryptUnencodedAsBytes(Key key, byte[] encryptedBytes)
129         throws EncryptorException {
130 
131         try {
132             Security.addProvider(getProvider());
133 
134             Cipher cipher = Cipher.getInstance(key.getAlgorithm());
135 
136             cipher.init(Cipher.DECRYPT_MODE, key);
137 
138             return cipher.doFinal(encryptedBytes);
139         }
140         catch (Exception e) {
141             throw new EncryptorException(e);
142         }
143     }
144 
145     public static String decryptUnencodedAsString(
146             Key key, byte[] encryptedBytes)
147         throws EncryptorException {
148 
149         try {
150             byte[] decryptedBytes = decryptUnencodedAsBytes(
151                 key, encryptedBytes);
152 
153             return new String(decryptedBytes, ENCODING);
154         }
155         catch (Exception e) {
156             throw new EncryptorException(e);
157         }
158     }
159 
160     public static String digest(String text) {
161         return DigesterUtil.digest(text);
162     }
163 
164     public static String digest(String algorithm, String text) {
165         return DigesterUtil.digest(algorithm, text);
166     }
167 
168     public static String encrypt(Key key, String plainText)
169         throws EncryptorException {
170 
171         byte[] encryptedBytes = encryptUnencoded(key, plainText);
172 
173         return Base64.encode(encryptedBytes);
174     }
175 
176     public static byte[] encryptUnencoded(Key key, byte[] plainBytes)
177         throws EncryptorException {
178 
179         try {
180             Security.addProvider(getProvider());
181 
182             Cipher cipher = Cipher.getInstance(key.getAlgorithm());
183 
184             cipher.init(Cipher.ENCRYPT_MODE, key);
185 
186             return cipher.doFinal(plainBytes);
187         }
188         catch (Exception e) {
189             throw new EncryptorException(e);
190         }
191     }
192 
193     public static byte[] encryptUnencoded(Key key, String plainText)
194         throws EncryptorException {
195 
196         try {
197             byte[] decryptedBytes = plainText.getBytes(ENCODING);
198 
199             return encryptUnencoded(key, decryptedBytes);
200         }
201         catch (Exception e) {
202             throw new EncryptorException(e);
203         }
204     }
205 
206     private static Log _log = LogFactoryUtil.getLog(Encryptor.class);
207 
208 }