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.KeyStore;
22  import java.security.PrivateKey;
23  import java.security.PublicKey;
24  import java.security.cert.Certificate;
25  import java.util.Objects;
26  
27  import javax.security.auth.Destroyable;
28  
29  import io.earcam.unexceptional.Exceptional;
30  
31  public class OpenedKeyStore implements Destroyable, AutoCloseable {
32  
33  	private KeyStore store;
34  	private KeyPairCredential credential;
35  
36  
37  	public OpenedKeyStore(KeyStore store, KeyPairCredential credential)
38  	{
39  		Objects.requireNonNull(store, "store");
40  		this.store = store;
41  		this.credential = credential;
42  	}
43  
44  
45  	public OpenedKeyStore(KeyStore store, String alias, char[] password)
46  	{
47  		this(store, new KeyPairCredential(KeyStores.keyPair(store, alias, password), alias, password));
48  	}
49  
50  
51  	@Override
52  	public void close()
53  	{
54  		destroy();
55  	}
56  
57  
58  	@Override
59  	public void destroy()
60  	{
61  		store = null;
62  		credential.destroy();
63  	}
64  
65  
66  	@Override
67  	public boolean isDestroyed()
68  	{
69  		return store == null;
70  	}
71  
72  
73  	public KeyStore store()
74  	{
75  		return store;
76  	}
77  
78  
79  	public PublicKey publicKey()
80  	{
81  		return credential.publicKey();
82  	}
83  
84  
85  	public PrivateKey privateKey()
86  	{
87  		return credential.privateKey();
88  	}
89  
90  
91  	public Certificate[] getCertificateChain()
92  	{
93  		return Exceptional.apply(store::getCertificateChain, credential.name());
94  	}
95  
96  
97  	public Certificate getCertificate()
98  	{
99  		return Exceptional.apply(store::getCertificate, credential.name());
100 	}
101 }