001/** 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.camel.converter.stream; 018 019import java.security.GeneralSecurityException; 020import java.security.Key; 021import java.security.SecureRandom; 022 023import javax.crypto.Cipher; 024import javax.crypto.KeyGenerator; 025import javax.crypto.spec.IvParameterSpec; 026 027/** 028 * A class to hold a pair of encryption and decryption ciphers. 029 */ 030public class CipherPair { 031 private final String transformation; 032 private final Cipher enccipher; 033 private final Cipher deccipher; 034 035 public CipherPair(String transformation) throws GeneralSecurityException { 036 this.transformation = transformation; 037 038 int d = transformation.indexOf('/'); 039 String a; 040 if (d > 0) { 041 a = transformation.substring(0, d); 042 } else { 043 a = transformation; 044 } 045 046 KeyGenerator keygen = KeyGenerator.getInstance(a); 047 keygen.init(new SecureRandom()); 048 Key key = keygen.generateKey(); 049 enccipher = Cipher.getInstance(transformation); 050 deccipher = Cipher.getInstance(transformation); 051 enccipher.init(Cipher.ENCRYPT_MODE, key); 052 final byte[] ivp = enccipher.getIV(); 053 deccipher.init(Cipher.DECRYPT_MODE, key, ivp == null ? null : new IvParameterSpec(ivp)); 054 } 055 056 public String getTransformation() { 057 return transformation; 058 } 059 060 public Cipher getEncryptor() { 061 return enccipher; 062 } 063 064 public Cipher getDecryptor() { 065 return deccipher; 066 } 067}