001    /*
002     * Licensed to the Apache Software Foundation (ASF) under one
003     * or more contributor license agreements.  See the NOTICE file
004     * distributed with this work for additional information
005     * regarding copyright ownership.  The ASF licenses this file
006     * to you under the Apache License, Version 2.0 (the
007     * "License"); you may not use this file except in compliance
008     * with the License.  You may obtain a copy of the License at
009     *
010     *     http://www.apache.org/licenses/LICENSE-2.0
011     *
012     * Unless required by applicable law or agreed to in writing,
013     * software distributed under the License is distributed on an
014     * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015     * KIND, either express or implied.  See the License for the
016     * specific language governing permissions and limitations
017     * under the License.
018     */
019    package org.apache.shiro.crypto;
020    
021    import org.apache.shiro.util.StringUtils;
022    
023    /**
024     * Base abstract class for block cipher algorithms.
025     *
026     * <h2>Usage</h2>
027     * Note that this class exists mostly to simplify algorithm-specific subclasses.  Unless you understand the concepts of
028     * cipher modes of operation, block sizes, and padding schemes, and you want direct control of these things, you should
029     * typically not uses instances of this class directly.  Instead, algorithm-specific subclasses, such as
030     * {@link AesCipherService}, {@link BlowfishCipherService}, and others are usually better suited for regular use.
031     * <p/>
032     * However, if you have the need to create a custom block cipher service where no sufficient algorithm-specific subclass
033     * exists in Shiro, this class would be very useful.
034     *
035     * <h2>Configuration</h2>
036     * Block ciphers can accept configuration parameters that direct how they operate.  These parameters concatenated
037     * together in a single String comprise what the JDK JCA documentation calls a
038     * <a href="http://java.sun.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html#trans">transformation
039     * string</a>.  We think that it is better for Shiro to construct this transformation string automatically based on its
040     * constituent parts instead of having the end-user construct the string manually, which may be error prone or
041     * confusing.  To that end, Shiro {@link DefaultBlockCipherService}s have attributes that can be set individually in
042     * a type-safe manner based on your configuration needs, and Shiro will build the transformation string for you.
043     * <p/>
044     * The following sections typically document the configuration options for block (byte array)
045     * {@link #encrypt(byte[], byte[])} and {@link #decrypt(byte[], byte[])} method invocations.  Streaming configuration
046     * for those same attributes are done via mirrored {@code streaming}* attributes, and their purpose is identical, but
047     * they're only used during streaming {@link #encrypt(java.io.InputStream, java.io.OutputStream, byte[])} and
048     * {@link #decrypt(java.io.InputStream, java.io.OutputStream, byte[])} methods.  See the &quot;Streaming&quot;
049     * section below for more.
050     *
051     * <h3>Block Size</h3>
052     * The block size specifies the number of bits (not bytes) that the cipher operates on when performing an operation.
053     * It can be specified explicitly via the {@link #setBlockSize blockSize} attribute.  If not set, the JCA Provider
054     * default will be used based on the cipher algorithm.  Block sizes are usually very algorithm specific, so set this
055     * value only if you know you don't want the JCA Provider's default for the desired algorithm.  For example, the
056     * AES algorithm's Rijndael implementation <em>only</em> supports a 128 bit block size and will not work with any other
057     * size.
058     * <p/>
059     * Also note that the {@link #setInitializationVectorSize initializationVectorSize} is usually the same as the
060     * {@link #setBlockSize blockSize} in block ciphers.  If you change either attribute, you should ensure that the other
061     * attribute is correct for the target cipher algorithm.
062     *
063     * <h3>Operation Mode</h3>
064     * You may set the block cipher's<a href="http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation">mode of
065     * operation</a> via the {@link #setMode(OperationMode) mode} attribute, which accepts a type-safe
066     * {@link OperationMode OperationMode} enum instance.  This type safety helps avoid typos when specifying the mode and
067     * guarantees that the mode name will be recognized by the underlying JCA Provider.
068     * <p/>
069     * <b>*</b>If no operation mode is specified, Shiro defaults all of its block {@code CipherService} instances to the
070     * {@link OperationMode#CFB CFB} mode, specifically to support auto-generation of initialization vectors during
071     * encryption.  This is different than the JDK's default {@link OperationMode#ECB ECB} mode because {@code ECB} does
072     * not support initialization vectors, which are necessary for strong encryption.  See  the
073     * {@link org.apache.shiro.crypto.JcaCipherService JcaCipherService parent class} class JavaDoc for an extensive
074     * explanation on why we do this and why we do not use the Sun {@code ECB} default.  You also might also want read
075     * the <a href="http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29">Wikipedia
076     * section on ECB<a/> and look at the encrypted image to see an example of why {@code ECB} should not be used in
077     * security-sensitive environments.
078     * <p/>
079     * In the rare case that you need to override the default with a mode not represented
080     * by the {@link OperationMode} enum, you may specify the raw mode name string that will be recognized by your JCA
081     * provider via the {@link #setModeName modeName} attribute.  Because this is not type-safe, it is recommended only to
082     * use this attribute if the {@link OperationMode} enum does not represent your desired mode.
083     * <p/>
084     * <b>NOTE:</b> If you change the mode to one that does not support initialization vectors (such as
085     * {@link OperationMode#ECB ECB} or {@link OperationMode#NONE NONE}), you <em>must</em> turn off auto-generated
086     * initialization vectors by setting {@link #setGenerateInitializationVectors(boolean) generateInitializationVectors}
087     * to {@code false}.  Abandoning initialization vectors significantly weakens encryption, so think twice before
088     * disabling this feature.
089     *
090     * <h3>Padding Scheme</h3>
091     * Because block ciphers process messages in fixed-length blocks, if the final block in a message is not equal to the
092     * block length, <a href="http://en.wikipedia.org/wiki/Padding_(cryptography)">padding</a> is applied to match that
093     * size to maintain the total length of the message.  This is good because it protects data patterns from being
094     * identified  - when all chunks look the same length, it is much harder to infer what that data might be.
095     * <p/>
096     * You may set a padding scheme via the {@link #setPaddingScheme(PaddingScheme) paddingScheme} attribute, which
097     * accepts a type-safe {@link PaddingScheme PaddingScheme} enum instance.  Like the {@link OperationMode} enum,
098     * this enum offers type safety to help avoid typos and guarantees that the mode will be recongized by the underlying
099     * 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 org.apache.shiro.crypto.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#CFB CFB}</li>
121     * <li>{@link #setStreamingPaddingScheme(PaddingScheme) streamingPaddingScheme} = {@link PaddingScheme#NONE none} (since
122     * the block size is already the most atomic size of a single byte)</li>
123     * </ul>
124     * <p/>
125     * These attributes have the same meaning as the {@code mode}, {@code blockSize}, and {@code paddingScheme} attributes
126     * described above, but they are applied during streaming method invocations only ({@link #encrypt(java.io.InputStream, java.io.OutputStream, byte[])}
127     * and {@link #decrypt(java.io.InputStream, java.io.OutputStream, byte[])}).
128     *
129     * @author Les Hazlewood
130     * @see BlowfishCipherService
131     * @see AesCipherService
132     * @see <a href="http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation">Wikipedia: Block Cipher Modes of Operation</a>
133     * @since 1.0
134     */
135    public class DefaultBlockCipherService extends AbstractSymmetricCipherService {
136    
137        private static final int DEFAULT_BLOCK_SIZE = 0;
138    
139        private static final String TRANSFORMATION_STRING_DELIMITER = "/";
140        private static final int DEFAULT_STREAMING_BLOCK_SIZE = 8; //8 bits (1 byte)
141    
142        private String modeName;
143        private int blockSize; //size in bits (not bytes) - i.e. a blockSize of 8 equals 1 byte. negative or zero value = use system default
144        private String paddingSchemeName;
145    
146        private String streamingModeName;
147        private int streamingBlockSize;
148        private String streamingPaddingSchemeName;
149    
150        private String transformationString; //cached value - rebuilt whenever any of its constituent parts change
151        private String streamingTransformationString; //cached value - rebuilt whenever any of its constituent parts change
152    
153    
154        /**
155         * Creates a new {@link DefaultBlockCipherService} using the specified block cipher {@code algorithmName}.  Per this
156         * class's JavaDoc, this constructor also sets the following defaults:
157         * <ul>
158         * <li>{@code streamingMode} = {@link OperationMode#CFB CFB}</li>
159         * <li>{@code streamingPaddingScheme} = {@link PaddingScheme#NONE none}</li>
160         * <li>{@code streamingBlockSize} = 8</li>
161         * </ul>
162         * All other attributes are null/unset, indicating the JCA Provider defaults will be used.
163         *
164         * @param algorithmName the block cipher algorithm to use when encrypting and decrypting
165         */
166        public DefaultBlockCipherService(String algorithmName) {
167            super(algorithmName);
168    
169            this.modeName = OperationMode.CFB.name();
170            this.paddingSchemeName = PaddingScheme.PKCS5.getTransformationName();
171            this.blockSize = DEFAULT_BLOCK_SIZE; //0 = use the JCA provider's default
172    
173            this.streamingModeName = OperationMode.CFB.name();
174            this.streamingPaddingSchemeName = PaddingScheme.NONE.getTransformationName();
175            this.streamingBlockSize = DEFAULT_STREAMING_BLOCK_SIZE;
176        }
177    
178        /**
179         * Returns the cipher operation mode name (as a String) to be used when constructing
180         * {@link javax.crypto.Cipher Cipher} transformation string or {@code null} if the JCA Provider default mode for
181         * the specified {@link #getAlgorithmName() algorithm} should be used.
182         * <p/>
183         * This attribute is used <em>only</em> when constructing the transformation string for block (byte array)
184         * operations ({@link #encrypt(byte[], byte[])} and {@link #decrypt(byte[], byte[])}).  The
185         * {@link #getStreamingModeName() streamingModeName} attribute is used when the block cipher is used for
186         * streaming operations.
187         * <p/>
188         * The default value is {@code null} to retain the JCA Provider default.
189         *
190         * @return the cipher operation mode name (as a String) to be used when constructing the
191         *         {@link javax.crypto.Cipher Cipher} transformation string, or {@code null} if the JCA Provider default
192         *         mode for the specified {@link #getAlgorithmName() algorithm} should be used.
193         */
194        public String getModeName() {
195            return modeName;
196        }
197    
198        /**
199         * Sets the cipher operation mode name to be used when constructing the
200         * {@link javax.crypto.Cipher Cipher} transformation string.  A {@code null} value indicates that the JCA Provider
201         * default mode for the specified {@link #getAlgorithmName() algorithm} should be used.
202         * <p/>
203         * This attribute is used <em>only</em> when constructing the transformation string for block (byte array)
204         * operations ({@link #encrypt(byte[], byte[])} and {@link #decrypt(byte[], byte[])}).  The
205         * {@link #getStreamingModeName() streamingModeName} attribute is used when the block cipher is used for
206         * streaming operations.
207         * <p/>
208         * The default value is {@code null} to retain the JCA Provider default.
209         * <p/>
210         * <b>NOTE:</b> most standard mode names are represented by the {@link OperationMode OperationMode} enum.  That enum
211         * should be used with the {@link #setMode mode} attribute when possible to retain type-safety and reduce the
212         * possibility of errors.  This method is better used if the {@link OperationMode} enum does not represent the
213         * necessary mode.
214         *
215         * @param modeName the cipher operation mode name to be used when constructing
216         *                 {@link javax.crypto.Cipher Cipher} transformation string, or {@code null} if the JCA Provider
217         *                 default mode for the specified {@link #getAlgorithmName() algorithm} should be used.
218         * @see #setMode
219         */
220        public void setModeName(String modeName) {
221            this.modeName = modeName;
222            //clear out the transformation string so the next invocation will rebuild it with the new mode:
223            this.transformationString = null;
224        }
225    
226        /**
227         * Sets the cipher operation mode of operation to be used when constructing the
228         * {@link javax.crypto.Cipher Cipher} transformation string.  A {@code null} value indicates that the JCA Provider
229         * default mode for the specified {@link #getAlgorithmName() algorithm} should be used.
230         * <p/>
231         * This attribute is used <em>only</em> when constructing the transformation string for block (byte array)
232         * operations ({@link #encrypt(byte[], byte[])} and {@link #decrypt(byte[], byte[])}).  The
233         * {@link #setStreamingMode streamingMode} attribute is used when the block cipher is used for
234         * streaming operations.
235         * <p/>
236         * If the {@link OperationMode} enum cannot represent your desired mode, you can set the name explicitly
237         * via the {@link #setModeName modeName} attribute directly.  However, because {@link OperationMode} represents all
238         * standard JDK mode names already, ensure that your underlying JCA Provider supports the non-standard name first.
239         *
240         * @param mode the cipher operation mode to be used when constructing
241         *             {@link javax.crypto.Cipher Cipher} transformation string, or {@code null} if the JCA Provider
242         *             default mode for the specified {@link #getAlgorithmName() algorithm} should be used.
243         */
244        public void setMode(OperationMode mode) {
245            setModeName(mode.name());
246        }
247    
248        /**
249         * Returns the cipher algorithm padding scheme name (as a String) to be used when constructing
250         * {@link javax.crypto.Cipher Cipher} transformation string or {@code null} if the JCA Provider default mode for
251         * the specified {@link #getAlgorithmName() algorithm} should be used.
252         * <p/>
253         * This attribute is used <em>only</em> when constructing the transformation string for block (byte array)
254         * operations ({@link #encrypt(byte[], byte[])} and {@link #decrypt(byte[], byte[])}).  The
255         * {@link #getStreamingPaddingSchemeName() streamingPaddingSchemeName} attribute is used when the block cipher is
256         * used for streaming operations.
257         * <p/>
258         * The default value is {@code null} to retain the JCA Provider default.
259         *
260         * @return the padding scheme name (as a String) to be used when constructing the
261         *         {@link javax.crypto.Cipher Cipher} transformation string, or {@code null} if the JCA Provider default
262         *         padding scheme for the specified {@link #getAlgorithmName() algorithm} should be used.
263         */
264        public String getPaddingSchemeName() {
265            return paddingSchemeName;
266        }
267    
268        /**
269         * Sets the padding scheme name to be used when constructing the
270         * {@link javax.crypto.Cipher Cipher} transformation string, or {@code null} if the JCA Provider default mode for
271         * the specified {@link #getAlgorithmName() algorithm} should be used.
272         * <p/>
273         * This attribute is used <em>only</em> when constructing the transformation string for block (byte array)
274         * operations ({@link #encrypt(byte[], byte[])} and {@link #decrypt(byte[], byte[])}).  The
275         * {@link #getStreamingPaddingSchemeName() streamingPaddingSchemeName} attribute is used when the block cipher is
276         * used for streaming operations.
277         * <p/>
278         * The default value is {@code null} to retain the JCA Provider default.
279         * <p/>
280         * <b>NOTE:</b> most standard padding schemes are represented by the {@link PaddingScheme PaddingScheme} enum.
281         * That enum should be used with the {@link #setPaddingScheme paddingScheme} attribute when possible to retain
282         * type-safety and reduce the possibility of errors.  Calling this method however is suitable if the
283         * {@code PaddingScheme} enum does not represent the desired scheme.
284         *
285         * @param paddingSchemeName the padding scheme name to be used when constructing
286         *                          {@link javax.crypto.Cipher Cipher} transformation string, or {@code null} if the JCA
287         *                          Provider default padding scheme for the specified {@link #getAlgorithmName() algorithm}
288         *                          should be used.
289         * @see #setPaddingScheme
290         */
291        public void setPaddingSchemeName(String paddingSchemeName) {
292            this.paddingSchemeName = paddingSchemeName;
293            //clear out the transformation string so the next invocation will rebuild it with the new padding scheme:
294            this.transformationString = null;
295        }
296    
297        /**
298         * Sets the padding scheme to be used when constructing the
299         * {@link javax.crypto.Cipher Cipher} transformation string. A {@code null} value indicates that the JCA Provider
300         * default padding scheme for the specified {@link #getAlgorithmName() algorithm} should be used.
301         * <p/>
302         * This attribute is used <em>only</em> when constructing the transformation string for block (byte array)
303         * operations ({@link #encrypt(byte[], byte[])} and {@link #decrypt(byte[], byte[])}).  The
304         * {@link #setStreamingPaddingScheme streamingPaddingScheme} attribute is used when the block cipher is used for
305         * streaming operations.
306         * <p/>
307         * If the {@link PaddingScheme PaddingScheme} enum does represent your desired scheme, you can set the name explicitly
308         * via the {@link #setPaddingSchemeName paddingSchemeName} attribute directly.  However, because
309         * {@code PaddingScheme} represents all standard JDK scheme names already, ensure that your underlying JCA Provider
310         * supports the non-standard name first.
311         *
312         * @param paddingScheme the padding scheme to be used when constructing
313         *                      {@link javax.crypto.Cipher Cipher} transformation string, or {@code null} if the JCA Provider
314         *                      default padding scheme for the specified {@link #getAlgorithmName() algorithm} should be used.
315         */
316        public void setPaddingScheme(PaddingScheme paddingScheme) {
317            setPaddingSchemeName(paddingScheme.getTransformationName());
318        }
319    
320        /**
321         * Returns the block cipher's block size to be used when constructing
322         * {@link javax.crypto.Cipher Cipher} transformation string or {@code 0} if the JCA Provider default block size
323         * for the specified {@link #getAlgorithmName() algorithm} should be used.
324         * <p/>
325         * This attribute is used <em>only</em> when constructing the transformation string for block (byte array)
326         * operations ({@link #encrypt(byte[], byte[])} and {@link #decrypt(byte[], byte[])}).  The
327         * {@link #getStreamingBlockSize() streamingBlockSize} attribute is used when the block cipher is used for
328         * streaming operations.
329         * <p/>
330         * The default value is {@code 0} which retains the JCA Provider default.
331         *
332         * @return the block cipher block size to be used when constructing the
333         *         {@link javax.crypto.Cipher Cipher} transformation string, or {@code 0} if the JCA Provider default
334         *         block size for the specified {@link #getAlgorithmName() algorithm} should be used.
335         */
336        public int getBlockSize() {
337            return blockSize;
338        }
339    
340        /**
341         * Sets the block cipher's block size to be used when constructing
342         * {@link javax.crypto.Cipher Cipher} transformation string.  {@code 0} indicates that the JCA Provider default
343         * block size for the specified {@link #getAlgorithmName() algorithm} should be used.
344         * <p/>
345         * This attribute is used <em>only</em> when constructing the transformation string for block (byte array)
346         * operations ({@link #encrypt(byte[], byte[])} and {@link #decrypt(byte[], byte[])}).  The
347         * {@link #getStreamingBlockSize() streamingBlockSize} attribute is used when the block cipher is used for
348         * streaming operations.
349         * <p/>
350         * The default value is {@code 0} which retains the JCA Provider default.
351         * <p/>
352         * <b>NOTE:</b> block cipher block sizes are very algorithm-specific.  If you change this value, ensure that it
353         * will work with the specified {@link #getAlgorithmName() algorithm}.
354         *
355         * @param blockSize the block cipher block size to be used when constructing the
356         *                  {@link javax.crypto.Cipher Cipher} transformation string, or {@code 0} if the JCA Provider
357         *                  default block size for the specified {@link #getAlgorithmName() algorithm} should be used.
358         */
359        public void setBlockSize(int blockSize) {
360            this.blockSize = Math.max(DEFAULT_BLOCK_SIZE, blockSize);
361            //clear out the transformation string so the next invocation will rebuild it with the new block size:
362            this.transformationString = null;
363        }
364    
365        /**
366         * Same purpose as the {@link #getModeName modeName} attribute, but is used instead only for for streaming
367         * operations ({@link #encrypt(java.io.InputStream, java.io.OutputStream, byte[])} and
368         * {@link #decrypt(java.io.InputStream, java.io.OutputStream, byte[])}).
369         * <p/>
370         * Note that unlike the {@link #getModeName modeName} attribute, the default value of this attribute is not
371         * {@code null} - it is {@link OperationMode#CFB CFB} for reasons described in the class-level JavaDoc in the
372         * {@code Streaming} section.
373         *
374         * @return the transformation string mode name to be used for streaming operations only.
375         */
376        public String getStreamingModeName() {
377            return streamingModeName;
378        }
379    
380        private boolean isModeStreamingCompatible(String modeName) {
381            return modeName != null &&
382                    !modeName.equalsIgnoreCase(OperationMode.ECB.name()) &&
383                    !modeName.equalsIgnoreCase(OperationMode.NONE.name());
384        }
385    
386        /**
387         * Sets the transformation string mode name to be used for streaming operations only.  The default value is
388         * {@link OperationMode#CFB CFB} for reasons described in the class-level JavaDoc in the {@code Streaming} section.
389         *
390         * @param streamingModeName transformation string mode name to be used for streaming operations only
391         */
392        public void setStreamingModeName(String streamingModeName) {
393            if (!isModeStreamingCompatible(streamingModeName)) {
394                String msg = "mode [" + streamingModeName + "] is not a valid operation mode for block cipher streaming.";
395                throw new IllegalArgumentException(msg);
396            }
397            this.streamingModeName = streamingModeName;
398            //clear out the streaming transformation string so the next invocation will rebuild it with the new mode:
399            this.streamingTransformationString = null;
400        }
401    
402        /**
403         * Sets the transformation string mode to be used for streaming operations only.  The default value is
404         * {@link OperationMode#CFB CFB} for reasons described in the class-level JavaDoc in the {@code Streaming} section.
405         *
406         * @param mode the transformation string mode to be used for streaming operations only
407         */
408        public void setStreamingMode(OperationMode mode) {
409            setStreamingModeName(mode.name());
410        }
411    
412        public String getStreamingPaddingSchemeName() {
413            return streamingPaddingSchemeName;
414        }
415    
416        public void setStreamingPaddingSchemeName(String streamingPaddingSchemeName) {
417            this.streamingPaddingSchemeName = streamingPaddingSchemeName;
418            //clear out the streaming transformation string so the next invocation will rebuild it with the new scheme:
419            this.streamingTransformationString = null;
420        }
421    
422        public void setStreamingPaddingScheme(PaddingScheme scheme) {
423            setStreamingPaddingSchemeName(scheme.getTransformationName());
424        }
425    
426        public int getStreamingBlockSize() {
427            return streamingBlockSize;
428        }
429    
430        public void setStreamingBlockSize(int streamingBlockSize) {
431            this.streamingBlockSize = Math.max(DEFAULT_BLOCK_SIZE, streamingBlockSize);
432            //clear out the streaming transformation string so the next invocation will rebuild it with the new block size:
433            this.streamingTransformationString = null;
434        }
435    
436        /**
437         * Returns the transformation string to use with the {@link javax.crypto.Cipher#getInstance} call.  If
438         * {@code streaming} is {@code true}, a block-cipher transformation string compatible with streaming operations will
439         * be constructed and cached for re-use later (see the class-level JavaDoc for more on using block ciphers
440         * for streaming).  If {@code streaming} is {@code false} a normal block-cipher transformation string will
441         * be constructed and cached for later re-use.
442         *
443         * @param streaming if the transformation string is going to be used for a Cipher performing stream-based encryption or not.
444         * @return the transformation string
445         */
446        protected String getTransformationString(boolean streaming) {
447            if (streaming) {
448                if (this.streamingTransformationString == null) {
449                    this.streamingTransformationString = buildStreamingTransformationString();
450                }
451                return this.streamingTransformationString;
452            } else {
453                if (this.transformationString == null) {
454                    this.transformationString = buildTransformationString();
455                }
456                return this.transformationString;
457            }
458        }
459    
460        private String buildTransformationString() {
461            return buildTransformationString(getModeName(), getPaddingSchemeName(), getBlockSize());
462        }
463    
464        private String buildStreamingTransformationString() {
465            return buildTransformationString(getStreamingModeName(), getStreamingPaddingSchemeName(), getStreamingBlockSize());
466        }
467    
468        private String buildTransformationString(String modeName, String paddingSchemeName, int blockSize) {
469            StringBuilder sb = new StringBuilder(getAlgorithmName());
470            if (StringUtils.hasText(modeName)) {
471                sb.append(TRANSFORMATION_STRING_DELIMITER).append(modeName);
472            }
473            if (blockSize > 0) {
474                sb.append(blockSize);
475            }
476            if (StringUtils.hasText(paddingSchemeName)) {
477                sb.append(TRANSFORMATION_STRING_DELIMITER).append(paddingSchemeName);
478            }
479            return sb.toString();
480        }
481    
482        /**
483         * Returns {@code true} if the specified cipher operation mode name supports initialization vectors,
484         * {@code false} otherwise.
485         *
486         * @param modeName the raw text name of the mode of operation
487         * @return {@code true} if the specified cipher operation mode name supports initialization vectors,
488         *         {@code false} otherwise.
489         */
490        private boolean isModeInitializationVectorCompatible(String modeName) {
491            return modeName != null &&
492                    !modeName.equalsIgnoreCase(OperationMode.ECB.name()) &&
493                    !modeName.equalsIgnoreCase(OperationMode.NONE.name());
494        }
495    
496        /**
497         * Overrides the parent implementation to ensure initialization vectors are always generated if streaming is
498         * enabled (block ciphers <em>must</em> use initialization vectors if they are to be used as a stream cipher).  If
499         * not being used as a stream cipher, then the value is computed based on whether or not the currently configured
500         * {@link #getModeName modeName} is compatible with initialization vectors as well as the result of the configured
501         * {@link #setGenerateInitializationVectors(boolean) generateInitializationVectors} value.
502         *
503         * @param streaming whether or not streaming is being performed
504         * @return {@code true} if streaming or a value computed based on if the currently configured mode is compatible
505         *         with initialization vectors.
506         */
507        @Override
508        protected boolean isGenerateInitializationVectors(boolean streaming) {
509            return streaming || super.isGenerateInitializationVectors() && isModeInitializationVectorCompatible(getModeName());
510        }
511    
512        @Override
513        protected byte[] generateInitializationVector(boolean streaming) {
514            if (streaming) {
515                String streamingModeName = getStreamingModeName();
516                if (!isModeInitializationVectorCompatible(streamingModeName)) {
517                    String msg = "streamingMode attribute value [" + streamingModeName + "] does not support " +
518                            "Initialization Vectors.  Ensure the streamingMode value represents an operation mode " +
519                            "that is compatible with initialization vectors.";
520                    throw new IllegalStateException(msg);
521                }
522            } else {
523                String modeName = getModeName();
524                if (!isModeInitializationVectorCompatible(modeName)) {
525                    String msg = "mode attribute value [" + modeName + "] does not support " +
526                            "Initialization Vectors.  Ensure the mode value represents an operation mode " +
527                            "that is compatible with initialization vectors.";
528                    throw new IllegalStateException(msg);
529                }
530            }
531            return super.generateInitializationVector(streaming);
532        }
533    }