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 javax.crypto.KeyGenerator; 22 import java.security.Key; 23 import java.security.NoSuchAlgorithmException; 24 25 /** 26 * Base abstract class for supporting symmetric key cipher algorithms. 27 * 28 * @since 1.0 29 */ 30 public abstract class AbstractSymmetricCipherService extends JcaCipherService { 31 32 protected AbstractSymmetricCipherService(String algorithmName) { 33 super(algorithmName); 34 } 35 36 /** 37 * Generates a new {@link java.security.Key Key} suitable for this CipherService's {@link #getAlgorithmName() algorithm} 38 * by calling {@link #generateNewKey(int) generateNewKey(128)} (uses a 128 bit size by default). 39 * 40 * @return a new {@link java.security.Key Key}, 128 bits in length. 41 */ 42 public Key generateNewKey() { 43 return generateNewKey(getKeySize()); 44 } 45 46 /** 47 * Generates a new {@link Key Key} of the specified size suitable for this CipherService 48 * (based on the {@link #getAlgorithmName() algorithmName} using the JDK {@link javax.crypto.KeyGenerator KeyGenerator}. 49 * 50 * @param keyBitSize the bit size of the key to create 51 * @return the created key suitable for use with this CipherService 52 */ 53 public Key generateNewKey(int keyBitSize) { 54 KeyGenerator kg; 55 try { 56 kg = KeyGenerator.getInstance(getAlgorithmName()); 57 } catch (NoSuchAlgorithmException e) { 58 String msg = "Unable to acquire " + getAlgorithmName() + " algorithm. This is required to function."; 59 throw new IllegalStateException(msg, e); 60 } 61 kg.init(keyBitSize); 62 return kg.generateKey(); 63 } 64 65 }