This project has retired. For details please refer to its Attic page.
AES xref
View Javadoc
1   /*
2    * Copyright 2001-2013 The Apache Software Foundation.
3    * 
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * 
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    * 
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   *
16   */
17  package org.apache.juddi.adminconsole;
18  
19  import java.nio.charset.Charset;
20  import javax.crypto.*;
21  import javax.crypto.spec.*;
22  import org.apache.commons.codec.binary.Base64;
23  
24  import org.apache.commons.logging.Log;
25  import org.apache.commons.logging.LogFactory;
26  
27  /**
28   * <summary> This program uses a AES key, retrieves its raw bytes, and then
29   * reinstantiates a AES key from the key bytes.</summary> The reinstantiated key
30   * is used to initialize a AES cipher for encryption and decryption. source :
31   * http://java.sun.com/developer/technicalArticles/Security/AES/AES_v1.html
32   *
33   * @author <a href="mailto:alexoree@apache.org">Alex O'Ree</a>
34   */
35  public class AES {
36  
37          public static final String logname = "org.apache.juddi.gui";
38          public static final Log log = LogFactory.getLog(logname);
39  
40          /**
41           * generates an AES based off of the selected key size
42           *
43           * @param keysize
44           * @return may return null if the key is not of a supported size by the
45           * current jdk
46           */
47          public static String GEN(int keysize) {
48                  KeyGenerator kgen;
49                  try {
50                          kgen = KeyGenerator.getInstance("AES");
51                          kgen.init(keysize);
52                          SecretKey skey = kgen.generateKey();
53                          byte[] raw = skey.getEncoded();
54                          return new String(Base64.encodeBase64(raw), Charset.defaultCharset());
55                  } catch (Exception ex) {
56                          log.fatal("error generating key", ex);
57                  }
58                  return null;
59          }
60  
61          /**
62           * Generate a new AES 256 bit encryption key. Once generated, this key
63           * can be used to replace the default key.
64           *
65           * @return a base64 encoded key, 256 bit
66           */
67          public static String GEN() {
68                  return GEN(256);
69          }
70  
71          static String EN(String cleartext, String key) throws Exception {
72                  byte[] raw =//skey.getEncoded();
73                          Base64.decodeBase64(key.getBytes(Charset.defaultCharset())); //
74                  SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
75                  // Instantiate the cipher
76                  Cipher cipher = Cipher.getInstance("AES");
77                  cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
78                  byte[] encrypted = cipher.doFinal(cleartext.getBytes());
79                  return  new String(Base64.encodeBase64(encrypted), Charset.defaultCharset());
80          }
81  
82          static String DE(String ciphertext, String key) throws Exception {
83                  byte[] raw =//skey.getEncoded();
84                          Base64.decodeBase64(key.getBytes(Charset.defaultCharset())); //
85                  SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
86                  Cipher cipher = Cipher.getInstance("AES");
87                  cipher.init(Cipher.DECRYPT_MODE, skeySpec);
88                  byte[] original = cipher.doFinal(Base64.decodeBase64(ciphertext.getBytes(Charset.defaultCharset())));
89                  return new String(original);
90          }
91  
92          /**
93           * return true is the supplied key is a valid aes key
94           *
95           * @param key
96           * @return true if the key is valid
97           */
98          public static boolean ValidateKey(String key) {
99                  try {
100                         String src = "abcdefghijklmopqrstuvwxyz123567890!@#$%^&*()_+{}|:\">?<,";
101                         String x = EN(src, key);
102                         String y = DE(x, key);
103                         //if the sample text is encryptable and decryptable, and it was actually encrypted
104                         if (y.equals(src) && !x.equals(y)) {
105                                 return true;
106                         }
107                         return false;
108                 } catch (Exception ex) {
109                         log.info("Key validation failed! "+ ex.getMessage());
110                         log.debug("Key validation failed! "+ ex.getMessage(), ex);
111                         return false;
112                 }
113         }
114 
115         /**
116          * encrypts a password using AES Requires the Unlimited Strength Crypto
117          * Extensions
118          *
119          * @param clear
120          * @param key
121          * @return a base64 encoded cipher of the clear text using the key
122          */
123         public static String Encrypt(String clear, String key) throws Exception {
124                 if ((clear == null || clear.length() == 0)) {
125                         return "";
126                 }
127                 if (key == null || key.length() == 0) {
128                         log.fatal("The generated encryption key was null or emtpy!");
129                 }
130                 try {
131                         return AES.EN(clear, key);
132                 } catch (Exception ex) {
133                         log.fatal("Cannot encrypt sensitive information! Check to make sure the unlimited strength JCE is installed " + ex.getMessage(), ex);
134                         throw new Exception("Internal Configuration Error, See Log for details. ");
135                 }
136                 // return "";
137         }
138 
139         /**
140          * Decrypts a password or other sensitive data If the parameter is null
141          * or empty, an empty string is returned. If the parameter is not
142          * encrypted or was encrypted using a different key or it fails to
143          * decrypt, the original text is returned.
144          *
145          * @param cipher encrypted text
146          * @param key
147          * @return the decrypted string
148          */
149         public static String Decrypt(String cipher, String key) {
150                 if ((cipher == null || cipher.length() == 0)) {
151                         return "";
152                 }
153                 if (key == null || key.length() == 0) {
154                         log.fatal("The generated encryption key was null or emtpy!");
155                 }
156                 try {
157                         return AES.DE(cipher, key);
158                 } catch (Exception ex) {
159                         log.fatal("trouble decrypting data, check to make sure the unlimited strength JCE is installed. If this error occured during deployment, I'll automatically try a smaller key size. " + ex.getMessage(), ex);
160                 }
161                 return cipher;
162 
163         }
164 }