001/** 002 * Copyright (C) 2016 Gary Gregory. All rights reserved. 003 * 004 * See the NOTICE.txt file distributed with this work for additional 005 * information regarding copyright ownership. 006 * 007 * Licensed under the Apache License, Version 2.0 (the "License"); 008 * you may not use this file except in compliance with the License. 009 * You may obtain a copy of the License at 010 * 011 * http://www.apache.org/licenses/LICENSE-2.0 012 * 013 * Unless required by applicable law or agreed to in writing, software 014 * distributed under the License is distributed on an "AS IS" BASIS, 015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 016 * See the License for the specific language governing permissions and 017 * limitations under the License. 018 */ 019 020package com.garygregory.jcommander.converters.crypto; 021 022import java.security.NoSuchAlgorithmException; 023import java.security.NoSuchProviderException; 024import java.security.Provider; 025 026import javax.crypto.Cipher; 027import javax.crypto.NoSuchPaddingException; 028 029import com.garygregory.jcommander.converters.AbstractBaseConverter; 030 031/** 032 * Converts a {@link String} into a {@link Cipher}. 033 * <p> 034 * For a description of the transformation parameter format, see {@link Cipher#getInstance(String)}. 035 * </p> 036 * <p> 037 * To get a Cipher from a specific {@link Provider}, use the syntax {@code transformation:provider} as described by 038 * {@link Cipher#getInstance(String, String)}. 039 * </p> 040 * 041 * <p> 042 * Example: 043 * </p> 044 * 045 * <pre class="prettyprint"> 046 * <code class="language-java">@Parameter(names = { "--cipher" }, converter = CipherConverter.class) 047 * private Cipher cipher;</code> 048 * </pre> 049 * <p> 050 * 051 * @see Cipher 052 * @see Cipher#getInstance(String) 053 * @see Cipher#getInstance(String, String) 054 * 055 * @since 1.0.0 056 * @author <a href="mailto:ggregory@garygregory.com">Gary Gregory</a> 057 */ 058public class CipherConverter extends AbstractBaseConverter<Cipher> { 059 060 /** 061 * Constructs a converter. 062 * 063 * @param optionName 064 * The option name, may be null. 065 */ 066 public CipherConverter(final String optionName) { 067 super(optionName, Cipher.class); 068 } 069 070 @Override 071 protected Cipher convertImpl(final String value) throws NoSuchAlgorithmException, NoSuchPaddingException, NoSuchProviderException { 072 final String[] split = split(value); 073 final String transformation = split[0]; 074 return isSingle(split) ? Cipher.getInstance(value) : Cipher.getInstance(transformation, split[1]); 075 } 076 077}