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 javax.crypto.KeyGenerator;
022    import java.security.Key;
023    import java.security.NoSuchAlgorithmException;
024    
025    /**
026     * Base abstract class for supporting symmetric key cipher algorithms.
027     *
028     * @author Les Hazlewood
029     * @since 1.0
030     */
031    public abstract class AbstractSymmetricCipherService extends JcaCipherService {
032    
033        protected AbstractSymmetricCipherService(String algorithmName) {
034            super(algorithmName);
035        }
036    
037        /**
038         * Generates a new {@link java.security.Key Key} suitable for this CipherService's {@link #getAlgorithmName() algorithm}
039         * by calling {@link #generateNewKey(int) generateNewKey(128)} (uses a 128 bit size by default).
040         *
041         * @return a new {@link java.security.Key Key}, 128 bits in length.
042         */
043        public Key generateNewKey() {
044            return generateNewKey(getKeySize());
045        }
046    
047        /**
048         * Generates a new {@link Key Key} of the specified size suitable for this CipherService
049         * (based on the {@link #getAlgorithmName() algorithmName} using the JDK {@link javax.crypto.KeyGenerator KeyGenerator}.
050         *
051         * @param keyBitSize the bit size of the key to create
052         * @return the created key suitable for use with this CipherService
053         */
054        public Key generateNewKey(int keyBitSize) {
055            KeyGenerator kg;
056            try {
057                kg = KeyGenerator.getInstance(getAlgorithmName());
058            } catch (NoSuchAlgorithmException e) {
059                String msg = "Unable to acquire " + getAlgorithmName() + " algorithm.  This is required to function.";
060                throw new IllegalStateException(msg, e);
061            }
062            kg.init(keyBitSize);
063            return kg.generateKey();
064        }
065    
066    }