View Javadoc
1   /*-
2    * #%L
3    * io.earcam.utilitarian.security
4    * %%
5    * Copyright (C) 2017 earcam
6    * %%
7    * SPDX-License-Identifier: (BSD-3-Clause OR EPL-1.0 OR Apache-2.0 OR MIT)
8    *
9    * You <b>must</b> choose to accept, in full - any individual or combination of
10   * the following licenses:
11   * <ul>
12   * 	<li><a href="https://opensource.org/licenses/BSD-3-Clause">BSD-3-Clause</a></li>
13   * 	<li><a href="https://www.eclipse.org/legal/epl-v10.html">EPL-1.0</a></li>
14   * 	<li><a href="https://www.apache.org/licenses/LICENSE-2.0">Apache-2.0</a></li>
15   * 	<li><a href="https://opensource.org/licenses/MIT">MIT</a></li>
16   * </ul>
17   * #L%
18   */
19  package io.earcam.utilitarian.security;
20  
21  import java.security.KeyPair;
22  import java.security.KeyPairGenerator;
23  
24  import io.earcam.unexceptional.Exceptional;
25  import io.earcam.unexceptional.UncheckedSecurityException;
26  
27  public class Keys {
28  
29  	private static final int DEFAULT_KEYSIZE = 2048;
30  
31  
32  	private Keys()
33  	{}
34  
35  
36  	/**
37  	 * RSA key pair of size {@value #DEFAULT_KEYSIZE}
38  	 * 
39  	 * @return a key pair generated with RSA
40  	 * @throws UncheckedSecurityException if a {@link java.security.NoSuchAlgorithmException} is thrown
41  	 */
42  	public static KeyPair rsa()
43  	{
44  		return keyPair("RSA");
45  	}
46  
47  
48  	/**
49  	 * DSA key pair of size {@value #DEFAULT_KEYSIZE}
50  	 * 
51  	 * @return a key pair generated with DSA
52  	 * @throws UncheckedSecurityException if a {@link java.security.NoSuchAlgorithmException} is thrown
53  	 */
54  	public static KeyPair dsa()
55  	{
56  		return keyPair("DSA");
57  	}
58  
59  
60  	/**
61  	 * Generate an asymmetric key pair of size {@value #DEFAULT_KEYSIZE} for the supplied {@code algorithm}
62  	 * 
63  	 * @param algorithm e.g. RSA, DSA
64  	 * @return a key pair generated with the supplied {@code algorithm}
65  	 * @throws UncheckedSecurityException if a {@link java.security.NoSuchAlgorithmException} is thrown
66  	 */
67  	public static KeyPair keyPair(String algorithm)
68  	{
69  		return keyPair(algorithm, DEFAULT_KEYSIZE);
70  	}
71  
72  
73  	/**
74  	 * Generate an asymmetric key pair of size {@code keysize} for the supplied {@code algorithm}
75  	 * 
76  	 * @param algorithm e.g. RSA, DSA
77  	 * @param keysize
78  	 * @return a key pair generated with the supplied {@code algorithm}
79  	 * @throws UncheckedSecurityException if a {@link java.security.NoSuchAlgorithmException} is thrown
80  	 */
81  	public static KeyPair keyPair(String algorithm, int keysize)
82  	{
83  		KeyPairGenerator keyPairGenerator = Exceptional.apply(KeyPairGenerator::getInstance, algorithm);
84  		keyPairGenerator.initialize(keysize);
85  		return keyPairGenerator.generateKeyPair();
86  	}
87  }