Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * JBoss, Home of Professional Open Source.
   * Copyright 2013, Red Hat, Inc., and individual contributors
   * as indicated by the @author tags. See the copyright.txt file in the
   * distribution for a full listing of individual contributors.
   *
   * This is free software; you can redistribute it and/or modify it
   * under the terms of the GNU Lesser General Public License as
   * published by the Free Software Foundation; either version 2.1 of
  * the License, or (at your option) any later version.
  *
  * This software is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with this software; if not, write to the Free
  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
  */
 
 package org.wildfly.test.security;
 
 import java.io.File;
 
 
VaultHandler is a handler for PicketBox Security Vault associated files. It can be used one-to-one with vault. It can create required keystore and after action delete all vault data files. It should be used for testing purpose only.

Author(s):
Peter Skopek (pskopek at redhat dot com)
 
 public class VaultHandler {
 
     private static Logger LOGGER = Logger.getLogger(VaultHandler.class);
 
     public static final String ENC_DAT_FILE = "ENC.dat";
     public static final String SHARED_DAT_FILE = "Shared.dat";
     public static final String VAULT_DAT_FILE = "VAULT.dat";
     public static final String DEFAULT_KEYSTORE_FILE = "vault.keystore";
 
     private String encodedVaultFileDirectory;
     private String keyStoreType;
     private String keyStore;
     private String keyStorePassword;
     private int keySize = 128;
     private String alias = "defaultalias";
     private String salt;
     private int iterationCount;
 
     private VaultSession vaultSession;
 
     private static String FILE_SEPARATOR = System.getProperty("file.separator");
     private static String TMP_DIR = System.getProperty("java.io.tmpdir");
     private static String DEFAULT_PASSWORD = "super_secret";

    
Create vault with all required files. It is the most complete constructor. If keyStore doesn't exist it will be created with specified keyStoreType and encryption directory will be created if not existent.

Parameters:
keyStore
keyStorePassword
keyStoreType - JCEKS, JKS or null
encodedVaultFileDirectory
keySize
alias
salt
iterationCount
 
     public VaultHandler(String keyStoreString keyStorePasswordString keyStoreTypeString encodedVaultFileDirectory,
             int keySizeString aliasString saltint iterationCount) {
 
         if (alias != null) {
             this. = alias;
         }
 
         if (keySize != 0) {
             this. = keySize;
         }
 
         if (keyStoreType == null) {
             this. = "JCEKS";
         } else {
             if (!keyStoreType.equals("JCEKS") && !keyStoreType.equals("JKS")) {
                 throw new IllegalArgumentException("Wrong keyStoreType. Supported are only (JCEKS or JKS). Preferred is JCEKS.");
             }
             this. = keyStoreType;
        }
        if (keyStorePassword == null) {
            this. = ;
        } else if (keyStorePassword.startsWith(.)) {
            throw new IllegalArgumentException("keyStorePassword cannot be a masked password, use plain text password, please");
        } else {
            this. = keyStorePassword;
        }
        try {
            File keyStoreFile = new File(keyStore);
            if (!keyStoreFile.exists()) {
                if (!this..equals("JCEKS")) {
                    throw new RuntimeException("keyStoreType has to be JCEKS when creating new key store");
                }
                File keyStoreParent = keyStoreFile.getAbsoluteFile().getParentFile();
                if (keyStoreParent != null) {
                    if (!keyStoreParent.exists()) {
                        assert keyStoreParent.mkdirs();
                    } else {
                        assert keyStoreParent.isDirectory();
                    }
                }
                KeyStore ks = KeyStoreUtil.createKeyStore(this.this..toCharArray());
                KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
                keyGenerator.init(this.);
                SecretKey secretKey = keyGenerator.generateKey();
                KeyStore.SecretKeyEntry skEntry = new KeyStore.SecretKeyEntry(secretKey);
                KeyStore.PasswordProtection p = new KeyStore.PasswordProtection(this..toCharArray());
                ks.setEntry(this.skEntryp);
                ks.store(new FileOutputStream(keyStoreFile), this..toCharArray());
            }
            this. = keyStoreFile.getAbsolutePath();
        } catch (Exception e) {
            throw new RuntimeException("Problem creating keyStore: "e);
        }
        File vaultDirectory = new File(encodedVaultFileDirectory).getAbsoluteFile();
        if (!vaultDirectory.exists()) {
            assert vaultDirectory.mkdirs();
        } else if (!vaultDirectory.isDirectory()) {
            throw new RuntimeException("Vault encryption directory has to be directory, but "
                    + vaultDirectory.getAbsolutePath() + " is not.");
        }
        this. = vaultDirectory.getAbsolutePath();
        if (salt == null) {
            String tmp = Long.toHexString(System.currentTimeMillis())
                    + Long.toHexString(System.currentTimeMillis())
                    + Long.toHexString(System.currentTimeMillis())
                    + Long.toHexString(System.currentTimeMillis());
            this. = tmp.substring(0, 8);
        } else {
            this. = salt;
        }
        if (iterationCount <= 0) {
            this. = new Random().nextInt(90) + 1;
        } else {
            this. = iterationCount;
        }
        if (.isDebugEnabled()) {
            logCreatedVault();
        }
        try {
            this. = new VaultSession(this.this.this.,
                    this.this.);
            this..startVaultSession(this.);
        } catch (Exception e) {
            throw new RuntimeException("Problem creating VaultSession: "e);
        }
        .debug("VaultSession started");
    }

    
Constructor with all default values, but keyStore and encodedVaultFileDirectory.

Parameters:
keyStore
encodedVaultFileDirectory
    public VaultHandler(String keyStoreString encodedVaultFileDirectory) {
        this(keyStorenullnullencodedVaultFileDirectory, 0, nullnull, 0);
    }

    
Constructor with all default values, but encodedVaultFileDirectory.

Parameters:
encodedVaultFileDirectory
    public VaultHandler(String encodedVaultFileDirectory) {
        this(getDefaultKeystoreFile(encodedVaultFileDirectory), encodedVaultFileDirectory);
    }

    
Constructor with all default values.
    public VaultHandler() {
        this();
    }
    public String getMaskedKeyStorePassword() {
        if ( != null) {
            return .getKeystoreMaskedPassword();
        } else {
            throw new RuntimeException("getMaskedKeyStorePassword: Vault inside this handler is not initialized or created");
        }
    }
    public String addSecuredAttribute(String vaultBlockString attributeNamechar[] attributeValue) {
        if ( != null) {
            try {
                return .addSecuredAttribute(vaultBlockattributeNameattributeValue);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else {
            throw new RuntimeException("addSecuredAttribute: Vault inside this handler is not initialized or created");
        }
    }
    public boolean exists(String vaultBlockString attributeName) {
        if ( != null) {
            try {
                return .checkSecuredAttribute(vaultBlockattributeName);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else {
            throw new RuntimeException("exists: Vault inside this handler is not initialized or created");
        }
    }

    
Return VaultSession for further vault manipulation when needed.

Returns:
    public VaultSession getVaultSession() {
        return ;
    }

    
Delete all associated vault files and keystore. After this action VaultHandler is not usable anymore.
    public void cleanUp() {
         = null;
    }
        return ;
    }
    public String getKeyStoreType() {
        return ;
    }
    public String getKeyStore() {
        return ;
    }
    public int getKeySize() {
        return ;
    }
    public String getAlias() {
        return ;
    }
    public String getSalt() {
        return ;
    }
    public String getKeyStorePassword() {
        return ;
    }
    public int getIterationCount() {
        return ;
    }
    public String getIterationCountAsString() {
        return Integer.toString();
    }
    private void logCreatedVault() {
        .debug("keystoreURL="+);
        .debug("KEYSTORE_PASSWORD="+);
        .debug("ENC_FILE_DIR="+);
        .debug("KEYSTORE_ALIAS="+);
        .debug("SALT="+);
        .debug("ITERATION_COUNT="+);
    }
    private static String getDefaultKeystoreFile(String encodedVaultFileDirectory) {
        return encodedVaultFileDirectory +  + ;
    }

    
Removes vault files from the given directory, with the assumption that the key store is located inside the directory in a file named DEFAULT_KEYSTORE_FILE.

Parameters:
encodedVaultFileDirectory the path of the directory
removeEncodedVaultFileDirectory true if the directory itself should be removed
    public static void cleanFilesystem(String encodedVaultFileDirectoryboolean removeEncodedVaultFileDirectory) {
        cleanFilesystem(encodedVaultFileDirectoryremoveEncodedVaultFileDirectorygetDefaultKeystoreFile(encodedVaultFileDirectory));
    }

    
Removes vault files from the given directory, and also removes the given key store file.

Parameters:
encodedVaultFileDirectory the path of the directory
removeEncodedVaultFileDirectory true if the directory itself should be removed
keyStore the path of the key store
    public static void cleanFilesystem(String encodedVaultFileDirectoryboolean removeEncodedVaultFileDirectoryString keyStore) {
        cleanFilesystem(new File(encodedVaultFileDirectory), removeEncodedVaultFileDirectorynew File(keyStore));
    }
    private static void cleanFilesystem(File encodedVaultFileDirectoryboolean removeEncodedVaultFileDirectory,
                                        File keyStore) {
        deleteIfExists(keyStore);
        File f = new File(keyStore.getParent(), keyStore.getName() + ".original");
        deleteIfExists(f);
        if (removeEncodedVaultFileDirectory) {
            deleteDirectory(encodedVaultFileDirectory);
        } else {
            cleanEncodedVaultFileDirectory(encodedVaultFileDirectory);
        }
    }
    private static void deleteDirectory(File f) {
        File[] children = f.isDirectory() ? f.listFiles() : null;
        if (children != null) {
            for (File child : children) {
                deleteDirectory(child);
            }
        }
        deleteIfExists(f);
    }
    private static void cleanEncodedVaultFileDirectory(File encodedVaultFileDirectory) {
        File f = new File(encodedVaultFileDirectory);
        deleteIfExists(f);
        f = new File(encodedVaultFileDirectory);
        deleteIfExists(f);
        f = new File(encodedVaultFileDirectory + ".original");
        deleteIfExists(f);
        f = new File(encodedVaultFileDirectory);
        deleteIfExists(f);
        // there might be a KEYSTORE_README file in the directory as a placeholder
        f = new File(encodedVaultFileDirectory"KEYSTORE_README");
        deleteIfExists(f);
    }
    private static void deleteIfExists(File f) {
        assert !f.exists() || f.delete();
    }
New to GrepCode? Check out our FAQ X