View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.shiro.crypto.cipher;
20  
21  import org.apache.shiro.lang.util.StringUtils;
22  
23  /**
24   * Base abstract class for block cipher algorithms.
25   *
26   * <h2>Usage</h2>
27   * Note that this class exists mostly to simplify algorithm-specific subclasses.  Unless you understand the concepts of
28   * cipher modes of operation, block sizes, and padding schemes, and you want direct control of these things, you should
29   * typically not uses instances of this class directly.  Instead, algorithm-specific subclasses, such as
30   * {@link AesCipherService}, {@link BlowfishCipherService}, and others are usually better suited for regular use.
31   * <p/>
32   * However, if you have the need to create a custom block cipher service where no sufficient algorithm-specific subclass
33   * exists in Shiro, this class would be very useful.
34   *
35   * <h2>Configuration</h2>
36   * Block ciphers can accept configuration parameters that direct how they operate.  These parameters concatenated
37   * together in a single String comprise what the JDK JCA documentation calls a
38   * <a href="http://java.sun.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html#trans">transformation
39   * string</a>.  We think that it is better for Shiro to construct this transformation string automatically based on its
40   * constituent parts instead of having the end-user construct the string manually, which may be error prone or
41   * confusing.  To that end, Shiro {@link DefaultBlockCipherService}s have attributes that can be set individually in
42   * a type-safe manner based on your configuration needs, and Shiro will build the transformation string for you.
43   * <p/>
44   * The following sections typically document the configuration options for block (byte array)
45   * {@link #encrypt(byte[], byte[])} and {@link #decrypt(byte[], byte[])} method invocations.  Streaming configuration
46   * for those same attributes are done via mirrored {@code streaming}* attributes, and their purpose is identical, but
47   * they're only used during streaming {@link #encrypt(java.io.InputStream, java.io.OutputStream, byte[])} and
48   * {@link #decrypt(java.io.InputStream, java.io.OutputStream, byte[])} methods.  See the &quot;Streaming&quot;
49   * section below for more.
50   *
51   * <h3>Block Size</h3>
52   * The block size specifies the number of bits (not bytes) that the cipher operates on when performing an operation.
53   * It can be specified explicitly via the {@link #setBlockSize blockSize} attribute.  If not set, the JCA Provider
54   * default will be used based on the cipher algorithm.  Block sizes are usually very algorithm specific, so set this
55   * value only if you know you don't want the JCA Provider's default for the desired algorithm.  For example, the
56   * AES algorithm's Rijndael implementation <em>only</em> supports a 128 bit block size and will not work with any other
57   * size.
58   * <p/>
59   * Also note that the {@link #setInitializationVectorSize initializationVectorSize} is usually the same as the
60   * {@link #setBlockSize blockSize} in block ciphers.  If you change either attribute, you should ensure that the other
61   * attribute is correct for the target cipher algorithm.
62   *
63   * <h3>Operation Mode</h3>
64   * You may set the block cipher's<a href="http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation">mode of
65   * operation</a> via the {@link #setMode(OperationMode) mode} attribute, which accepts a type-safe
66   * {@link OperationMode OperationMode} enum instance.  This type safety helps avoid typos when specifying the mode and
67   * guarantees that the mode name will be recognized by the underlying JCA Provider.
68   * <p/>
69   * <b>*</b>If no operation mode is specified, Shiro defaults all of its block {@code CipherService} instances to the
70   * {@link OperationMode#CBC CBC} mode, specifically to support auto-generation of initialization vectors during
71   * encryption.  This is different than the JDK's default {@link OperationMode#ECB ECB} mode because {@code ECB} does
72   * not support initialization vectors, which are necessary for strong encryption.  See  the
73   * {@link JcaCipherService JcaCipherService parent class} class JavaDoc for an extensive
74   * explanation on why we do this and why we do not use the Sun {@code ECB} default.  You also might also want read
75   * the <a href="http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29">Wikipedia
76   * section on ECB<a/> and look at the encrypted image to see an example of why {@code ECB} should not be used in
77   * security-sensitive environments.
78   * <p/>
79   * In the rare case that you need to override the default with a mode not represented
80   * by the {@link OperationMode} enum, you may specify the raw mode name string that will be recognized by your JCA
81   * provider via the {@link #setModeName modeName} attribute.  Because this is not type-safe, it is recommended only to
82   * use this attribute if the {@link OperationMode} enum does not represent your desired mode.
83   * <p/>
84   * <b>NOTE:</b> If you change the mode to one that does not support initialization vectors (such as
85   * {@link OperationMode#ECB ECB} or {@link OperationMode#NONE NONE}), you <em>must</em> turn off auto-generated
86   * initialization vectors by setting {@link #setGenerateInitializationVectors(boolean) generateInitializationVectors}
87   * to {@code false}.  Abandoning initialization vectors significantly weakens encryption, so think twice before
88   * disabling this feature.
89   *
90   * <h3>Padding Scheme</h3>
91   * Because block ciphers process messages in fixed-length blocks, if the final block in a message is not equal to the
92   * block length, <a href="http://en.wikipedia.org/wiki/Padding_(cryptography)">padding</a> is applied to match that
93   * size to maintain the total length of the message.  This is good because it protects data patterns from being
94   * identified  - when all chunks look the same length, it is much harder to infer what that data might be.
95   * <p/>
96   * You may set a padding scheme via the {@link #setPaddingScheme(PaddingScheme) paddingScheme} attribute, which
97   * accepts a type-safe {@link PaddingScheme PaddingScheme} enum instance.  Like the {@link OperationMode} enum,
98   * this enum offers type safety to help avoid typos and guarantees that the mode will be recognized by the underlying
99   * JCA provider.
100  * <p/>
101  * <b>*</b>If no padding scheme is specified, this class defaults to the {@link PaddingScheme#PKCS5} scheme, specifically
102  * to be compliant with the default behavior of auto-generating initialization vectors during encryption (see the
103  * {@link JcaCipherService JcaCipherService parent class} class JavaDoc for why).
104  * <p/>
105  * In the rare case that you need to override the default with a scheme not represented by the {@link PaddingScheme}
106  * enum, you may specify the raw padding scheme name string that will be recognized by your JCA provider via the
107  * {@link #setPaddingScheme paddingSchemeName} attribute.  Because this is not type-safe, it is recommended only to
108  * use this attribute if the {@link PaddingScheme} enum does not represent your desired scheme.
109  *
110  * <h2>Streaming</h2>
111  * Most people don't think of using block ciphers as stream ciphers, since their name implies working
112  * with block data (i.e. byte arrays) only.  However, block ciphers can be turned into byte-oriented stream ciphers by
113  * using an appropriate {@link OperationMode operation mode} with a {@link #getStreamingBlockSize() streaming block size}
114  * of 8 bits.  This is why the {@link CipherService} interface provides both block and streaming operations.
115  * <p/>
116  * Because this streaming 8-bit block size rarely changes across block-cipher algorithms, default values have been set
117  * for all three streaming configuration parameters.  The defaults are:
118  * <ul>
119  * <li>{@link #setStreamingBlockSize(int) streamingBlockSize} = {@code 8} (bits)</li>
120  * <li>{@link #setStreamingMode streamingMode} = {@link OperationMode#CBC CBC}</li>
121  * <li>{@link #setStreamingPaddingScheme(PaddingScheme) streamingPaddingScheme} = {@link PaddingScheme#PKCS5 PKCS5}</li>
122  * </ul>
123  * <p/>
124  * These attributes have the same meaning as the {@code mode}, {@code blockSize}, and {@code paddingScheme} attributes
125  * described above, but they are applied during streaming method invocations only
126  * ({@link #encrypt(java.io.InputStream, java.io.OutputStream, byte[])}
127  * and {@link #decrypt(java.io.InputStream, java.io.OutputStream, byte[])}).
128  *
129  * @see BlowfishCipherService
130  * @see AesCipherService
131  * @see <a href="http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation">Wikipedia: Block Cipher Modes of Operation</a>
132  * @since 1.0
133  */
134 public class DefaultBlockCipherService extends AbstractSymmetricCipherService {
135 
136     private static final int DEFAULT_BLOCK_SIZE = 0;
137 
138     private static final String TRANSFORMATION_STRING_DELIMITER = "/";
139     //8 bits (1 byte)
140     private static final int DEFAULT_STREAMING_BLOCK_SIZE = 8;
141 
142     private String modeName;
143 
144     /**
145      * size in bits (not bytes) - i.e. a blockSize of 8 equals 1 byte. negative or zero value = use system default
146      */
147     private int blockSize;
148     private String paddingSchemeName;
149 
150     private String streamingModeName;
151     private int streamingBlockSize;
152     private String streamingPaddingSchemeName;
153 
154     /**
155      * cached value - rebuilt whenever any of its constituent parts change.
156      */
157     private String transformationString;
158 
159     /**
160      * cached value - rebuilt whenever any of its constituent parts change.
161      */
162     private String streamingTransformationString;
163 
164 
165     /**
166      * Creates a new {@link DefaultBlockCipherService} using the specified block cipher {@code algorithmName}.  Per this
167      * class's JavaDoc, this constructor also sets the following defaults:
168      * <ul>
169      * <li>{@code streamingMode} = {@link OperationMode#CBC CBC}</li>
170      * <li>{@code streamingPaddingScheme} = {@link PaddingScheme#NONE none}</li>
171      * <li>{@code streamingBlockSize} = 8</li>
172      * </ul>
173      * All other attributes are null/unset, indicating the JCA Provider defaults will be used.
174      *
175      * @param algorithmName the block cipher algorithm to use when encrypting and decrypting
176      */
177     public DefaultBlockCipherService(String algorithmName) {
178         super(algorithmName);
179 
180         this.modeName = OperationMode.CBC.name();
181         this.paddingSchemeName = PaddingScheme.PKCS5.getTransformationName();
182         //0 = use the JCA provider's default
183         this.blockSize = DEFAULT_BLOCK_SIZE;
184 
185         this.streamingModeName = OperationMode.CBC.name();
186         this.streamingPaddingSchemeName = PaddingScheme.PKCS5.getTransformationName();
187         this.streamingBlockSize = DEFAULT_STREAMING_BLOCK_SIZE;
188     }
189 
190     /**
191      * Returns the cipher operation mode name (as a String) to be used when constructing
192      * {@link javax.crypto.Cipher Cipher} transformation string or {@code null} if the JCA Provider default mode for
193      * the specified {@link #getAlgorithmName() algorithm} should be used.
194      * <p/>
195      * This attribute is used <em>only</em> when constructing the transformation string for block (byte array)
196      * operations ({@link #encrypt(byte[], byte[])} and {@link #decrypt(byte[], byte[])}).  The
197      * {@link #getStreamingModeName() streamingModeName} attribute is used when the block cipher is used for
198      * streaming operations.
199      * <p/>
200      * The default value is {@code null} to retain the JCA Provider default.
201      *
202      * @return the cipher operation mode name (as a String) to be used when constructing the
203      * {@link javax.crypto.Cipher Cipher} transformation string, or {@code null} if the JCA Provider default
204      * mode for the specified {@link #getAlgorithmName() algorithm} should be used.
205      */
206     public String getModeName() {
207         return modeName;
208     }
209 
210     /**
211      * Sets the cipher operation mode name to be used when constructing the
212      * {@link javax.crypto.Cipher Cipher} transformation string.  A {@code null} value indicates that the JCA Provider
213      * default mode for the specified {@link #getAlgorithmName() algorithm} should be used.
214      * <p/>
215      * This attribute is used <em>only</em> when constructing the transformation string for block (byte array)
216      * operations ({@link #encrypt(byte[], byte[])} and {@link #decrypt(byte[], byte[])}).  The
217      * {@link #getStreamingModeName() streamingModeName} attribute is used when the block cipher is used for
218      * streaming operations.
219      * <p/>
220      * The default value is {@code null} to retain the JCA Provider default.
221      * <p/>
222      * <b>NOTE:</b> most standard mode names are represented by the {@link OperationMode OperationMode} enum.  That enum
223      * should be used with the {@link #setMode mode} attribute when possible to retain type-safety and reduce the
224      * possibility of errors.  This method is better used if the {@link OperationMode} enum does not represent the
225      * necessary mode.
226      *
227      * @param modeName the cipher operation mode name to be used when constructing
228      *                 {@link javax.crypto.Cipher Cipher} transformation string, or {@code null} if the JCA Provider
229      *                 default mode for the specified {@link #getAlgorithmName() algorithm} should be used.
230      * @see #setMode
231      */
232     public void setModeName(String modeName) {
233         this.modeName = modeName;
234         //clear out the transformation string so the next invocation will rebuild it with the new mode:
235         this.transformationString = null;
236     }
237 
238     /**
239      * Sets the cipher operation mode of operation to be used when constructing the
240      * {@link javax.crypto.Cipher Cipher} transformation string.  A {@code null} value indicates that the JCA Provider
241      * default mode for the specified {@link #getAlgorithmName() algorithm} should be used.
242      * <p/>
243      * This attribute is used <em>only</em> when constructing the transformation string for block (byte array)
244      * operations ({@link #encrypt(byte[], byte[])} and {@link #decrypt(byte[], byte[])}).  The
245      * {@link #setStreamingMode streamingMode} attribute is used when the block cipher is used for
246      * streaming operations.
247      * <p/>
248      * If the {@link OperationMode} enum cannot represent your desired mode, you can set the name explicitly
249      * via the {@link #setModeName modeName} attribute directly.  However, because {@link OperationMode} represents all
250      * standard JDK mode names already, ensure that your underlying JCA Provider supports the non-standard name first.
251      *
252      * @param mode the cipher operation mode to be used when constructing
253      *             {@link javax.crypto.Cipher Cipher} transformation string, or {@code null} if the JCA Provider
254      *             default mode for the specified {@link #getAlgorithmName() algorithm} should be used.
255      */
256     public void setMode(OperationMode mode) {
257         setModeName(mode.name());
258     }
259 
260     /**
261      * Returns the cipher algorithm padding scheme name (as a String) to be used when constructing
262      * {@link javax.crypto.Cipher Cipher} transformation string or {@code null} if the JCA Provider default mode for
263      * the specified {@link #getAlgorithmName() algorithm} should be used.
264      * <p/>
265      * This attribute is used <em>only</em> when constructing the transformation string for block (byte array)
266      * operations ({@link #encrypt(byte[], byte[])} and {@link #decrypt(byte[], byte[])}).  The
267      * {@link #getStreamingPaddingSchemeName() streamingPaddingSchemeName} attribute is used when the block cipher is
268      * used for streaming operations.
269      * <p/>
270      * The default value is {@code null} to retain the JCA Provider default.
271      *
272      * @return the padding scheme name (as a String) to be used when constructing the
273      * {@link javax.crypto.Cipher Cipher} transformation string, or {@code null} if the JCA Provider default
274      * padding scheme for the specified {@link #getAlgorithmName() algorithm} should be used.
275      */
276     public String getPaddingSchemeName() {
277         return paddingSchemeName;
278     }
279 
280     /**
281      * Sets the padding scheme name to be used when constructing the
282      * {@link javax.crypto.Cipher Cipher} transformation string, or {@code null} if the JCA Provider default mode for
283      * the specified {@link #getAlgorithmName() algorithm} should be used.
284      * <p/>
285      * This attribute is used <em>only</em> when constructing the transformation string for block (byte array)
286      * operations ({@link #encrypt(byte[], byte[])} and {@link #decrypt(byte[], byte[])}).  The
287      * {@link #getStreamingPaddingSchemeName() streamingPaddingSchemeName} attribute is used when the block cipher is
288      * used for streaming operations.
289      * <p/>
290      * The default value is {@code null} to retain the JCA Provider default.
291      * <p/>
292      * <b>NOTE:</b> most standard padding schemes are represented by the {@link PaddingScheme PaddingScheme} enum.
293      * That enum should be used with the {@link #setPaddingScheme paddingScheme} attribute when possible to retain
294      * type-safety and reduce the possibility of errors.  Calling this method however is suitable if the
295      * {@code PaddingScheme} enum does not represent the desired scheme.
296      *
297      * @param paddingSchemeName the padding scheme name to be used when constructing
298      *                          {@link javax.crypto.Cipher Cipher} transformation string, or {@code null} if the JCA
299      *                          Provider default padding scheme for the specified {@link #getAlgorithmName() algorithm}
300      *                          should be used.
301      * @see #setPaddingScheme
302      */
303     public void setPaddingSchemeName(String paddingSchemeName) {
304         this.paddingSchemeName = paddingSchemeName;
305         //clear out the transformation string so the next invocation will rebuild it with the new padding scheme:
306         this.transformationString = null;
307     }
308 
309     /**
310      * Sets the padding scheme to be used when constructing the
311      * {@link javax.crypto.Cipher Cipher} transformation string. A {@code null} value indicates that the JCA Provider
312      * default padding scheme for the specified {@link #getAlgorithmName() algorithm} should be used.
313      * <p/>
314      * This attribute is used <em>only</em> when constructing the transformation string for block (byte array)
315      * operations ({@link #encrypt(byte[], byte[])} and {@link #decrypt(byte[], byte[])}).  The
316      * {@link #setStreamingPaddingScheme streamingPaddingScheme} attribute is used when the block cipher is used for
317      * streaming operations.
318      * <p/>
319      * If the {@link PaddingScheme PaddingScheme} enum does represent your desired scheme, you can set the name explicitly
320      * via the {@link #setPaddingSchemeName paddingSchemeName} attribute directly.  However, because
321      * {@code PaddingScheme} represents all standard JDK scheme names already, ensure that your underlying JCA Provider
322      * supports the non-standard name first.
323      *
324      * @param paddingScheme the padding scheme to be used when constructing
325      *                      {@link javax.crypto.Cipher Cipher} transformation string, or {@code null} if the JCA Provider
326      *                      default padding scheme for the specified {@link #getAlgorithmName() algorithm} should be used.
327      */
328     public void setPaddingScheme(PaddingScheme paddingScheme) {
329         setPaddingSchemeName(paddingScheme.getTransformationName());
330     }
331 
332     /**
333      * Returns the block cipher's block size to be used when constructing
334      * {@link javax.crypto.Cipher Cipher} transformation string or {@code 0} if the JCA Provider default block size
335      * for the specified {@link #getAlgorithmName() algorithm} should be used.
336      * <p/>
337      * This attribute is used <em>only</em> when constructing the transformation string for block (byte array)
338      * operations ({@link #encrypt(byte[], byte[])} and {@link #decrypt(byte[], byte[])}).  The
339      * {@link #getStreamingBlockSize() streamingBlockSize} attribute is used when the block cipher is used for
340      * streaming operations.
341      * <p/>
342      * The default value is {@code 0} which retains the JCA Provider default.
343      *
344      * @return the block cipher block size to be used when constructing the
345      * {@link javax.crypto.Cipher Cipher} transformation string, or {@code 0} if the JCA Provider default
346      * block size for the specified {@link #getAlgorithmName() algorithm} should be used.
347      */
348     public int getBlockSize() {
349         return blockSize;
350     }
351 
352     /**
353      * Sets the block cipher's block size to be used when constructing
354      * {@link javax.crypto.Cipher Cipher} transformation string.  {@code 0} indicates that the JCA Provider default
355      * block size for the specified {@link #getAlgorithmName() algorithm} should be used.
356      * <p/>
357      * This attribute is used <em>only</em> when constructing the transformation string for block (byte array)
358      * operations ({@link #encrypt(byte[], byte[])} and {@link #decrypt(byte[], byte[])}).  The
359      * {@link #getStreamingBlockSize() streamingBlockSize} attribute is used when the block cipher is used for
360      * streaming operations.
361      * <p/>
362      * The default value is {@code 0} which retains the JCA Provider default.
363      * <p/>
364      * <b>NOTE:</b> block cipher block sizes are very algorithm-specific.  If you change this value, ensure that it
365      * will work with the specified {@link #getAlgorithmName() algorithm}.
366      *
367      * @param blockSize the block cipher block size to be used when constructing the
368      *                  {@link javax.crypto.Cipher Cipher} transformation string, or {@code 0} if the JCA Provider
369      *                  default block size for the specified {@link #getAlgorithmName() algorithm} should be used.
370      */
371     public void setBlockSize(int blockSize) {
372         this.blockSize = Math.max(DEFAULT_BLOCK_SIZE, blockSize);
373         //clear out the transformation string so the next invocation will rebuild it with the new block size:
374         this.transformationString = null;
375     }
376 
377     /**
378      * Same purpose as the {@link #getModeName modeName} attribute, but is used instead only for for streaming
379      * operations ({@link #encrypt(java.io.InputStream, java.io.OutputStream, byte[])} and
380      * {@link #decrypt(java.io.InputStream, java.io.OutputStream, byte[])}).
381      * <p/>
382      * Note that unlike the {@link #getModeName modeName} attribute, the default value of this attribute is not
383      * {@code null} - it is {@link OperationMode#CBC CBC} for reasons described in the class-level JavaDoc in the
384      * {@code Streaming} section.
385      *
386      * @return the transformation string mode name to be used for streaming operations only.
387      */
388     public String getStreamingModeName() {
389         return streamingModeName;
390     }
391 
392     private boolean isModeStreamingCompatible(String modeName) {
393         return modeName != null
394                 && !modeName.equalsIgnoreCase(OperationMode.ECB.name())
395                 && !modeName.equalsIgnoreCase(OperationMode.NONE.name());
396     }
397 
398     /**
399      * Sets the transformation string mode name to be used for streaming operations only.  The default value is
400      * {@link OperationMode#CBC CBC} for reasons described in the class-level JavaDoc in the {@code Streaming} section.
401      *
402      * @param streamingModeName transformation string mode name to be used for streaming operations only
403      */
404     public void setStreamingModeName(String streamingModeName) {
405         if (!isModeStreamingCompatible(streamingModeName)) {
406             String msg = "mode [" + streamingModeName + "] is not a valid operation mode for block cipher streaming.";
407             throw new IllegalArgumentException(msg);
408         }
409         this.streamingModeName = streamingModeName;
410         //clear out the streaming transformation string so the next invocation will rebuild it with the new mode:
411         this.streamingTransformationString = null;
412     }
413 
414     /**
415      * Sets the transformation string mode to be used for streaming operations only.  The default value is
416      * {@link OperationMode#CBC CBC} for reasons described in the class-level JavaDoc in the {@code Streaming} section.
417      *
418      * @param mode the transformation string mode to be used for streaming operations only
419      */
420     public void setStreamingMode(OperationMode mode) {
421         setStreamingModeName(mode.name());
422     }
423 
424     public String getStreamingPaddingSchemeName() {
425         return streamingPaddingSchemeName;
426     }
427 
428     public void setStreamingPaddingSchemeName(String streamingPaddingSchemeName) {
429         this.streamingPaddingSchemeName = streamingPaddingSchemeName;
430         //clear out the streaming transformation string so the next invocation will rebuild it with the new scheme:
431         this.streamingTransformationString = null;
432     }
433 
434     public void setStreamingPaddingScheme(PaddingScheme scheme) {
435         setStreamingPaddingSchemeName(scheme.getTransformationName());
436     }
437 
438     public int getStreamingBlockSize() {
439         return streamingBlockSize;
440     }
441 
442     public void setStreamingBlockSize(int streamingBlockSize) {
443         this.streamingBlockSize = Math.max(DEFAULT_BLOCK_SIZE, streamingBlockSize);
444         //clear out the streaming transformation string so the next invocation will rebuild it with the new block size:
445         this.streamingTransformationString = null;
446     }
447 
448     /**
449      * Returns the transformation string to use with the {@link javax.crypto.Cipher#getInstance} call.  If
450      * {@code streaming} is {@code true}, a block-cipher transformation string compatible with streaming operations will
451      * be constructed and cached for re-use later (see the class-level JavaDoc for more on using block ciphers
452      * for streaming).  If {@code streaming} is {@code false} a normal block-cipher transformation string will
453      * be constructed and cached for later re-use.
454      *
455      * @param streaming if the transformation string is going to be used for a Cipher performing stream-based encryption or not.
456      * @return the transformation string
457      */
458     protected String getTransformationString(boolean streaming) {
459         if (streaming) {
460             if (this.streamingTransformationString == null) {
461                 this.streamingTransformationString = buildStreamingTransformationString();
462             }
463             return this.streamingTransformationString;
464         } else {
465             if (this.transformationString == null) {
466                 this.transformationString = buildTransformationString();
467             }
468             return this.transformationString;
469         }
470     }
471 
472     private String buildTransformationString() {
473         return buildTransformationString(getModeName(), getPaddingSchemeName(), getBlockSize());
474     }
475 
476     private String buildStreamingTransformationString() {
477         return buildTransformationString(getStreamingModeName(), getStreamingPaddingSchemeName(), 0);
478     }
479 
480     private String buildTransformationString(String modeName, String paddingSchemeName, int blockSize) {
481         StringBuilder sb = new StringBuilder(getAlgorithmName());
482         if (StringUtils.hasText(modeName)) {
483             sb.append(TRANSFORMATION_STRING_DELIMITER).append(modeName);
484         }
485         if (blockSize > 0) {
486             sb.append(blockSize);
487         }
488         if (StringUtils.hasText(paddingSchemeName)) {
489             sb.append(TRANSFORMATION_STRING_DELIMITER).append(paddingSchemeName);
490         }
491         return sb.toString();
492     }
493 
494     /**
495      * Returns {@code true} if the specified cipher operation mode name supports initialization vectors,
496      * {@code false} otherwise.
497      *
498      * @param modeName the raw text name of the mode of operation
499      * @return {@code true} if the specified cipher operation mode name supports initialization vectors,
500      * {@code false} otherwise.
501      */
502     private boolean isModeInitializationVectorCompatible(String modeName) {
503         return modeName != null
504                 && !modeName.equalsIgnoreCase(OperationMode.ECB.name())
505                 && !modeName.equalsIgnoreCase(OperationMode.NONE.name());
506     }
507 
508     /**
509      * Overrides the parent implementation to ensure initialization vectors are always generated if streaming is
510      * enabled (block ciphers <em>must</em> use initialization vectors if they are to be used as a stream cipher).  If
511      * not being used as a stream cipher, then the value is computed based on whether or not the currently configured
512      * {@link #getModeName modeName} is compatible with initialization vectors as well as the result of the configured
513      * {@link #setGenerateInitializationVectors(boolean) generateInitializationVectors} value.
514      *
515      * @param streaming whether or not streaming is being performed
516      * @return {@code true} if streaming or a value computed based on if the currently configured mode is compatible
517      * with initialization vectors.
518      */
519     @Override
520     protected boolean isGenerateInitializationVectors(boolean streaming) {
521         return streaming || super.isGenerateInitializationVectors() && isModeInitializationVectorCompatible(getModeName());
522     }
523 
524     @Override
525     protected byte[] generateInitializationVector(boolean streaming) {
526         if (streaming) {
527             String streamingModeName = getStreamingModeName();
528             if (!isModeInitializationVectorCompatible(streamingModeName)) {
529                 String msg = "streamingMode attribute value [" + streamingModeName + "] does not support "
530                         + "Initialization Vectors.  Ensure the streamingMode value represents an operation mode "
531                         + "that is compatible with initialization vectors.";
532                 throw new IllegalStateException(msg);
533             }
534         } else {
535             String modeName = getModeName();
536             if (!isModeInitializationVectorCompatible(modeName)) {
537                 String msg = "mode attribute value [" + modeName + "] does not support "
538                         + "Initialization Vectors.  Ensure the mode value represents an operation mode "
539                         + "that is compatible with initialization vectors.";
540                 throw new IllegalStateException(msg);
541             }
542         }
543         return super.generateInitializationVector(streaming);
544     }
545 }