KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mmbase > util > transformers > EncryptionTransformerFactory


1 /*
2
3  This software is OSI Certified Open Source Software.
4  OSI Certified is a certification mark of the Open Source Initiative.
5
6  The license (Mozilla version 1.0) can be read at the MMBase site.
7  See http://www.MMBase.org/license
8
9  */

10
11 package org.mmbase.util.transformers;
12
13 import java.io.Reader JavaDoc;
14 import java.io.Writer JavaDoc;
15 import java.security.GeneralSecurityException JavaDoc;
16
17 import javax.crypto.Cipher;
18 import javax.crypto.spec.SecretKeySpec;
19
20 import org.mmbase.util.functions.Parameter;
21 import org.mmbase.util.functions.Parameters;
22 import org.mmbase.util.logging.Logger;
23 import org.mmbase.util.logging.Logging;
24
25 /**
26  * This transformerfactory can encrypt and decrypt strings. The algorithm which is
27  * used for encryption/decryption is parameterized, and defaults to AES. Since
28  * these encryption algorithms return raw bytes, an encoding must be supplied
29  * which is used to convert bytes to characters: either hexadecimal encoding
30  * or base64.
31  * @author Sander de Boer
32  */

33
34 public class EncryptionTransformerFactory implements ParameterizedTransformerFactory {
35     private static final Logger log = Logging.getLoggerInstance(EncryptionTransformerFactory.class);
36
37     /**
38      * Encode a given array of bytes to a string, using the given format.
39      * This can be 'hex' or 'base64'.
40      */

41     public static String JavaDoc encode(byte input[], String JavaDoc format) {
42         if ("hex".equalsIgnoreCase(format)) {
43             Hex h = new Hex();
44             String JavaDoc output = h.transform(input);
45             return output;
46         } else if ("base64".equalsIgnoreCase(format)) {
47             Base64 b = new Base64();
48             String JavaDoc output = b.transform(input);
49             return output;
50         }
51         return "";
52     }
53
54     /**
55      * Decode a given string to an array of bytes, using a given format.
56      * This can throw an 'IllegalArgumentException' when the given input
57      * string isn't correct according to the format.
58      */

59     public static byte[] decode(String JavaDoc input, String JavaDoc format) throws IllegalArgumentException JavaDoc{
60         if ("hex".equalsIgnoreCase(format)) {
61             Hex h = new Hex();
62             byte[] output = h.transformBack(input);
63             return output;
64         } else if ("base64".equalsIgnoreCase(format)) {
65             Base64 b = new Base64();
66             byte[] output = b.transformBack(input);
67             return output;
68         }
69         return new byte[0];
70     }
71
72     protected final static Parameter[] PARAMS = {
73         new Parameter("key", String JavaDoc.class, "1234567890abcdef"),
74         new Parameter("format", String JavaDoc.class, "hex"),
75         new Parameter("algorithm", String JavaDoc.class, "AES"),
76         new Parameter("direction", String JavaDoc.class, "encrypt")
77     };
78
79     public Parameters createParameters() {
80         return new Parameters(PARAMS);
81     }
82
83     /**
84      * Return a parameterized transformer, based on the given parameters. These can be the following:
85      * <ul>
86      * <li>algorithm, defaults to 'AES'</li>
87      * <li>direction, can be 'encrypt' or 'decrypt'</li>
88      * <li>format, can be 'base64' or 'hex'</li>
89      * <li>key, defaults to '1234567890abcdef' (NOTE: the length of this key must match the requirements set by the algorithm</li>
90      * </ul>
91      */

92     public Transformer createTransformer(Parameters parameters) {
93         String JavaDoc direction = (String JavaDoc) parameters.get("direction");
94         if ("encrypt".equalsIgnoreCase(direction)) {
95             return new Encryption((String JavaDoc) parameters.get("key"), (String JavaDoc) parameters.get("format"), (String JavaDoc) parameters.get("algorithm"));
96         } else if ("decrypt".equalsIgnoreCase(direction)) {
97             return new Decryption((String JavaDoc) parameters.get("key"), (String JavaDoc) parameters.get("format"), (String JavaDoc) parameters.get("algorithm"));
98         } else {
99             throw new UnsupportedOperationException JavaDoc("Unknown value for attribute 'direction', (known are 'encrypt' and 'decrypt')");
100         }
101     }
102
103     class Encryption extends ReaderTransformer {
104         private String JavaDoc key;
105         private String JavaDoc format;
106         private String JavaDoc algorithm;
107
108         Encryption(String JavaDoc key, String JavaDoc format, String JavaDoc algorithm) {
109             this.key = key;
110             this.format = format;
111             this.algorithm = algorithm;
112
113             if ((!"base64".equalsIgnoreCase(format)) & (!"hex".equalsIgnoreCase(format))) {
114                 throw new UnsupportedOperationException JavaDoc("Unknown value for attribute 'format', (known are 'base64' and 'hex')");
115             }
116         }
117
118         public Writer JavaDoc transform(Reader JavaDoc r, Writer JavaDoc w) {
119             StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
120
121             try {
122                 int i;
123                 while ((i = r.read()) > -1) {
124                     sb.append((char) i);
125                 }
126                 byte input[] = sb.toString().getBytes();
127
128                 byte[] secretKey = key.getBytes();
129                 SecretKeySpec skeySpec = new SecretKeySpec(secretKey, algorithm);
130
131                 Cipher cipher = Cipher.getInstance(algorithm);
132                 cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
133                 byte encrypted[] = cipher.doFinal(input);
134
135                 String JavaDoc output = encode(encrypted, format);
136
137                 w.write(output);
138                 return w;
139                 
140             } catch (IllegalArgumentException JavaDoc h) {
141                 throw new UnsupportedOperationException JavaDoc(h.getMessage());
142             } catch (SecurityException JavaDoc g) {
143                 throw new UnsupportedOperationException JavaDoc(g.getMessage());
144             } catch (GeneralSecurityException JavaDoc f) {
145                 throw new UnsupportedOperationException JavaDoc(f.getMessage());
146             } catch (Exception JavaDoc e) {
147                 log.error(e.getMessage() + Logging.stackTrace(e));
148             }
149             return w;
150         }
151     }
152
153     class Decryption extends ReaderTransformer {
154         private String JavaDoc key;
155         private String JavaDoc format;
156         private String JavaDoc algorithm;
157
158         Decryption(String JavaDoc key, String JavaDoc format, String JavaDoc algorithm) {
159             this.key = key;
160             this.format = format;
161             this.algorithm = algorithm;
162
163             if ((!"base64".equalsIgnoreCase(format)) & (!"hex".equalsIgnoreCase(format))) {
164                 throw new UnsupportedOperationException JavaDoc("Unknown value for attribute 'format', (known are 'base64' and 'hex')");
165             }
166         }
167
168         public Writer JavaDoc transform(Reader JavaDoc r, Writer JavaDoc w) {
169             StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
170
171             try {
172                 int i;
173                 while ((i = r.read()) > -1) {
174                     sb.append((char) i);
175                 }
176
177                 byte[] input = decode(sb.toString(), format);
178
179                 byte[] secretKey = key.getBytes();
180                 SecretKeySpec skeySpec = new SecretKeySpec(secretKey, algorithm);
181
182                 Cipher cipher = Cipher.getInstance(algorithm);
183                 cipher.init(Cipher.DECRYPT_MODE, skeySpec);
184                 byte decrypted[] = cipher.doFinal(input);
185                 String JavaDoc output = new String JavaDoc(decrypted);
186                 w.write(output);
187                 return w;
188
189             } catch (IllegalArgumentException JavaDoc h) {
190                 throw new UnsupportedOperationException JavaDoc(h.getMessage());
191             } catch (SecurityException JavaDoc g) {
192                 throw new UnsupportedOperationException JavaDoc(g.getMessage());
193             } catch (GeneralSecurityException JavaDoc f) {
194                 throw new UnsupportedOperationException JavaDoc(f.getMessage());
195             } catch (Exception JavaDoc e) {
196                 log.error(e.getMessage() + Logging.stackTrace(e));
197             }
198             return w;
199         }
200     }
201 }
202
Popular Tags