1 package com.freemindcafe.security.sample2;
4 import java.io.FileInputStream;
5 import java.io.IOException;
6 import java.security.KeyStore;
7 import java.security.KeyStore.PasswordProtection;
8 import java.security.KeyStoreException;
9 import java.security.NoSuchAlgorithmException;
10 import java.security.NoSuchProviderException;
11 import java.security.Provider;
12 import java.security.Security;
13 import java.security.UnrecoverableEntryException;
14 import java.security.cert.CertificateException;
16 import javax.crypto.SecretKey;
18 import org.eclipse.jetty.http.security.Password;
22 public static SecretKey readKeyFromKeystore(String keyStorePath, String keyStoreType, String keyStorePassword, String keyAlias)
23 throws NoSuchProviderException, KeyStoreException, UnrecoverableEntryException, NoSuchAlgorithmException, CertificateException, IOException {
25 KeyStore keystore = loadKeyStore(keyStorePath, keyStoreType, keyStorePassword);
26 PasswordProtection pp =
new PasswordProtection(Password.deobfuscate(keyStorePassword).toCharArray());
29 if (keystore.entryInstanceOf(keyAlias, KeyStore.SecretKeyEntry.class)) {
30 KeyStore.SecretKeyEntry secretKeyEntry = (KeyStore.SecretKeyEntry)keystore.getEntry(keyAlias, pp);
31 key = secretKeyEntry.getSecretKey();
34 throw new RuntimeException(
"No secret key with alias " + keyAlias +
" found in keystore file " + keyStorePath);
40 public static KeyStore loadKeyStore(String keyStorePath, String keyStoreType, String keyStorePassword)
41 throws CertificateException, NoSuchAlgorithmException, NoSuchProviderException, KeyStoreException, IOException {
42 KeyStore keystore = KeyStore.getInstance(keyStoreType, getSupportingSecurityProvider(keyStoreType));
43 keystore.load(
new FileInputStream(
new File(keyStorePath)), Password.deobfuscate(keyStorePassword).toCharArray());
47 public static Provider getSupportingSecurityProvider(String keyStoreType)
throws NoSuchProviderException {
48 Provider supportingProvider = null;
49 Provider[] providers = Security.getProviders();
50 if (providers != null) {
51 for (Provider p : providers) {
52 if (p.getService(
"KeyStore", keyStoreType) != null) {
53 supportingProvider = p;
58 if (supportingProvider == null) {
59 throw new NoSuchProviderException(
"No Security Provider supporting keystore type '"+keyStoreType+
"' is available");
61 return supportingProvider;