Samples JDK
EncryptionUtil.java
1 package com.freemindcafe.security.sample2;
2 
3 import java.io.File;
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;
15 
16 import javax.crypto.SecretKey;
17 
18 import org.eclipse.jetty.http.security.Password;
19 
20 public class EncryptionUtil {
21 
22  public static SecretKey readKeyFromKeystore(String keyStorePath, String keyStoreType, String keyStorePassword, String keyAlias)
23  throws NoSuchProviderException, KeyStoreException, UnrecoverableEntryException, NoSuchAlgorithmException, CertificateException, IOException {
24 
25  KeyStore keystore = loadKeyStore(keyStorePath, keyStoreType, keyStorePassword);
26  PasswordProtection pp = new PasswordProtection(Password.deobfuscate(keyStorePassword).toCharArray());
27 
28  SecretKey key = null;
29  if (keystore.entryInstanceOf(keyAlias, KeyStore.SecretKeyEntry.class)) {
30  KeyStore.SecretKeyEntry secretKeyEntry = (KeyStore.SecretKeyEntry)keystore.getEntry(keyAlias, pp);
31  key = secretKeyEntry.getSecretKey();
32  }
33  if (key == null) {
34  throw new RuntimeException("No secret key with alias " + keyAlias + " found in keystore file " + keyStorePath);
35  }
36  return key;
37  }
38 
39 
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());
44  return keystore;
45  }
46 
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;
54  break;
55  }
56  }
57  }
58  if (supportingProvider == null) {
59  throw new NoSuchProviderException("No Security Provider supporting keystore type '"+keyStoreType+"' is available");
60  }
61  return supportingProvider;
62  }
63 }