1 /**
2 * Copyright (C) 2016 Gary Gregory. All rights reserved.
3 *
4 * See the NOTICE.txt file distributed with this work for additional
5 * information regarding copyright ownership.
6 *
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 */
19
20 package com.garygregory.jcommander.converters.crypto;
21
22 import java.security.NoSuchAlgorithmException;
23 import java.security.NoSuchProviderException;
24 import java.security.Provider;
25
26 import javax.crypto.Cipher;
27 import javax.crypto.NoSuchPaddingException;
28
29 import com.garygregory.jcommander.converters.AbstractBaseConverter;
30
31 /**
32 * Converts a {@link String} into a {@link Cipher}.
33 * <p>
34 * For a description of the transformation parameter format, see {@link Cipher#getInstance(String)}.
35 * </p>
36 * <p>
37 * To get a Cipher from a specific {@link Provider}, use the syntax {@code transformation:provider} as described by
38 * {@link Cipher#getInstance(String, String)}.
39 * </p>
40 *
41 * <p>
42 * Example:
43 * </p>
44 *
45 * <pre class="prettyprint">
46 * <code class="language-java">@Parameter(names = { "--cipher" }, converter = CipherConverter.class)
47 * private Cipher cipher;</code>
48 * </pre>
49 * <p>
50 *
51 * @see Cipher
52 * @see Cipher#getInstance(String)
53 * @see Cipher#getInstance(String, String)
54 *
55 * @since 1.0.0
56 * @author <a href="mailto:ggregory@garygregory.com">Gary Gregory</a>
57 */
58 public class CipherConverter extends AbstractBaseConverter<Cipher> {
59
60 /**
61 * Constructs a converter.
62 *
63 * @param optionName
64 * The option name, may be null.
65 */
66 public CipherConverter(final String optionName) {
67 super(optionName, Cipher.class);
68 }
69
70 @Override
71 protected Cipher convertImpl(final String value) throws NoSuchAlgorithmException, NoSuchPaddingException, NoSuchProviderException {
72 final String[] split = split(value);
73 final String transformation = split[0];
74 return isSingle(split) ? Cipher.getInstance(value) : Cipher.getInstance(transformation, split[1]);
75 }
76
77 }