|
6 | 6 | import java.io.FileInputStream; |
7 | 7 | import java.io.IOException; |
8 | 8 | import java.io.InputStream; |
| 9 | +import java.security.GeneralSecurityException; |
9 | 10 | import java.security.InvalidKeyException; |
10 | 11 | import java.security.KeyStore; |
| 12 | +import java.security.KeyStore.Entry; |
| 13 | +import java.security.KeyStore.PrivateKeyEntry; |
| 14 | +import java.security.KeyStore.ProtectionParameter; |
11 | 15 | import java.security.KeyStoreException; |
12 | 16 | import java.security.NoSuchAlgorithmException; |
13 | 17 | import java.security.NoSuchProviderException; |
14 | 18 | import java.security.PrivateKey; |
15 | 19 | import java.security.SignatureException; |
| 20 | +import java.security.UnrecoverableEntryException; |
16 | 21 | import java.security.cert.Certificate; |
17 | 22 | import java.security.cert.CertificateException; |
18 | 23 | import java.security.cert.X509Certificate; |
|
28 | 33 | import com.google.common.collect.Lists; |
29 | 34 |
|
30 | 35 | public class KeyStoreUtils { |
| 36 | + public static final String DEFAULT_KEYSTORE_SECRET = "notasecret"; |
| 37 | + |
| 38 | + public static KeyStore load(File keystoreFile) throws KeyStoreException, IOException, NoSuchAlgorithmException, |
| 39 | + CertificateException { |
| 40 | + return load(keystoreFile, DEFAULT_KEYSTORE_SECRET); |
| 41 | + } |
| 42 | + |
31 | 43 | public static KeyStore load(File keystoreFile, String keystoreSecret) throws KeyStoreException, IOException, |
32 | 44 | NoSuchAlgorithmException, CertificateException { |
33 | 45 | InputStream is = null; |
@@ -150,4 +162,25 @@ public static byte[] serialize(KeyStore keystore, String keystoreSecret) throws |
150 | 162 | Io.safeClose(baos); |
151 | 163 | } |
152 | 164 | } |
| 165 | + |
| 166 | + public static CertificateAndKey getCertificateAndKey(KeyStore keyStore, String alias, String password) |
| 167 | + throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException { |
| 168 | + if (!keyStore.isKeyEntry(alias)) { |
| 169 | + return null; |
| 170 | + } |
| 171 | + |
| 172 | + ProtectionParameter protParam = new KeyStore.PasswordProtection(password.toCharArray()); |
| 173 | + Entry key = keyStore.getEntry(alias, protParam); |
| 174 | + if (key == null || !(key instanceof PrivateKeyEntry)) { |
| 175 | + return null; |
| 176 | + } |
| 177 | + |
| 178 | + return new KeystoreCertificateAndKey((PrivateKeyEntry) key); |
| 179 | + } |
| 180 | + |
| 181 | + public static void put(KeyStore keystore, String alias, CertificateAndKey certificateAndKey, String secret) |
| 182 | + throws GeneralSecurityException { |
| 183 | + keystore.setKeyEntry(alias, certificateAndKey.getPrivateKey(), secret.toCharArray(), |
| 184 | + certificateAndKey.getCertificateChain()); |
| 185 | + } |
153 | 186 | } |
0 commit comments