[jboss-cvs] Picketbox SVN: r404 - branches/embargo/4.0.16.Final-vault/security-jboss-sx/jbosssx/src/main/java/org/picketbox/plugins/vault.
jboss-cvs-commits at lists.jboss.org
jboss-cvs-commits at lists.jboss.org
Tue Apr 16 15:10:44 EDT 2013
Author: pskopek
Date: 2013-04-16 15:10:44 -0400 (Tue, 16 Apr 2013)
New Revision: 404
Modified:
branches/embargo/4.0.16.Final-vault/security-jboss-sx/jbosssx/src/main/java/org/picketbox/plugins/vault/OriginalPicketBoxSecurityVault.java
branches/embargo/4.0.16.Final-vault/security-jboss-sx/jbosssx/src/main/java/org/picketbox/plugins/vault/PicketBoxSecurityVault.java
Log:
adding keystore type support
Modified: branches/embargo/4.0.16.Final-vault/security-jboss-sx/jbosssx/src/main/java/org/picketbox/plugins/vault/OriginalPicketBoxSecurityVault.java
===================================================================
--- branches/embargo/4.0.16.Final-vault/security-jboss-sx/jbosssx/src/main/java/org/picketbox/plugins/vault/OriginalPicketBoxSecurityVault.java 2013-04-16 15:42:36 UTC (rev 403)
+++ branches/embargo/4.0.16.Final-vault/security-jboss-sx/jbosssx/src/main/java/org/picketbox/plugins/vault/OriginalPicketBoxSecurityVault.java 2013-04-16 19:10:44 UTC (rev 404)
@@ -201,7 +201,7 @@
{
String keystorePass = decode(maskedPassword, salt, iterationCount);
keyStorePWD = keystorePass.toCharArray();
- keystore = KeyStoreUtil.getKeyStore(keystoreURL, keystorePass.toCharArray());
+ keystore = KeyStoreUtil.getKeyStore(null, keystoreURL, keystorePass.toCharArray());
keypair = KeyStoreUtil.getPrivateKey(keystore, alias, keystorePass.toCharArray());
}
catch (Exception e)
Modified: branches/embargo/4.0.16.Final-vault/security-jboss-sx/jbosssx/src/main/java/org/picketbox/plugins/vault/PicketBoxSecurityVault.java
===================================================================
--- branches/embargo/4.0.16.Final-vault/security-jboss-sx/jbosssx/src/main/java/org/picketbox/plugins/vault/PicketBoxSecurityVault.java 2013-04-16 15:42:36 UTC (rev 403)
+++ branches/embargo/4.0.16.Final-vault/security-jboss-sx/jbosssx/src/main/java/org/picketbox/plugins/vault/PicketBoxSecurityVault.java 2013-04-16 19:10:44 UTC (rev 404)
@@ -53,344 +53,297 @@
import java.util.concurrent.ConcurrentHashMap;
/**
- * An instance of {@link SecurityVault} that uses
- * a {@link KeyStore}
- * The shared key just uses a concatenation of a {@link java.util.UUID}
- * and a keystore alias.
+ * An instance of {@link SecurityVault} that uses a {@link KeyStore} The shared key just uses a concatenation of a
+ * {@link java.util.UUID} and a keystore alias.
*
- * The following options are expected in the {@link SecurityVault#init(Map)} call:
- * ENC_FILE_DIR: the location where the encoded files will be kept. End with "/" or "\" based on your platform
- * KEYSTORE_URL: location where your keystore is located
- * KEYSTORE_PASSWORD: Masked keystore password. Has to be prepended with MASK-
- * KEYSTORE_ALIAS: Alias where the keypair is located
- * SALT: salt of the masked password. Ensured it is 8 characters in length
- * ITERATION_COUNT: Iteration Count of the masked password.
- * KEY_SIZE: Key size of encryption. Default is 128 bytes.
+ * The following options are expected in the {@link SecurityVault#init(Map)} call: <br/>
+ * ENC_FILE_DIR: the location where the encoded files will be kept. End with "/" or "\" based on your platform. <br/>
+ * KEYSTORE_URL: location where your keystore is located. <br/>
+ * KEYSTORE_PASSWORD: Masked keystore password. Has to be prepended with "MASK-". <br/>
+ * KEYSTORE_ALIAS: Alias where the keypair is located. <br/>
+ * SALT: salt of the masked password. Ensured it is 8 characters in length. <br/>
+ * ITERATION_COUNT: Iteration Count of the masked password. <br/>
+ * KEY_SIZE: Key size of encryption. Default is 128 bytes. <br/>
+ * CREATE_KEYSTORE: Whether PicketBox Security Vault has to create missing key store in time of initialization. Default is "FALSE". Implies KEYSTORE_TYPE "JCEKS". <br/>
+ * KEYSTORE_TYPE: Key store type. Default is JCEKS. <br/>
*
* @author Anil.Saldhana at redhat.com
* @author Peter Skopek (pskopek_at_redhat_dot_com)
* @since Aug 12, 2011
*/
-public class PicketBoxSecurityVault implements SecurityVault
-{
- protected boolean finishedInit = false;
+public class PicketBoxSecurityVault implements SecurityVault {
+ protected boolean finishedInit = false;
+ protected KeyStore keystore = null;
+ protected int keySize = 128;
+ private char[] keyStorePWD = null;
+ private String alias = null;
+ private SecurityVaultData vaultContent = null;
+ private SecretKey adminKey;
+ private String decodedEncFileDir;
+ private boolean createKeyStore = false;
+ private String keyStoreType = defaultKeyStoreType;
- protected KeyStore keystore = null;
-
- protected String encryptionAlgorithm = "AES";
-
- protected int keySize = 128;
-
- private char[] keyStorePWD = null;
-
- private String alias = null;
-
- private SecurityVaultData vaultContent = null;
-
- private SecretKey adminKey;
-
- public static final String ENC_FILE_DIR = "ENC_FILE_DIR";
-
- public static final String KEYSTORE_URL = "KEYSTORE_URL";
-
- public static final String KEYSTORE_PASSWORD = "KEYSTORE_PASSWORD";
-
- public static final String KEYSTORE_ALIAS = "KEYSTORE_ALIAS";
-
- public static final String SALT = "SALT";
-
- public static final String ITERATION_COUNT = "ITERATION_COUNT";
-
- public static final String PASS_MASK_PREFIX = "MASK-";
-
- public static final String PUBLIC_CERT = "PUBLIC_CERT";
-
- public static final String KEY_SIZE = "KEY_SIZE";
+ protected String encryptionAlgorithm = "AES";
+ protected static final String VAULT_CONTENT_FILE = "VAULT.dat"; // versioned vault data file
+ protected static final String defaultKeyStoreType = "JCEKS";
- // backward compatibility constants
- private static final String ENCODED_FILE = "ENC.dat";
- private static final String SHARED_KEY_FILE = "Shared.dat";
- private static final String ADMIN_KEY = "ADMIN_KEY";
-
- // versioned vault data file
- protected static final String VAULT_CONTENT_FILE = "VAULT.dat";
-
- private String decodedEncFileDir;
-
- protected String LINE_BREAK = "LINE_BREAK";
-
- /*
- * @see org.jboss.security.vault.SecurityVault#init(java.util.Map)
- */
- public void init(Map<String, Object> options) throws SecurityVaultException
- {
- if(options == null || options.isEmpty())
- throw PicketBoxMessages.MESSAGES.invalidNullOrEmptyOptionMap("options");
+ // options
+ public static final String ENC_FILE_DIR = "ENC_FILE_DIR";
+ public static final String KEYSTORE_URL = "KEYSTORE_URL";
+ public static final String KEYSTORE_PASSWORD = "KEYSTORE_PASSWORD";
+ public static final String KEYSTORE_ALIAS = "KEYSTORE_ALIAS";
+ public static final String SALT = "SALT";
+ public static final String ITERATION_COUNT = "ITERATION_COUNT";
+ public static final String PASS_MASK_PREFIX = "MASK-";
+ public static final String PUBLIC_CERT = "PUBLIC_CERT";
+ public static final String KEY_SIZE = "KEY_SIZE";
+ public static final String CREATE_KEYSTORE = "CREATE_KEYSTORE";
+ public static final String KEYSTORE_TYPE = "KEYSTORE_TYPE";
- String keystoreURL = (String) options.get(KEYSTORE_URL);
- if(keystoreURL == null)
- throw new SecurityVaultException(PicketBoxMessages.MESSAGES.invalidNullOrEmptyOptionMessage(KEYSTORE_URL));
+ // backward compatibility constants
+ private static final String ENCODED_FILE = "ENC.dat";
+ private static final String SHARED_KEY_FILE = "Shared.dat";
+ private static final String ADMIN_KEY = "ADMIN_KEY";
- if (keystoreURL.contains("${")){
- keystoreURL = keystoreURL.replaceAll(":", StringUtil.PROPERTY_DEFAULT_SEPARATOR); // replace single ":" with PL default
- }
- keystoreURL = StringUtil.getSystemPropertyAsString(keystoreURL);
+ /*
+ * @see org.jboss.security.vault.SecurityVault#init(java.util.Map)
+ */
+ public void init(Map<String, Object> options) throws SecurityVaultException {
+ if (options == null || options.isEmpty())
+ throw PicketBoxMessages.MESSAGES.invalidNullOrEmptyOptionMap("options");
- String maskedPassword = (String) options.get(KEYSTORE_PASSWORD);
- if(maskedPassword == null)
- throw new SecurityVaultException(PicketBoxMessages.MESSAGES.invalidNullOrEmptyOptionMessage(KEYSTORE_PASSWORD));
- if(maskedPassword.startsWith(PASS_MASK_PREFIX) == false)
- throw new SecurityVaultException(PicketBoxMessages.MESSAGES.invalidUnmaskedKeystorePasswordMessage());
+ String keystoreURL = (String) options.get(KEYSTORE_URL);
+ if (keystoreURL == null)
+ throw new SecurityVaultException(PicketBoxMessages.MESSAGES.invalidNullOrEmptyOptionMessage(KEYSTORE_URL));
- String salt = (String) options.get(SALT);
- if(salt == null)
- throw new SecurityVaultException(PicketBoxMessages.MESSAGES.invalidNullOrEmptyOptionMessage(SALT));
+ if (keystoreURL.contains("${")) {
+ keystoreURL = keystoreURL.replaceAll(":", StringUtil.PROPERTY_DEFAULT_SEPARATOR); // replace single ":" with PL
+ // default
+ }
+ keystoreURL = StringUtil.getSystemPropertyAsString(keystoreURL);
- String iterationCountStr = (String) options.get(ITERATION_COUNT);
- if(iterationCountStr == null)
- throw new SecurityVaultException(PicketBoxMessages.MESSAGES.invalidNullOrEmptyOptionMessage(ITERATION_COUNT));
- int iterationCount = Integer.parseInt(iterationCountStr);
-
- this.alias = (String) options.get(KEYSTORE_ALIAS);
- if(alias == null)
- throw new SecurityVaultException(PicketBoxMessages.MESSAGES.invalidNullOrEmptyOptionMessage(KEYSTORE_ALIAS));
-
- String keySizeStr = (String) options.get(KEY_SIZE);
- if(keySizeStr != null)
- {
- keySize = Integer.parseInt(keySizeStr);
- }
-
- String encFileDir = (String) options.get(ENC_FILE_DIR);
- if(encFileDir == null)
- throw new SecurityVaultException(PicketBoxMessages.MESSAGES.invalidNullOrEmptyOptionMessage(ENC_FILE_DIR));
+ String maskedPassword = (String) options.get(KEYSTORE_PASSWORD);
+ if (maskedPassword == null)
+ throw new SecurityVaultException(PicketBoxMessages.MESSAGES.invalidNullOrEmptyOptionMessage(KEYSTORE_PASSWORD));
+ if (maskedPassword.startsWith(PASS_MASK_PREFIX) == false)
+ throw new SecurityVaultException(PicketBoxMessages.MESSAGES.invalidUnmaskedKeystorePasswordMessage());
- try
- {
- String keystorePass = decode(maskedPassword, salt, iterationCount);
- keyStorePWD = keystorePass.toCharArray();
- keystore = KeyStoreUtil.getKeyStore(keystoreURL, keystorePass.toCharArray());
- }
- catch (Exception e)
- {
- throw new SecurityVaultException(e);
- }
-
- // read and possibly convert vault content
- readVaultContent(keystoreURL, encFileDir);
+ String salt = (String) options.get(SALT);
+ if (salt == null)
+ throw new SecurityVaultException(PicketBoxMessages.MESSAGES.invalidNullOrEmptyOptionMessage(SALT));
-
- PicketBoxLogger.LOGGER.infoVaultInitialized();
- finishedInit = true;
- }
+ String iterationCountStr = (String) options.get(ITERATION_COUNT);
+ if (iterationCountStr == null)
+ throw new SecurityVaultException(PicketBoxMessages.MESSAGES.invalidNullOrEmptyOptionMessage(ITERATION_COUNT));
+ int iterationCount = Integer.parseInt(iterationCountStr);
- /*
- * @see org.jboss.security.vault.SecurityVault#isInitialized()
- */
- public boolean isInitialized()
- {
- return finishedInit;
- }
+ this.alias = (String) options.get(KEYSTORE_ALIAS);
+ if (alias == null)
+ throw new SecurityVaultException(PicketBoxMessages.MESSAGES.invalidNullOrEmptyOptionMessage(KEYSTORE_ALIAS));
- /*
- * @see org.jboss.security.vault.SecurityVault#handshake(java.util.Map)
- */
- public byte[] handshake(Map<String, Object> handshakeOptions) throws SecurityVaultException {
- return new byte[keySize];
- }
-
- /*
- * @see org.jboss.security.vault.SecurityVault#keyList()
- */
+ String keySizeStr = (String) options.get(KEY_SIZE);
+ if (keySizeStr != null) {
+ keySize = Integer.parseInt(keySizeStr);
+ }
+
+ String encFileDir = (String) options.get(ENC_FILE_DIR);
+ if (encFileDir == null)
+ throw new SecurityVaultException(PicketBoxMessages.MESSAGES.invalidNullOrEmptyOptionMessage(ENC_FILE_DIR));
+
+ createKeyStore = (options.get(CREATE_KEYSTORE) != null ? Boolean.parseBoolean((String) options.get(CREATE_KEYSTORE))
+ : createKeyStore);
+ keyStoreType = (options.get(KEYSTORE_TYPE) != null ? (String) options.get(KEYSTORE_TYPE) : defaultKeyStoreType);
+
+ try {
+ String keystorePass = decode(maskedPassword, salt, iterationCount);
+ keyStorePWD = keystorePass.toCharArray();
+ keystore = getKeyStore(keystoreURL);
+ } catch (Exception e) {
+ throw new SecurityVaultException(e);
+ }
+
+ // read and possibly convert vault content
+ readVaultContent(keystoreURL, encFileDir);
+
+ PicketBoxLogger.LOGGER.infoVaultInitialized();
+ finishedInit = true;
+ }
+
+ /*
+ * @see org.jboss.security.vault.SecurityVault#isInitialized()
+ */
+ public boolean isInitialized() {
+ return finishedInit;
+ }
+
+ /*
+ * @see org.jboss.security.vault.SecurityVault#handshake(java.util.Map)
+ */
+ public byte[] handshake(Map<String, Object> handshakeOptions) throws SecurityVaultException {
+ return new byte[keySize];
+ }
+
+ /*
+ * @see org.jboss.security.vault.SecurityVault#keyList()
+ */
public Set<String> keyList() throws SecurityVaultException {
return vaultContent.getVaultData().keySet();
}
- /*
- * @see org.jboss.security.vault.SecurityVault#store(java.lang.String, java.lang.String, char[], byte[])
- */
- public void store(String vaultBlock, String attributeName, char[] attributeValue, byte[] sharedKey)
- throws SecurityVaultException
- {
- if(StringUtil.isNullOrEmpty(vaultBlock))
- throw PicketBoxMessages.MESSAGES.invalidNullArgument("vaultBlock");
- if(StringUtil.isNullOrEmpty(attributeName))
- throw PicketBoxMessages.MESSAGES.invalidNullArgument("attributeName");
+ /*
+ * @see org.jboss.security.vault.SecurityVault#store(java.lang.String, java.lang.String, char[], byte[])
+ */
+ public void store(String vaultBlock, String attributeName, char[] attributeValue, byte[] sharedKey)
+ throws SecurityVaultException {
+ if (StringUtil.isNullOrEmpty(vaultBlock))
+ throw PicketBoxMessages.MESSAGES.invalidNullArgument("vaultBlock");
+ if (StringUtil.isNullOrEmpty(attributeName))
+ throw PicketBoxMessages.MESSAGES.invalidNullArgument("attributeName");
- vaultContent.getVaultData().put(dataKey(vaultBlock, attributeName), sharedKey);
-
- String av = new String(attributeValue);
-
- EncryptionUtil util = new EncryptionUtil(encryptionAlgorithm, keySize);
- try
- {
- SecretKeySpec sKeySpec = new SecretKeySpec(adminKey.getEncoded(), encryptionAlgorithm);
- byte[] encryptedData = util.encrypt(av.getBytes(), sKeySpec);
- vaultContent.getVaultData().put(dataKey(vaultBlock, attributeName), encryptedData);
- }
- catch (Exception e1)
- {
- throw new SecurityVaultException(PicketBoxMessages.MESSAGES.unableToEncryptDataMessage(),e1);
- }
-
- try {
- writeVaultData();
- }
- catch (IOException e) {
- throw new SecurityVaultException(PicketBoxMessages.MESSAGES.unableToWriteVaultDataFileMessage(VAULT_CONTENT_FILE), e);
- }
- }
+ vaultContent.getVaultData().put(dataKey(vaultBlock, attributeName), sharedKey);
- /*
- * @see org.jboss.security.vault.SecurityVault#retrieve(java.lang.String, java.lang.String, byte[])
- */
- public char[] retrieve(String vaultBlock, String attributeName, byte[] sharedKey) throws SecurityVaultException
- {
- if(StringUtil.isNullOrEmpty(vaultBlock))
- throw PicketBoxMessages.MESSAGES.invalidNullArgument("vaultBlock");
- if(StringUtil.isNullOrEmpty(attributeName))
- throw PicketBoxMessages.MESSAGES.invalidNullArgument("attributeName");
+ String av = new String(attributeValue);
- byte[] encryptedValue = vaultContent.getVaultData().get(dataKey(vaultBlock, attributeName));
-
- SecretKeySpec secretKeySpec = new SecretKeySpec(adminKey.getEncoded(), encryptionAlgorithm);
- EncryptionUtil encUtil = new EncryptionUtil(encryptionAlgorithm, keySize);
- try
- {
- return (new String(encUtil.decrypt(encryptedValue, secretKeySpec))).toCharArray();
- }
- catch (Exception e)
- {
- throw new SecurityVaultException(e);
- }
- }
+ EncryptionUtil util = new EncryptionUtil(encryptionAlgorithm, keySize);
+ try {
+ SecretKeySpec sKeySpec = new SecretKeySpec(adminKey.getEncoded(), encryptionAlgorithm);
+ byte[] encryptedData = util.encrypt(av.getBytes(), sKeySpec);
+ vaultContent.getVaultData().put(dataKey(vaultBlock, attributeName), encryptedData);
+ } catch (Exception e1) {
+ throw new SecurityVaultException(PicketBoxMessages.MESSAGES.unableToEncryptDataMessage(), e1);
+ }
- /**
- * @see org.jboss.security.vault.SecurityVault#exists(String, String)
- */
- public boolean exists(String vaultBlock, String attributeName) throws SecurityVaultException {
- return vaultContent.getVaultData().get(dataKey(vaultBlock, attributeName)) != null;
- }
-
- /*
- * @see org.jboss.security.vault.SecurityVault#remove(java.lang.String, java.lang.String, byte[])
- */
- public boolean remove(String vaultBlock, String attributeName, byte[] sharedKey)
- throws SecurityVaultException
- {
- try {
- vaultContent.getVaultData().remove(dataKey(vaultBlock, attributeName));
- }
- catch(Exception e) {
- return false;
- }
- return true;
- }
-
- private String decode(String maskedString, String salt, int iterationCount) throws Exception
- {
- String pbeAlgo = "PBEwithMD5andDES";
- if (maskedString.startsWith(PASS_MASK_PREFIX))
- {
- // Create the PBE secret key
- SecretKeyFactory factory = SecretKeyFactory.getInstance(pbeAlgo);
+ try {
+ writeVaultData();
+ } catch (IOException e) {
+ throw new SecurityVaultException(PicketBoxMessages.MESSAGES.unableToWriteVaultDataFileMessage(VAULT_CONTENT_FILE),
+ e);
+ }
+ }
- char[] password = "somearbitrarycrazystringthatdoesnotmatter".toCharArray();
- PBEParameterSpec cipherSpec = new PBEParameterSpec(salt.getBytes(), iterationCount);
- PBEKeySpec keySpec = new PBEKeySpec(password);
- SecretKey cipherKey = factory.generateSecret(keySpec);
+ /*
+ * @see org.jboss.security.vault.SecurityVault#retrieve(java.lang.String, java.lang.String, byte[])
+ */
+ public char[] retrieve(String vaultBlock, String attributeName, byte[] sharedKey) throws SecurityVaultException {
+ if (StringUtil.isNullOrEmpty(vaultBlock))
+ throw PicketBoxMessages.MESSAGES.invalidNullArgument("vaultBlock");
+ if (StringUtil.isNullOrEmpty(attributeName))
+ throw PicketBoxMessages.MESSAGES.invalidNullArgument("attributeName");
- maskedString = maskedString.substring(PASS_MASK_PREFIX.length());
- String decodedValue = PBEUtils.decode64(maskedString, pbeAlgo, cipherKey, cipherSpec);
+ byte[] encryptedValue = vaultContent.getVaultData().get(dataKey(vaultBlock, attributeName));
- maskedString = decodedValue;
- }
- return maskedString;
- }
-
- private void setUpVault(String keystoreURL, String decodedEncFileDir) throws NoSuchAlgorithmException, IOException
- {
- vaultContent = new SecurityVaultData(new ConcurrentHashMap<String, byte[]>());
- writeVaultData();
-
- SecretKey sk = getAdminKey();
- if (sk != null) {
- adminKey = sk;
- }
- else {
- // try to generate new admin key and store it under specified alias
- EncryptionUtil util = new EncryptionUtil(encryptionAlgorithm, keySize);
- sk = util.generateKey();
- KeyStore.SecretKeyEntry skEntry = new KeyStore.SecretKeyEntry(sk);
- try {
- keystore.setEntry(alias, skEntry, new KeyStore.PasswordProtection(keyStorePWD));
- adminKey = sk;
- saveKeyStoreToFile(keystoreURL);
- }
- catch (KeyStoreException e) {
- throw PicketBoxMessages.MESSAGES.noSecretKeyandAliasAlreadyUsed(alias);
- }
- catch (Exception e) {
- throw PicketBoxMessages.MESSAGES.unableToStoreKeyStoreToFile(e, keystoreURL);
- }
- }
- }
-
- private void writeVaultData() throws IOException
- {
- FileOutputStream fos = null;
- ObjectOutputStream oos = null;
- try
- {
- fos = new FileOutputStream(decodedEncFileDir + VAULT_CONTENT_FILE);
- oos = new ObjectOutputStream(fos);
- oos.writeObject(vaultContent);
- }
- finally
- {
- safeClose(oos);
- safeClose(fos);
- }
- }
-
- private boolean vaultFileExists(String fileName)
- {
- File file = new File(this.decodedEncFileDir + fileName);
- return file != null && file.exists();
- }
-
- private boolean directoryExists(String dir)
- {
- File file = new File(dir);
- return file != null && file.exists();
- }
-
- private void safeClose(InputStream fis)
- {
- try
- {
- if(fis != null)
- {
- fis.close();
- }
- }
- catch(Exception e)
- {}
- }
+ SecretKeySpec secretKeySpec = new SecretKeySpec(adminKey.getEncoded(), encryptionAlgorithm);
+ EncryptionUtil encUtil = new EncryptionUtil(encryptionAlgorithm, keySize);
+ try {
+ return (new String(encUtil.decrypt(encryptedValue, secretKeySpec))).toCharArray();
+ } catch (Exception e) {
+ throw new SecurityVaultException(e);
+ }
+ }
- private void safeClose(OutputStream os)
- {
- try
- {
- if(os != null)
- {
- os.close();
- }
- }
- catch(Exception e)
- {}
- }
+ /**
+ * @see org.jboss.security.vault.SecurityVault#exists(String, String)
+ */
+ public boolean exists(String vaultBlock, String attributeName) throws SecurityVaultException {
+ return vaultContent.getVaultData().get(dataKey(vaultBlock, attributeName)) != null;
+ }
+ /*
+ * @see org.jboss.security.vault.SecurityVault#remove(java.lang.String, java.lang.String, byte[])
+ */
+ public boolean remove(String vaultBlock, String attributeName, byte[] sharedKey) throws SecurityVaultException {
+ try {
+ vaultContent.getVaultData().remove(dataKey(vaultBlock, attributeName));
+ } catch (Exception e) {
+ return false;
+ }
+ return true;
+ }
+
+ private String decode(String maskedString, String salt, int iterationCount) throws Exception {
+ String pbeAlgo = "PBEwithMD5andDES";
+ if (maskedString.startsWith(PASS_MASK_PREFIX)) {
+ // Create the PBE secret key
+ SecretKeyFactory factory = SecretKeyFactory.getInstance(pbeAlgo);
+
+ char[] password = "somearbitrarycrazystringthatdoesnotmatter".toCharArray();
+ PBEParameterSpec cipherSpec = new PBEParameterSpec(salt.getBytes(), iterationCount);
+ PBEKeySpec keySpec = new PBEKeySpec(password);
+ SecretKey cipherKey = factory.generateSecret(keySpec);
+
+ maskedString = maskedString.substring(PASS_MASK_PREFIX.length());
+ String decodedValue = PBEUtils.decode64(maskedString, pbeAlgo, cipherKey, cipherSpec);
+
+ maskedString = decodedValue;
+ }
+ return maskedString;
+ }
+
+ private void setUpVault(String keystoreURL, String decodedEncFileDir) throws NoSuchAlgorithmException, IOException {
+ vaultContent = new SecurityVaultData(new ConcurrentHashMap<String, byte[]>());
+ writeVaultData();
+
+ SecretKey sk = getAdminKey();
+ if (sk != null) {
+ adminKey = sk;
+ } else {
+ // try to generate new admin key and store it under specified alias
+ EncryptionUtil util = new EncryptionUtil(encryptionAlgorithm, keySize);
+ sk = util.generateKey();
+ KeyStore.SecretKeyEntry skEntry = new KeyStore.SecretKeyEntry(sk);
+ try {
+ keystore.setEntry(alias, skEntry, new KeyStore.PasswordProtection(keyStorePWD));
+ adminKey = sk;
+ saveKeyStoreToFile(keystoreURL);
+ } catch (KeyStoreException e) {
+ throw PicketBoxMessages.MESSAGES.noSecretKeyandAliasAlreadyUsed(alias);
+ } catch (Exception e) {
+ throw PicketBoxMessages.MESSAGES.unableToStoreKeyStoreToFile(e, keystoreURL);
+ }
+ }
+ }
+
+ private void writeVaultData() throws IOException {
+ FileOutputStream fos = null;
+ ObjectOutputStream oos = null;
+ try {
+ fos = new FileOutputStream(decodedEncFileDir + VAULT_CONTENT_FILE);
+ oos = new ObjectOutputStream(fos);
+ oos.writeObject(vaultContent);
+ } finally {
+ safeClose(oos);
+ safeClose(fos);
+ }
+ }
+
+ private boolean vaultFileExists(String fileName) {
+ File file = new File(this.decodedEncFileDir + fileName);
+ return file != null && file.exists();
+ }
+
+ private boolean directoryExists(String dir) {
+ File file = new File(dir);
+ return file != null && file.exists();
+ }
+
+ private void safeClose(InputStream fis) {
+ try {
+ if (fis != null) {
+ fis.close();
+ }
+ } catch (Exception e) {
+ }
+ }
+
+ private void safeClose(OutputStream os) {
+ try {
+ if (os != null) {
+ os.close();
+ }
+ } catch (Exception e) {
+ }
+ }
+
private void readVaultContent(String keystoreURL, String encFileDir) throws SecurityVaultException {
try {
@@ -429,102 +382,105 @@
}
- @SuppressWarnings("unchecked")
- private void convertVaultContent(String keystoreURL, String alias) throws Exception {
- FileInputStream fis = null;
- ObjectInputStream ois = null;
- Map<String, byte[]> theContent;
-
- try {
- fis = new FileInputStream(decodedEncFileDir + ENCODED_FILE);
- ois = new ObjectInputStream(fis);
- theContent = (Map<String, byte[]>) ois.readObject();
- } finally {
- safeClose(fis);
- safeClose(ois);
- }
-
- Map<String, byte[]> newVault = new ConcurrentHashMap<String, byte[]>();
-
- adminKey = null;
- for (String key: theContent.keySet()) {
- if (key.equals(ADMIN_KEY)) {
- byte[] admin_key = theContent.get(key);
- adminKey = new SecretKeySpec(admin_key, encryptionAlgorithm);
- }
- else {
- if (key.contains("_")) {
- StringTokenizer tokenizer = new StringTokenizer(key, "_");
- String vaultBlock = tokenizer.nextToken();
- String attributeName = tokenizer.nextToken();
- if (tokenizer.hasMoreTokens()) {
- attributeName = key.substring(vaultBlock.length() + 1);
- PicketBoxLogger.LOGGER.ambiguosKeyForSecurityVaultTransformation("_", vaultBlock, attributeName);
- }
- byte[] encodedAttributeValue = theContent.get(key);
- newVault.put(dataKey(vaultBlock, attributeName), encodedAttributeValue);
- }
- }
- }
- if (adminKey == null) {
- throw PicketBoxMessages.MESSAGES.missingAdminKeyInOriginalVaultData();
- }
-
- // create new transformed vault data
- vaultContent = new SecurityVaultData(newVault);
-
- // convert keystore to JCEKS format
- convertKeyStoreToJCEKS();
-
- // add secret key (admin_key) to keystore
- KeyStore.SecretKeyEntry skEntry = new KeyStore.SecretKeyEntry(adminKey);
- keystore.setEntry(alias, skEntry, new KeyStore.PasswordProtection(keyStorePWD));
+ @SuppressWarnings("unchecked")
+ private void convertVaultContent(String keystoreURL, String alias) throws Exception {
+ FileInputStream fis = null;
+ ObjectInputStream ois = null;
+ Map<String, byte[]> theContent;
- // backup original keystore file
- copyFile(new File(keystoreURL), new File(keystoreURL + ".original"));
- // save the current keystore
- saveKeyStoreToFile(keystoreURL);
+ try {
+ fis = new FileInputStream(decodedEncFileDir + ENCODED_FILE);
+ ois = new ObjectInputStream(fis);
+ theContent = (Map<String, byte[]>) ois.readObject();
+ } finally {
+ safeClose(fis);
+ safeClose(ois);
+ }
+
+ Map<String, byte[]> newVault = new ConcurrentHashMap<String, byte[]>();
+
+ adminKey = null;
+ for (String key : theContent.keySet()) {
+ if (key.equals(ADMIN_KEY)) {
+ byte[] admin_key = theContent.get(key);
+ adminKey = new SecretKeySpec(admin_key, encryptionAlgorithm);
+ } else {
+ if (key.contains("_")) {
+ StringTokenizer tokenizer = new StringTokenizer(key, "_");
+ String vaultBlock = tokenizer.nextToken();
+ String attributeName = tokenizer.nextToken();
+ if (tokenizer.hasMoreTokens()) {
+ attributeName = key.substring(vaultBlock.length() + 1);
+ PicketBoxLogger.LOGGER.ambiguosKeyForSecurityVaultTransformation("_", vaultBlock, attributeName);
+ }
+ byte[] encodedAttributeValue = theContent.get(key);
+ newVault.put(dataKey(vaultBlock, attributeName), encodedAttributeValue);
+ }
+ }
+ }
+ if (adminKey == null) {
+ throw PicketBoxMessages.MESSAGES.missingAdminKeyInOriginalVaultData();
+ }
+
+ // create new transformed vault data
+ vaultContent = new SecurityVaultData(newVault);
+
+ // convert keystore to JCEKS format
+ convertKeyStoreToJCEKS();
+
+ // add secret key (admin_key) to keystore
+ KeyStore.SecretKeyEntry skEntry = new KeyStore.SecretKeyEntry(adminKey);
+ keystore.setEntry(alias, skEntry, new KeyStore.PasswordProtection(keyStorePWD));
+
+ // backup original keystore file
+ copyFile(new File(keystoreURL), new File(keystoreURL + ".original"));
+ // save the current keystore
+ saveKeyStoreToFile(keystoreURL);
+
+ // backup original vault files
+ copyFile(new File(decodedEncFileDir + ENCODED_FILE), new File(decodedEncFileDir + ENCODED_FILE + ".original"));
+ copyFile(new File(decodedEncFileDir + SHARED_KEY_FILE), new File(decodedEncFileDir + SHARED_KEY_FILE + ".original"));
+
+ // delete original vault files
+ File f = new File(decodedEncFileDir + ENCODED_FILE);
+ if (!f.delete()) {
+ PicketBoxLogger.LOGGER.cannotDeleteOriginalVaultFile(f.getCanonicalPath());
+ }
+ f = new File(decodedEncFileDir + SHARED_KEY_FILE);
+ if (!f.delete()) {
+ PicketBoxLogger.LOGGER.cannotDeleteOriginalVaultFile(f.getCanonicalPath());
+ }
+
+ }
+
+ private void saveKeyStoreToFile(String keystoreURL) throws Exception {
+ keystore.store(new FileOutputStream(new File(keystoreURL)), keyStorePWD);
+ }
+
+ private void convertKeyStoreToJCEKS() throws Exception {
+ if (keystore.getType().equalsIgnoreCase("JKS")) {
+ createKeyStore("JCEKS");
+ }
+ }
- // backup original vault files
- copyFile(new File(decodedEncFileDir + ENCODED_FILE), new File(decodedEncFileDir + ENCODED_FILE + ".original"));
- copyFile(new File(decodedEncFileDir + SHARED_KEY_FILE), new File(decodedEncFileDir + SHARED_KEY_FILE + ".original"));
+ private KeyStore createKeyStore(String keyStoreType) throws Exception {
+ KeyStore ks = KeyStore.getInstance(keyStoreType);
+ ks.load(null, keyStorePWD);
+ return ks;
+ }
- // delete original vault files
- File f = new File(decodedEncFileDir + ENCODED_FILE);
- if (!f.delete()) {
- PicketBoxLogger.LOGGER.cannotDeleteOriginalVaultFile(f.getCanonicalPath());
- }
- f = new File(decodedEncFileDir + SHARED_KEY_FILE);
- if (!f.delete()) {
- PicketBoxLogger.LOGGER.cannotDeleteOriginalVaultFile(f.getCanonicalPath());
- }
-
- }
+ /**
+ * Creates new format for data key in vault. All parameters has to be non-null.
+ *
+ * @param vaultBlock
+ * @param attributeName
+ * @param alias
+ * @return
+ */
+ public static String dataKey(String vaultBlock, String attributeName) {
+ return vaultBlock + StringUtil.PROPERTY_DEFAULT_SEPARATOR + attributeName;
+ }
- private void saveKeyStoreToFile(String keystoreURL) throws Exception {
- keystore.store(new FileOutputStream(new File(keystoreURL)), keyStorePWD);
- }
-
-
- private void convertKeyStoreToJCEKS() throws Exception {
- if (keystore.getType().equalsIgnoreCase("JKS")) {
- keystore = KeyStore.getInstance("JCEKS");
- keystore.load(null, keyStorePWD);
- }
- }
-
- /**
- * Creates new format for data key in vault. All parameters has to be non-null.
- *
- * @param vaultBlock
- * @param attributeName
- * @param alias
- * @return
- */
- public static String dataKey(String vaultBlock, String attributeName) {
- return vaultBlock + StringUtil.PROPERTY_DEFAULT_SEPARATOR + attributeName;
- }
-
private void readVersionedVaultContent() throws Exception {
FileInputStream fis = null;
ObjectInputStream ois = null;
@@ -536,39 +492,38 @@
safeClose(fis);
safeClose(ois);
}
-
+
adminKey = getAdminKey();
if (adminKey == null) {
throw PicketBoxMessages.MESSAGES.vaultDoesnotContainSecretKey(alias);
- }
+ }
}
-
+
/**
- * Returns SecretKey stored in defined keystore under defined alias.
- * If no such SecretKey exists returns null.
+ * Returns SecretKey stored in defined keystore under defined alias. If no such SecretKey exists returns null.
+ *
* @return
*/
private SecretKey getAdminKey() {
try {
Entry e = keystore.getEntry(alias, new KeyStore.PasswordProtection(keyStorePWD));
if (e instanceof KeyStore.SecretKeyEntry) {
- return ((KeyStore.SecretKeyEntry)e).getSecretKey();
+ return ((KeyStore.SecretKeyEntry) e).getSecretKey();
}
- }
- catch (Exception e) {
+ } catch (Exception e) {
PicketBoxLogger.LOGGER.vaultDoesnotContainSecretKey(alias);
return null;
}
return null;
}
-
- /**
- * Copy file method.
- *
- * @param sourceFile
- * @param destFile
- * @throws IOException
- */
+
+ /**
+ * Copy file method.
+ *
+ * @param sourceFile
+ * @param destFile
+ * @throws IOException
+ */
public static void copyFile(File sourceFile, File destFile) throws IOException {
if (!destFile.exists()) {
destFile.createNewFile();
@@ -601,4 +556,33 @@
}
}
}
+
+
+ /**
+ * Get key store based on options passed to PicketBoxSecurityVault.
+ * @return
+ */
+ private KeyStore getKeyStore(String keystoreURL) {
+
+ try {
+ return KeyStoreUtil.getKeyStore(keyStoreType, keystoreURL, keyStorePWD);
+ }
+ catch (IOException e) {
+ // deliberately empty
+ }
+ catch (GeneralSecurityException e) {
+ throw PicketBoxMessages.MESSAGES.unableToGetKeyStore(e, keystoreURL);
+ }
+
+ try {
+ if (createKeyStore) {
+ return createKeyStore(keyStoreType);
+ }
+ }
+ catch (Throwable e) {
+ throw PicketBoxMessages.MESSAGES.unableToGetKeyStore(e, keystoreURL);
+ }
+
+ return null;
+ }
}
\ No newline at end of file
More information about the jboss-cvs-commits
mailing list