View Javadoc
1   package org.apache.fulcrum.jce.crypto.extended;
2   
3   /*
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *   http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.
20   */
21  
22  import java.io.ByteArrayInputStream;
23  import java.io.IOException;
24  import java.io.InputStream;
25  import java.io.OutputStream;
26  import java.security.GeneralSecurityException;
27  import java.security.Key;
28  import java.security.NoSuchAlgorithmException;
29  import java.security.SecureRandom;
30  import java.util.Map;
31  import java.util.concurrent.ConcurrentHashMap;
32  
33  import javax.crypto.Cipher;
34  
35  import org.apache.fulcrum.jce.crypto.PasswordFactory;
36  import org.apache.fulcrum.jce.crypto.StreamUtil;
37  import org.apache.fulcrum.jce.crypto.algo.CryptoStreamGCMImpl;
38  import org.apache.fulcrum.jce.crypto.algo.CryptoStreamPBEImpl;
39  import org.apache.fulcrum.jce.crypto.extended.CryptoParametersJ8.TYPES;
40  
41  /**
42   * Concrete factory for creating encrypting/decrypting streams. 
43   * 
44   * 
45   **/
46  public abstract class CryptoStreamFactoryJ8Template /*  extends CryptoStreamFactoryImpl*/ implements CryptoStreamFactoryJ8
47  {
48  	
49  	/** the salt for the algorithm */
50      protected byte[] salt;
51  
52      /** the count parameter for the algorithm, not used for GCM */
53      protected int count;
54  
55      /** the name of the JCE provider */
56      protected String providerName;
57  
58      /** the algorithm to use */
59      protected String algorithm;
60      
61      private TYPES type;
62      
63      public TYPES getType() {
64        return type;
65      }
66      
67      public void setType(TYPES type) {
68      	this.type = type;
69      }
70      
71      /**
72       * The JCE provider name known to work. If the value
73       * is set to null an appropriate provider will be
74       * used.
75       */
76      protected static final String PROVIDERNAME = null;
77  
78      protected static final int SALT_SIZE = 16; //might increase cipher length
79  
80      /** the default instances */
81      protected static final Map<TYPES,CryptoStreamFactoryJ8Template> instances = new ConcurrentHashMap<>();
82      
83      //protected AlgorithmParameters algorithmParameters;// used only for debugging
84     
85      public CryptoStreamFactoryJ8Template() {
86         
87      }
88      
89      /**
90       * Factory method to get a default instance
91       * 
92       * creating instance of type {@link CryptoParametersJ8#DEFAULT_TYPE}.
93       * 
94       * @return an instance of the CryptoStreamFactory
95       */
96      public static CryptoStreamFactoryJ8 getInstance() 
97      {
98          synchronized (CryptoStreamFactoryJ8Template.class) {
99              if( !instances.containsKey(CryptoParametersJ8.DEFAULT_TYPE) )
100             {
101                 try {
102                     instances.put(CryptoParametersJ8.DEFAULT_TYPE, 
103                             (CryptoParametersJ8.DEFAULT_TYPE.equals(TYPES.PBE))? new CryptoStreamPBEImpl():
104                                 new CryptoStreamGCMImpl()
105                             );
106                 } catch (GeneralSecurityException e) {
107                     e.printStackTrace();
108                     throw new RuntimeException(e.getMessage());
109                 }
110             }
111     
112             return instances.get(CryptoParametersJ8.DEFAULT_TYPE);
113         }
114     }
115 
116     /**
117      * Factory method to get a default instance
118      * 
119      * @param type the @see {@link TYPES} of the instance.
120      * @return an instance of the CryptoStreamFactory
121      */
122     public static CryptoStreamFactoryJ8 getInstance(TYPES type) 
123     {
124         synchronized (CryptoStreamFactoryJ8Template.class) {
125             if( !instances.containsKey(type) )
126             {
127                 try {
128                     instances.put(type, 
129                             (type.equals(TYPES.PBE))? new CryptoStreamPBEImpl():
130                                 new CryptoStreamGCMImpl()
131                             );
132                 } catch (GeneralSecurityException e) {
133                     e.printStackTrace();
134                     throw new RuntimeException(e.getMessage());
135                 }
136             }
137     
138             return instances.get(type);
139         }
140     }
141     
142     /**
143      * Factory method to get a default instance
144      * 
145      * @param type the @see {@link TYPES} of the instance.
146      * @param salt provided salt
147      * @param count provided count, used only for {@link TYPES#PBE}.
148      * @return an instance of the CryptoStreamFactory
149      */
150     public static CryptoStreamFactoryJ8 getInstance(TYPES type, byte[] salt, int count) 
151     {
152         synchronized (CryptoStreamFactoryJ8Template.class) {
153             if( !instances.containsKey(type) )
154             {
155                 try {
156                     instances.put(type, 
157                             (type.equals(TYPES.PBE))? new CryptoStreamPBEImpl(salt, count):
158                                 new CryptoStreamGCMImpl(salt)
159                             );
160                 } catch (Exception e) {
161                     e.printStackTrace();
162                     throw new RuntimeException(e.getMessage());
163                 }
164             }
165     
166             return instances.get(type);
167         }
168     }
169 
170 
171     /**
172      * @see org.apache.fulcrum.jce.crypto.CryptoStreamFactory#getSmartInputStream(java.io.InputStream)
173      */
174 
175     public InputStream getSmartInputStream(InputStream is)
176         throws GeneralSecurityException, IOException
177     {
178         return this.getSmartInputStream(
179             is,
180             PasswordFactory.getInstance("SHA-256").create()
181             );
182     }
183 
184     /**
185      * @see org.apache.fulcrum.jce.crypto.CryptoStreamFactory#getInputStream(java.io.InputStream,char[])
186      */
187     public InputStream getInputStream( InputStream is, char[] password )
188         throws GeneralSecurityException, IOException
189     {
190         byte[] decrypted =  this.createCipher( is, Cipher.DECRYPT_MODE, password.clone() );
191         InputStream eis = new ByteArrayInputStream(decrypted);
192         return eis;
193     }
194 
195     /**
196      * @see org.apache.fulcrum.jce.crypto.extended.CryptoStreamFactoryJ8#getOutputStream(InputStream, OutputStream, char[])
197      */
198     public OutputStream getOutputStream(InputStream is, OutputStream os, char[] password)
199             throws GeneralSecurityException, IOException {
200         byte[] encrypted =  this.createCipher( is, Cipher.ENCRYPT_MODE, password.clone() );
201         InputStream eis = new ByteArrayInputStream(encrypted);
202         StreamUtil.copy(eis, os);
203         return os;
204     }
205     
206     /**
207      * resets the default instances
208      */
209     public static void resetInstances()
210     {
211         CryptoStreamFactoryJ8Template.instances.clear();
212     }
213     
214 //    /**
215 //     * Set the default instances from an external application.
216 //     * @param instances the new default instances map
217 //     * @throws Exception if instances are null
218 //     */
219 //    public static void setInstances(Map<TYPES,CryptoStreamFactoryJ8Template> instances ) throws Exception
220 //    {
221 //    	if (instances == null) throw new Exception("setting instances to null not allowed!");
222 //        CryptoStreamFactoryJ8Template.instances = instances;
223 //    }
224     
225     /** not used / implemented methods **/
226     
227     @Override
228 	public InputStream getInputStream(InputStream is, String decryptionMode)
229 			throws GeneralSecurityException, IOException {
230 		throw new UnsupportedOperationException("not implemented");
231 	}
232 
233 	@Override
234 	public InputStream getInputStream(InputStream is, String decryptionMode, char[] password)
235 			throws GeneralSecurityException, IOException {
236 		throw new UnsupportedOperationException("not implemented");
237 	}
238 
239 	@Override
240 	public InputStream getInputStream(InputStream is) throws GeneralSecurityException, IOException {
241 		throw new UnsupportedOperationException("not implemented");
242 	}
243 
244 	@Override
245 	public InputStream getSmartInputStream(InputStream is, char[] password)
246 			throws GeneralSecurityException, IOException {
247 		throw new UnsupportedOperationException("not implemented");
248 	}
249 
250 	@Override
251 	public OutputStream getOutputStream(OutputStream os) throws GeneralSecurityException, IOException {
252 		throw new UnsupportedOperationException("not implemented");
253 	}
254 
255 	@Override
256 	public OutputStream getOutputStream(OutputStream os, char[] password) throws GeneralSecurityException, IOException {
257 		throw new UnsupportedOperationException("not implemented");
258 	}
259     /** not used methods end **/
260 
261     /**
262      * Create a PBE key.
263      *
264      * @param password the password to use.
265      * @param salt if provided this is used, otherweise {@link #getSalt()}.
266      * @return the key
267      * @throws GeneralSecurityException creating the key failed
268      */
269     protected abstract Key createKey( char[] password, byte[] salt ) 
270             throws GeneralSecurityException;
271 
272     /**
273      * Create a Cipher.
274      *
275      * @param is the input stream
276      * @param mode the cipher mode
277      * @param password the password
278      * @return an instance of a cipher
279      * @return the cipher as byte array
280      * @throws GeneralSecurityException creating a cipher failed
281      * @throws IOException creating a cipher failed
282      */
283     protected abstract byte[] createCipher(InputStream is, int mode, char[] password )
284         throws GeneralSecurityException, IOException;
285     
286     /**
287      * creates salt from {@link SecureRandom#getInstance(String)} by default was algorithm SHA1PRNG
288      * 
289      * changed to {@link SecureRandom#getInstanceStrong()} and let the system decide, what PRNG to use for salt random.
290      * 
291      * salt size is by default @link {@value #SALT_SIZE}.
292      * 
293      * @return the generated salt as byte array
294      * @throws GeneralSecurityException if no algo could be found.
295      */
296     protected static byte[] generateSalt() throws GeneralSecurityException {
297         SecureRandom random;
298         try {
299             random = SecureRandom.getInstanceStrong();
300             byte[] salt = new byte[SALT_SIZE ];
301             random.nextBytes(salt);
302             return salt;
303         } catch (NoSuchAlgorithmException e) {
304             throw new GeneralSecurityException(e);  
305         }
306     }
307 
308 	public byte[] getSalt() {
309 		return salt.clone();
310 	}
311 
312 	protected void setSalt(byte[] salt) {
313 		this.salt = salt.clone();
314 	}
315 
316 	public int getCount() {
317 		return count;
318 	}
319 
320 	public void setCount(int count) {
321 		this.count = count;
322 	}
323 
324 	public String getProviderName() {
325 		return providerName;
326 	}
327 
328 	public void setProviderName(String providerName) {
329 		this.providerName = providerName;
330 	}
331 
332 	public String getAlgorithm() {
333 		return algorithm;
334 	}
335 
336 	public void setAlgorithm(String algorithm) {
337 		this.algorithm = algorithm;
338 	}
339 
340 }