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