Source Code Cross Referenced for EncryptionTransformerFactory.java in  » Database-ORM » MMBase » org » mmbase » util » transformers » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Database ORM » MMBase » org.mmbase.util.transformers 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /*
002:
003:         This software is OSI Certified Open Source Software.
004:         OSI Certified is a certification mark of the Open Source Initiative.
005:
006:         The license (Mozilla version 1.0) can be read at the MMBase site.
007:         See http://www.MMBase.org/license
008:
009:         */
010:
011:        package org.mmbase.util.transformers;
012:
013:        import java.io.Reader;
014:        import java.io.Writer;
015:        import java.security.GeneralSecurityException;
016:
017:        import javax.crypto.Cipher;
018:        import javax.crypto.spec.SecretKeySpec;
019:
020:        import org.mmbase.util.functions.Parameter;
021:        import org.mmbase.util.functions.Parameters;
022:        import org.mmbase.util.logging.Logger;
023:        import org.mmbase.util.logging.Logging;
024:
025:        /**
026:         * This transformerfactory can encrypt and decrypt strings. The algorithm which is
027:         * used for encryption/decryption is parameterized, and defaults to AES. Since
028:         * these encryption algorithms return raw bytes, an encoding must be supplied
029:         * which is used to convert bytes to characters: either hexadecimal encoding
030:         * or base64.
031:         * @author Sander de Boer
032:         */
033:
034:        public class EncryptionTransformerFactory implements 
035:                ParameterizedTransformerFactory<CharTransformer> {
036:            private static final Logger log = Logging
037:                    .getLoggerInstance(EncryptionTransformerFactory.class);
038:
039:            /**
040:             * Encode a given array of bytes to a string, using the given format.
041:             * This can be 'hex' or 'base64'.
042:             */
043:            public static String encode(byte input[], String format) {
044:                if ("hex".equalsIgnoreCase(format)) {
045:                    Hex h = new Hex();
046:                    String output = h.transform(input);
047:                    return output;
048:                } else if ("base64".equalsIgnoreCase(format)) {
049:                    Base64 b = new Base64();
050:                    String output = b.transform(input);
051:                    return output;
052:                }
053:                return "";
054:            }
055:
056:            /**
057:             * Decode a given string to an array of bytes, using a given format.
058:             * This can throw an 'IllegalArgumentException' when the given input
059:             * string isn't correct according to the format.
060:             */
061:            public static byte[] decode(String input, String format)
062:                    throws IllegalArgumentException {
063:                if ("hex".equalsIgnoreCase(format)) {
064:                    Hex h = new Hex();
065:                    byte[] output = h.transformBack(input);
066:                    return output;
067:                } else if ("base64".equalsIgnoreCase(format)) {
068:                    Base64 b = new Base64();
069:                    byte[] output = b.transformBack(input);
070:                    return output;
071:                }
072:                return new byte[0];
073:            }
074:
075:            protected final static Parameter[] PARAMS = {
076:                    new Parameter<String>("key", String.class,
077:                            "1234567890abcdef"),
078:                    new Parameter<String>("format", String.class, "hex"),
079:                    new Parameter<String>("algorithm", String.class, "AES"),
080:                    new Parameter<String>("direction", String.class, "encrypt") };
081:
082:            public Parameters createParameters() {
083:                return new Parameters(PARAMS);
084:            }
085:
086:            /**
087:             * Return a parameterized transformer, based on the given parameters. These can be the following:
088:             * <ul>
089:             *  <li>algorithm, defaults to 'AES'</li>
090:             *  <li>direction, can be 'encrypt' or 'decrypt'</li>
091:             *  <li>format, can be 'base64' or 'hex'</li>
092:             *  <li>key, defaults to '1234567890abcdef' (NOTE: the length of this key must match the requirements set by the algorithm</li>
093:             * </ul>
094:             */
095:            public CharTransformer createTransformer(Parameters parameters) {
096:                String direction = (String) parameters.get("direction");
097:                if ("encrypt".equalsIgnoreCase(direction)) {
098:                    return new Encryption((String) parameters.get("key"),
099:                            (String) parameters.get("format"),
100:                            (String) parameters.get("algorithm"));
101:                } else if ("decrypt".equalsIgnoreCase(direction)) {
102:                    return new Decryption((String) parameters.get("key"),
103:                            (String) parameters.get("format"),
104:                            (String) parameters.get("algorithm"));
105:                } else {
106:                    throw new UnsupportedOperationException(
107:                            "Unknown value for attribute 'direction', (known are 'encrypt' and 'decrypt')");
108:                }
109:            }
110:
111:            class Encryption extends ReaderTransformer {
112:                private String key;
113:                private String format;
114:                private String algorithm;
115:
116:                Encryption(String key, String format, String algorithm) {
117:                    this .key = key;
118:                    this .format = format;
119:                    this .algorithm = algorithm;
120:
121:                    if ((!"base64".equalsIgnoreCase(format))
122:                            & (!"hex".equalsIgnoreCase(format))) {
123:                        throw new UnsupportedOperationException(
124:                                "Unknown value for attribute 'format', (known are 'base64' and 'hex')");
125:                    }
126:                }
127:
128:                public Writer transform(Reader r, Writer w) {
129:                    StringBuilder sb = new StringBuilder();
130:
131:                    try {
132:                        int i;
133:                        while ((i = r.read()) > -1) {
134:                            sb.append((char) i);
135:                        }
136:                        byte input[] = sb.toString().getBytes();
137:
138:                        byte[] secretKey = key.getBytes();
139:                        SecretKeySpec skeySpec = new SecretKeySpec(secretKey,
140:                                algorithm);
141:
142:                        Cipher cipher = Cipher.getInstance(algorithm);
143:                        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
144:                        byte encrypted[] = cipher.doFinal(input);
145:
146:                        String output = encode(encrypted, format);
147:
148:                        w.write(output);
149:                        return w;
150:
151:                    } catch (IllegalArgumentException h) {
152:                        throw new UnsupportedOperationException(h.getMessage());
153:                    } catch (SecurityException g) {
154:                        throw new UnsupportedOperationException(g.getMessage());
155:                    } catch (GeneralSecurityException f) {
156:                        throw new UnsupportedOperationException(f.getMessage());
157:                    } catch (Exception e) {
158:                        log.error(e.getMessage() + Logging.stackTrace(e));
159:                    }
160:                    return w;
161:                }
162:            }
163:
164:            class Decryption extends ReaderTransformer {
165:                private String key;
166:                private String format;
167:                private String algorithm;
168:
169:                Decryption(String key, String format, String algorithm) {
170:                    this .key = key;
171:                    this .format = format;
172:                    this .algorithm = algorithm;
173:
174:                    if ((!"base64".equalsIgnoreCase(format))
175:                            & (!"hex".equalsIgnoreCase(format))) {
176:                        throw new UnsupportedOperationException(
177:                                "Unknown value for attribute 'format', (known are 'base64' and 'hex')");
178:                    }
179:                }
180:
181:                public Writer transform(Reader r, Writer w) {
182:                    StringBuilder sb = new StringBuilder();
183:
184:                    try {
185:                        int i;
186:                        while ((i = r.read()) > -1) {
187:                            sb.append((char) i);
188:                        }
189:
190:                        byte[] input = decode(sb.toString(), format);
191:
192:                        byte[] secretKey = key.getBytes();
193:                        SecretKeySpec skeySpec = new SecretKeySpec(secretKey,
194:                                algorithm);
195:
196:                        Cipher cipher = Cipher.getInstance(algorithm);
197:                        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
198:                        byte decrypted[] = cipher.doFinal(input);
199:                        String output = new String(decrypted);
200:                        w.write(output);
201:                        return w;
202:
203:                    } catch (IllegalArgumentException h) {
204:                        throw new UnsupportedOperationException(h.getMessage());
205:                    } catch (SecurityException g) {
206:                        throw new UnsupportedOperationException(g.getMessage());
207:                    } catch (GeneralSecurityException f) {
208:                        throw new UnsupportedOperationException(f.getMessage());
209:                    } catch (Exception e) {
210:                        log.error(e.getMessage() + Logging.stackTrace(e));
211:                    }
212:                    return w;
213:                }
214:            }
215:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.