You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@synapse.apache.org by in...@apache.org on 2008/07/03 20:55:11 UTC

svn commit: r673760 - in /synapse/trunk/java: modules/core/src/main/java/org/apache/synapse/security/ modules/core/src/main/java/org/apache/synapse/security/bean/ modules/core/src/main/java/org/apache/synapse/security/secret/ modules/core/src/main/java...

Author: indika
Date: Thu Jul  3 11:55:10 2008
New Revision: 673760

URL: http://svn.apache.org/viewvc?rev=673760&view=rev
Log:
Add initial implementation of the securing passwords.
Add a  initial implementation of a tool for encrypting  and decrypting.  
Add common-cli as it needs tool

Added:
    synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/
    synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/bean/
    synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/bean/CipherInformation.java
    synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/bean/KeyStoreInformation.java
    synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/secret/
    synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/secret/SecretManager.java
    synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/secret/SecretRepository.java
    synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/secret/repository/
    synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/secret/repository/FileBaseSecretRepository.java
    synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/tool/
    synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/tool/CipherTool.java
    synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/wrappers/
    synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/wrappers/CipherWrapper.java
    synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/wrappers/IdentityKeyStoreWrapper.java
    synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/wrappers/KeyStoreWrapper.java
    synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/wrappers/TrustKeyStoreWrapper.java
    synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/util/MiscellaneousUtil.java
    synapse/trunk/java/repository/conf/cipher-text.properties
    synapse/trunk/java/repository/conf/secret-manager.properties
Modified:
    synapse/trunk/java/src/main/assembly/bin.xml

Added: synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/bean/CipherInformation.java
URL: http://svn.apache.org/viewvc/synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/bean/CipherInformation.java?rev=673760&view=auto
==============================================================================
--- synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/bean/CipherInformation.java (added)
+++ synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/bean/CipherInformation.java Thu Jul  3 11:55:10 2008
@@ -0,0 +1,83 @@
+/*
+*  Licensed to the Apache Software Foundation (ASF) under one
+*  or more contributor license agreements.  See the NOTICE file
+*  distributed with this work for additional information
+*  regarding copyright ownership.  The ASF licenses this file
+*  to you under the Apache License, Version 2.0 (the
+*  "License"); you may not use this file except in compliance
+*  with the License.  You may obtain a copy of the License at
+*
+*   http://www.apache.org/licenses/LICENSE-2.0
+*
+*  Unless required by applicable law or agreed to in writing,
+*  software distributed under the License is distributed on an
+*   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+*  KIND, either express or implied.  See the License for the
+*  specific language governing permissions and limitations
+*  under the License.
+*/
+package org.apache.synapse.security.bean;
+
+/**
+ * Encapsulates the cipher related information
+ */
+public class CipherInformation {
+
+    private static String DEFAULT_ALGORITHM = "RSA";
+    private String algorithm = DEFAULT_ALGORITHM;
+    private String operationMode;
+    private String mode;
+    private String inType;
+    private String outType;
+    private String type;
+
+    public String getAlgorithm() {
+        return algorithm;
+    }
+
+    public void setAlgorithm(String algorithm) {
+        if (this.algorithm != null) {
+            this.algorithm = algorithm;
+        }
+    }
+
+    public String getOperationMode() {
+        return operationMode;
+    }
+
+    public void setOperationMode(String operationMode) {
+        this.operationMode = operationMode;
+    }
+
+    public String getMode() {
+        return mode;
+    }
+
+    public void setMode(String mode) {
+        this.mode = mode;
+    }
+
+    public String getType() {
+        return type;
+    }
+
+    public void setType(String type) {
+        this.type = type;
+    }
+
+    public String getInType() {
+        return inType;
+    }
+
+    public void setInType(String inType) {
+        this.inType = inType;
+    }
+
+    public String getOutType() {
+        return outType;
+    }
+
+    public void setOutType(String outType) {
+        this.outType = outType;
+    }
+}

Added: synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/bean/KeyStoreInformation.java
URL: http://svn.apache.org/viewvc/synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/bean/KeyStoreInformation.java?rev=673760&view=auto
==============================================================================
--- synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/bean/KeyStoreInformation.java (added)
+++ synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/bean/KeyStoreInformation.java Thu Jul  3 11:55:10 2008
@@ -0,0 +1,55 @@
+/*
+*  Licensed to the Apache Software Foundation (ASF) under one
+*  or more contributor license agreements.  See the NOTICE file
+*  distributed with this work for additional information
+*  regarding copyright ownership.  The ASF licenses this file
+*  to you under the Apache License, Version 2.0 (the
+*  "License"); you may not use this file except in compliance
+*  with the License.  You may obtain a copy of the License at
+*
+*   http://www.apache.org/licenses/LICENSE-2.0
+*
+*  Unless required by applicable law or agreed to in writing,
+*  software distributed under the License is distributed on an
+*   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+*  KIND, either express or implied.  See the License for the
+*  specific language governing permissions and limitations
+*  under the License.
+*/
+package org.apache.synapse.security.bean;
+
+/**
+ * Encapsulates the keyStore related information
+ */
+public class KeyStoreInformation {
+
+    private String storeType;
+    private String alias;
+    private String location;
+
+
+    public String getStoreType() {
+        return storeType;
+    }
+
+    public void setStoreType(String storeType) {
+        this.storeType = storeType;
+    }
+
+    public String getAlias() {
+        return alias;
+    }
+
+    public void setAlias(String alias) {
+        this.alias = alias;
+    }
+
+    public String getLocation() {
+        return location;
+    }
+
+    public void setLocation(String location) {
+        this.location = location;
+    }
+
+}

Added: synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/secret/SecretManager.java
URL: http://svn.apache.org/viewvc/synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/secret/SecretManager.java?rev=673760&view=auto
==============================================================================
--- synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/secret/SecretManager.java (added)
+++ synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/secret/SecretManager.java Thu Jul  3 11:55:10 2008
@@ -0,0 +1,165 @@
+/**
+ *
+ */
+package org.apache.synapse.security.secret;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.SynapseException;
+import org.apache.synapse.security.bean.KeyStoreInformation;
+import org.apache.synapse.security.secret.repository.FileBaseSecretRepository;
+import org.apache.synapse.security.wrappers.IdentityKeyStoreWrapper;
+import org.apache.synapse.security.wrappers.TrustKeyStoreWrapper;
+import org.apache.synapse.util.MiscellaneousUtil;
+
+import java.util.Properties;
+
+/**
+ * Entry point for manage secrets
+ */
+public class SecretManager {
+
+    private static Log log = LogFactory.getLog(SecretManager.class);
+
+    private static SecretManager ourInstance = new SecretManager();
+
+    private final static String DEFAULT_CONF_LOCATION = "secret-manager.properties";
+    private final static String SECRET_MANAGER_CONF = "secret-manage-conf";
+    private final static String SECRET_REPOSITORIES = "secretRepositories";
+    private final static String TYPE = "type";
+    private final static String IDENTITY_KEY_STORE = "keystore.identity.location";
+    private final static String IDENTITY_KEY_STORE_TYPE = "keystore.identity.type";
+    private final static String IDENTITY_KEY_STORE_ALIAS = "keystore.identity.alias";
+    private final static String TRUST_KEY_STORE = "keystore.trust.location";
+    private final static String TRUST_KEY_STORE_TYPE = "keystore.trust.type";
+    private final static String TRUST_KEY_STORE_ALIAS = "keystore.trust.alias";
+    private final static String DOT = ".";
+    private final static String REPO_TYPE_FILE = "file";
+
+    private SecretRepository parentRepository;
+    private boolean initialize = false;
+
+    public static SecretManager getInstance() {
+        return ourInstance;
+    }
+
+    private SecretManager() {
+    }
+
+    /**
+     * Initializes the Secret Manager .Paswords for both trusted and private keyStores have to be
+     * provided separately due to security reasons
+     *
+     * @param properties        Configuration properties for manager except passwords
+     * @param identityStorePass Password to access private  keyStore
+     * @param identityKeyPass   Password to access private or secret keys
+     * @param trustStorePass    Password to access trusted KeyStore
+     */
+    public void init(Properties properties, String identityStorePass, String identityKeyPass, String trustStorePass) {
+
+        String configurationFile = MiscellaneousUtil.getProperty(
+                properties, SECRET_MANAGER_CONF, DEFAULT_CONF_LOCATION);
+
+        Properties configurationProperties = MiscellaneousUtil.loadProperties(configurationFile);
+        if (configurationProperties == null || configurationProperties.isEmpty()) {
+            if (log.isDebugEnabled()) {
+                log.debug("Configuration properties can not be loaded form : " + configurationFile);
+            }
+            return;
+
+        }
+
+        String repositoriesString = MiscellaneousUtil.getProperty(
+                configurationProperties, SECRET_REPOSITORIES, null);
+        if (repositoriesString == null || "".equals(repositoriesString)) {
+            if (log.isDebugEnabled()) {
+                log.debug("No secret repositories have been configured");
+            }
+            return;
+        }
+
+        String[] repositories = repositoriesString.split(",");
+        if (repositories == null || repositories.length == 0) {
+            if (log.isDebugEnabled()) {
+                log.debug("No secret repositories have been configured");
+            }
+            return;
+        }
+
+        KeyStoreInformation keyStoreInformation = new KeyStoreInformation();
+
+        keyStoreInformation.setAlias(
+                MiscellaneousUtil.getProperty(configurationProperties, IDENTITY_KEY_STORE_ALIAS, null));
+        keyStoreInformation.setLocation(
+                MiscellaneousUtil.getProperty(configurationProperties, IDENTITY_KEY_STORE, null));
+        keyStoreInformation.setStoreType(
+                MiscellaneousUtil.getProperty(configurationProperties, IDENTITY_KEY_STORE_TYPE, null));
+
+        KeyStoreInformation trustInformation = new KeyStoreInformation();
+
+        trustInformation.setAlias(
+                MiscellaneousUtil.getProperty(configurationProperties, TRUST_KEY_STORE, null));
+        trustInformation.setLocation(
+                MiscellaneousUtil.getProperty(configurationProperties, TRUST_KEY_STORE_ALIAS, null));
+        trustInformation.setStoreType(
+                MiscellaneousUtil.getProperty(configurationProperties, TRUST_KEY_STORE_TYPE, null));
+
+        IdentityKeyStoreWrapper identityKeyStoreWrapper = new IdentityKeyStoreWrapper();
+        identityKeyStoreWrapper.init(keyStoreInformation, identityStorePass, identityKeyPass);
+
+        TrustKeyStoreWrapper trustStoreWrapper = new TrustKeyStoreWrapper();
+        trustStoreWrapper.init(keyStoreInformation, trustStorePass);
+
+        SecretRepository currentParent = null;
+        for (String secretRepo : repositories) {
+
+            StringBuffer sb = new StringBuffer();
+            sb.append(SECRET_REPOSITORIES);
+            sb.append(DOT);
+            sb.append(secretRepo);
+            String id = sb.toString();
+            sb.append(DOT);
+            sb.append(TYPE);
+
+            String type = MiscellaneousUtil.getProperty(
+                    configurationProperties, sb.toString(), null);
+            if (type == null || "".equals(type)) {
+                handleException("Repository type cannot be null ");
+            }
+
+            if (REPO_TYPE_FILE.equals(type)) {
+                SecretRepository secretRepository = new FileBaseSecretRepository(
+                        identityKeyStoreWrapper, trustStoreWrapper);
+                secretRepository.init(configurationProperties, id);
+                if (parentRepository == null) {
+                    parentRepository = secretRepository;
+                }
+                secretRepository.setParent(currentParent);
+                currentParent = secretRepository;
+                initialize = true;
+            } else {
+                log.warn("Unsupported secret sepository type : " + type);
+            }
+
+        }
+
+    }
+
+    /**
+     * Returns the secret corresponding to the given alias name
+     *
+     * @param alias The logical or alias name
+     * @return If there is a secret , otherwise , alias itself
+     */
+    public String getSecret(String alias) {
+        if (!initialize || parentRepository == null) {
+            return alias;
+        }
+        return parentRepository.getSecret(alias);
+    }
+
+    private void handleException(String msg) {
+        log.error(msg);
+        throw new SynapseException(msg);
+    }
+}

Added: synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/secret/SecretRepository.java
URL: http://svn.apache.org/viewvc/synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/secret/SecretRepository.java?rev=673760&view=auto
==============================================================================
--- synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/secret/SecretRepository.java (added)
+++ synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/secret/SecretRepository.java Thu Jul  3 11:55:10 2008
@@ -0,0 +1,43 @@
+package org.apache.synapse.security.secret;
+
+import java.util.Properties;
+
+/**
+ * Represents the abstraction 'Repository of secret'
+ * Implementation can be any type - file,jdbc
+ */
+public interface SecretRepository {
+    /**
+     * Initializes the repository based on provided properties
+     *
+     * @param properties Configuration properties
+     * @param id         Identifier to identify properties related to the corresponding repository
+     */
+    void init(Properties properties, String id);
+
+    /**
+     * Returns the secret of provided alias name . An alias represents the logical name
+     * for a lookup secret
+     *
+     * @param alias Alias name for look up a secret
+     * @return Secret if there is any , otherwise ,alias itself
+     */
+    String getSecret(String alias);
+
+    /**
+     * Sets the parent secret repository
+     * Secret Repositories are made a chain so that , one can get a secret from other.
+     * For example, JDBC password can be in file based secret repository
+     *
+     * @param parent Parent secret repository
+     */
+    void setParent(SecretRepository parent);
+
+    /**
+     * Returns the parent secret repository
+     *
+     * @return Parent secret repository
+     */
+    SecretRepository getParent();
+
+}

Added: synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/secret/repository/FileBaseSecretRepository.java
URL: http://svn.apache.org/viewvc/synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/secret/repository/FileBaseSecretRepository.java?rev=673760&view=auto
==============================================================================
--- synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/secret/repository/FileBaseSecretRepository.java (added)
+++ synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/secret/repository/FileBaseSecretRepository.java Thu Jul  3 11:55:10 2008
@@ -0,0 +1,209 @@
+/*
+*  Licensed to the Apache Software Foundation (ASF) under one
+*  or more contributor license agreements.  See the NOTICE file
+*  distributed with this work for additional information
+*  regarding copyright ownership.  The ASF licenses this file
+*  to you under the Apache License, Version 2.0 (the
+*  "License"); you may not use this file except in compliance
+*  with the License.  You may obtain a copy of the License at
+*
+*   http://www.apache.org/licenses/LICENSE-2.0
+*
+*  Unless required by applicable law or agreed to in writing,
+*  software distributed under the License is distributed on an
+*   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+*  KIND, either express or implied.  See the License for the
+*  specific language governing permissions and limitations
+*  under the License.
+*/
+package org.apache.synapse.security.secret.repository;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.security.bean.CipherInformation;
+import org.apache.synapse.security.secret.SecretRepository;
+import org.apache.synapse.security.tool.CipherTool;
+import org.apache.synapse.security.wrappers.CipherWrapper;
+import org.apache.synapse.security.wrappers.IdentityKeyStoreWrapper;
+import org.apache.synapse.security.wrappers.TrustKeyStoreWrapper;
+import org.apache.synapse.util.MiscellaneousUtil;
+
+import java.io.ByteArrayInputStream;
+import java.security.PublicKey;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+
+/**
+ * Holds all secrets in a file
+ */
+public class FileBaseSecretRepository implements SecretRepository {
+
+    private static Log log = LogFactory.getLog(FileBaseSecretRepository.class);
+
+    private final static String LOCATION = "location";
+    private final static String KEY_STORE = "keyStore";
+    private final static String DOT = ".";
+    private final static String SECRET = "secret";
+    private final static String ALIASES = "aliases";
+    private final static String ALGORITHM = "algorithm";
+    private final static String DEFAULT_ALGORITHM = "RSA";
+    private final static String TRUSTED = "trusted";
+    private final static String DEFAULT_CONF_LOCATION = "cipher-text.properties";
+
+    private SecretRepository parentRepository;
+
+    private final Map secrets = new HashMap();
+    private IdentityKeyStoreWrapper identity;
+    private TrustKeyStoreWrapper trust;
+    private boolean initialize = false;
+
+    public FileBaseSecretRepository(IdentityKeyStoreWrapper wrapper, TrustKeyStoreWrapper trust) {
+        this.identity = wrapper;
+        this.trust = trust;
+    }
+
+    /**
+     * Initializes the repository based on provided properties
+     *
+     * @param properties Configuration properties
+     * @param id         Identifier to identify properties related to the corresponding repository
+     */
+    public void init(Properties properties, String id) {
+        StringBuffer sb = new StringBuffer();
+        sb.append(id);
+        sb.append(DOT);
+        sb.append(LOCATION);
+
+        String filePath = MiscellaneousUtil.getProperty(properties,
+                sb.toString(), DEFAULT_CONF_LOCATION);
+
+        Properties cipherProperties = MiscellaneousUtil.loadProperties(filePath);
+        if (cipherProperties == null) {
+            if (log.isDebugEnabled()) {
+                log.debug("Cipher texts cannot be loaded form : " + filePath);
+            }
+            return;
+        }
+
+        String aliasesString = MiscellaneousUtil.getProperty(cipherProperties, ALIASES, null);
+        if (aliasesString == null || "".equals(aliasesString)) {
+            if (log.isDebugEnabled()) {
+                log.debug("There are no alias names in the cipher text file");
+            }
+            return;
+        }
+
+        String[] aliases = aliasesString.split(",");
+        if (aliases == null) {
+            if (log.isDebugEnabled()) {
+                log.debug("There are no alias names in the cipher text file");
+            }
+            return;
+        }
+
+        for (String alias : aliases) {
+
+            StringBuffer buffer = new StringBuffer();
+            buffer.append(alias);
+            buffer.append(DOT);
+            buffer.append(SECRET);
+            String propKey = buffer.toString();
+
+            String secret = MiscellaneousUtil.getProperty(cipherProperties, propKey, null);
+            if (secret == null || "".equals(secret)) {
+                if (log.isDebugEnabled()) {
+                    log.debug("No secret found for alias name " + alias);
+                }
+                continue;
+            }
+            buffer.append(DOT);
+            buffer.append(KEY_STORE);
+            String keyStorePropertyKey = buffer.toString();
+
+            //Load keyStore
+            String keyStore = MiscellaneousUtil.getProperty(cipherProperties, keyStorePropertyKey, null);
+
+            StringBuffer sbTwo = new StringBuffer();
+            sbTwo.append(propKey);
+            sbTwo.append(DOT);
+            sbTwo.append(ALGORITHM);
+            //Load algorithm
+            String algorithm = MiscellaneousUtil.getProperty(cipherProperties,
+                    sbTwo.toString(), DEFAULT_ALGORITHM);
+
+            StringBuffer sbThree = new StringBuffer();
+            sbThree.append(propKey);
+            sbThree.append(DOT);
+            sbThree.append(CipherTool.ALIAS);
+
+            //Loads the alias of a certificate
+            String aliasOfCert = MiscellaneousUtil.getProperty(
+                    cipherProperties, sbThree.toString(), null);
+
+            PublicKey key;
+            if (TRUSTED.equals(keyStore)) {
+                if (aliasOfCert == null) {
+                    key = trust.getPublicKey();
+                } else {
+                    key = trust.getPublicKey(aliasOfCert);
+                }
+            } else {
+                if (aliasOfCert == null) {
+                    key = identity.getPublicKey();
+                } else {
+                    key = identity.getPublicKey(aliasOfCert);
+                }
+            }
+            //Creates a cipherInformation
+            CipherInformation cipherInformation = new CipherInformation();
+            cipherInformation.setAlgorithm(algorithm);
+            cipherInformation.setOperationMode(CipherTool.DECRYPT);
+            cipherInformation.setInType(CipherTool.BASE64);
+
+            //Creates a cipher
+            CipherWrapper cipherWrapper = new CipherWrapper(cipherInformation, key);
+
+            ByteArrayInputStream in = new ByteArrayInputStream(secret.getBytes());
+            String decryptedText = cipherWrapper.getSecret(in);
+            secrets.put(propKey, decryptedText);
+            initialize = true;
+        }
+    }
+
+    public String getSecret(String alias) {
+
+        if (alias == null || "".equals(alias)) {
+            return alias; // TODO is it need to throw an error?
+        }
+
+        if (!initialize || secrets.isEmpty()) {
+            if (log.isDebugEnabled()) {
+                log.debug("There is no secret found for alias '" + alias + "' returning itself");
+            }
+            return alias;
+        }
+
+        StringBuffer sb = new StringBuffer();
+        sb.append(alias);
+        sb.append(DOT);
+        sb.append(SECRET);
+
+        String secret = (String) secrets.get(sb.toString());
+        if (secret == null || "".equals(secret)) {
+            if (log.isDebugEnabled()) {
+                log.debug("There is no secret found for alias '" + alias + "' returning itself");
+            }
+            return alias;
+        }
+        return secret;
+    }
+
+    public void setParent(SecretRepository parent) {
+        this.parentRepository = parent;
+    }
+
+    public SecretRepository getParent() {
+        return this.parentRepository;
+    }
+}

Added: synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/tool/CipherTool.java
URL: http://svn.apache.org/viewvc/synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/tool/CipherTool.java?rev=673760&view=auto
==============================================================================
--- synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/tool/CipherTool.java (added)
+++ synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/tool/CipherTool.java Thu Jul  3 11:55:10 2008
@@ -0,0 +1,335 @@
+/*
+*  Licensed to the Apache Software Foundation (ASF) under one
+*  or more contributor license agreements.  See the NOTICE file
+*  distributed with this work for additional information
+*  regarding copyright ownership.  The ASF licenses this file
+*  to you under the Apache License, Version 2.0 (the
+*  "License"); you may not use this file except in compliance
+*  with the License.  You may obtain a copy of the License at
+*
+*   http://www.apache.org/licenses/LICENSE-2.0
+*
+*  Unless required by applicable law or agreed to in writing,
+*  software distributed under the License is distributed on an
+*   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+*  KIND, either express or implied.  See the License for the
+*  specific language governing permissions and limitations
+*  under the License.
+*/
+package org.apache.synapse.security.tool;
+
+import org.apache.commons.cli.*;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.SynapseException;
+import org.apache.synapse.security.bean.CipherInformation;
+import org.apache.synapse.security.bean.KeyStoreInformation;
+import org.apache.synapse.security.wrappers.CipherWrapper;
+import org.apache.synapse.security.wrappers.IdentityKeyStoreWrapper;
+import org.apache.synapse.security.wrappers.TrustKeyStoreWrapper;
+
+import java.io.*;
+import java.security.Key;
+
+/**
+ * Tool for encrypting and decrypting.
+ * Arguments and their meanings
+ * <ul>
+ * <li>keystore     If keys are in a store ,it's location
+ * <li>storepass    Password for access keyStore
+ * <li>keypass      To get private key
+ * <li>alias        Alias to identify key owner
+ * <li>storetype    Type of keyStore
+ * <li>keyfile      If key is in a file
+ * <li>opmode       encrypt or decrypt
+ * <li>algorithm    encrypt or decrypt algorithm
+ * <li>source       Either cipher or plain text as an in-lined form
+ * <li>sourceFile   Source from a file
+ * <li>outEncode    Currently base64
+ * <li>inEncode     Currently base64
+ * <ul>
+ */
+public class CipherTool {
+
+    private static Log log = LogFactory.getLog(CipherTool.class);
+
+    /* The argument name for KeyStore location */
+    public static String KEY_STORE = "keystore";
+    /* The KeyStore type*/
+    public static String STORE_TYPE = "storetype";
+    /* The argument name for password to access KeyStore*/
+    public static String STORE_PASS = "storepass";
+    /* The argument name for password for access private key */
+    public static String KEY_PASS = "keypass";
+    /* The alias to identify key owner */
+    public static String ALIAS = "alias";
+
+    /* If the key is from a file , then it's location*/
+    public static String KEY_FILE = "keyfile";
+
+    /* The algorithm for encrypting or decrypting */
+    public static String ALGORITHM = "algorithm";
+    /* The operation mode of cihper - encrypt or decrypt */
+    public static String OP_MODE = "opmode";
+    /* The cipher type - asymmetric , symmetric */
+    public static String CIPHER_TYPE = "ciphertype";
+
+    /* The cipher or plain text as an in-lined */
+    public static String SOURCE_IN_LINED = "source";
+    /* The the source from a file*/
+    public static String SOURCE_FILE = "sourcefile";
+    /* If  the target has to be written to a file*/
+    public static String TARGET_FILE = "targetfile";
+    /* If  the output of cipher operation need to be encode - only base64*/
+    public static String OUT_TYPE = "outtype";
+    /* If  the encode of the input type base64*/
+    public static String IN_TYPE = "intype";
+    /* Is this keyStore a trusted one */
+    public static String TRUSTED = "trusted";
+
+    /* Operation mode */
+    public static String ENCRYPT = "encrypt";
+    public static String DECRYPT = "decrypt";
+
+    public static String BASE64 = "base64";
+
+    public static void main(String args[]) throws Exception {
+
+        // loads the options
+        Options options = getOptions();
+        // create the command line parser
+        CommandLineParser parser = new GnuParser();
+        // parse the command line arguments
+        try {
+            CommandLine cmd = parser.parse(options, args);
+            // Loads the cipher relate information
+            CipherInformation cipherInformation = getCipherInformation(cmd);
+            // Loads the keyStore relate information
+            KeyStoreInformation keyStoreInformation = getKeyStoreInformation(cmd);
+            //Key information must not contain any password
+            //Password for access KeyStore
+            String storePass = getArgument(cmd, STORE_PASS);
+            //Password for access private key
+            String keyPass = getArgument(cmd, KEY_PASS);
+            // If Key need to be loaded from a file
+            String keyFile = getArgument(cmd, KEY_FILE);
+            // Source  as an in-lined
+            String source = getArgument(cmd, SOURCE_IN_LINED);
+
+            boolean isTrusted = isArgumentPresent(cmd, TRUSTED);
+
+            Key key;
+            if (keyFile != null) {
+                key = getKey(keyFile);
+            } else {
+                if (isTrusted) {
+                    TrustKeyStoreWrapper trustKeyStoreWrapper = new TrustKeyStoreWrapper();
+                    trustKeyStoreWrapper.init(keyStoreInformation, storePass);
+                    key = trustKeyStoreWrapper.getPublicKey();
+                } else {
+                    IdentityKeyStoreWrapper storeWrapper = new IdentityKeyStoreWrapper();
+                    storeWrapper.init(keyStoreInformation, storePass, keyPass);
+                    if (ENCRYPT.equals(cipherInformation.getOperationMode())) {
+                        key = storeWrapper.getPrivateKey();
+                    } else {
+                        key = storeWrapper.getPublicKey();
+                    }
+                }
+            }
+
+            if (key == null) {
+                handleException("Cannot find a key ");
+            }
+
+            CipherWrapper cipherWrapper = new CipherWrapper(cipherInformation, key);
+            ByteArrayInputStream in = new ByteArrayInputStream(source.getBytes());
+
+            System.out.println("Output : " + cipherWrapper.getSecret(in));
+
+        } catch (ParseException e) {
+            handleException("Error passing arguments ", e);
+        }
+    }
+
+    /**
+     * Utility method to extract command line arguments
+     *
+     * @param cmd     Command line which capture all command line arguments
+     * @param argName Name of the argument to be extracted
+     * @return value of the argument if there is , o.w null
+     */
+    private static String getArgument(CommandLine cmd, String argName) {
+
+        if (cmd == null) {
+            handleException("CommandLine is null");
+        }
+
+        if (argName == null || "".equals(argName)) {
+            if (log.isDebugEnabled()) {
+                log.debug("Provided argument name is null. Returning null as value");
+            }
+            return null;
+        }
+
+        if (cmd.hasOption(argName)) {
+            return cmd.getOptionValue(argName);
+        }
+        return null;
+    }
+
+    /**
+     * Utility method to find boolean argument
+     *
+     * @param cmd     Command line which capture all command line arguments
+     * @param argName Name of the argument to be extracted
+     * @return True if presents
+     */
+    private static boolean isArgumentPresent(CommandLine cmd, String argName) {
+        if (cmd == null) {
+            handleException("CommandLine is null");
+        }
+
+        if (argName == null || "".equals(argName)) {
+            if (log.isDebugEnabled()) {
+                log.debug("Provided argument name is null. Returning null as value");
+            }
+            return false;
+        }
+
+        return cmd.hasOption(argName);
+    }
+
+    /**
+     * Factory method to construct @see CipherInformation from command line options
+     *
+     * @param cmd Command line which capture all command line arguments
+     * @return CipherInformation object
+     */
+    private static CipherInformation getCipherInformation(CommandLine cmd) {
+
+        CipherInformation information = new CipherInformation();
+        information.setAlgorithm(getArgument(cmd, ALGORITHM));
+        information.setOperationMode(getArgument(cmd, OP_MODE));
+        information.setInType(getArgument(cmd, IN_TYPE));
+        information.setOutType(getArgument(cmd, OUT_TYPE));
+        information.setType(getArgument(cmd, CIPHER_TYPE));
+        return information;
+
+    }
+
+    /**
+     * Factoyr method to create a @see keyStoreInformation from command line options
+     *
+     * @param cmd Command line which capture all command line arguments
+     * @return KeyStoreInformation object
+     */
+    private static KeyStoreInformation getKeyStoreInformation(CommandLine cmd) {
+
+        KeyStoreInformation information = new KeyStoreInformation();
+        information.setAlias(getArgument(cmd, ALIAS));
+        information.setLocation(getArgument(cmd, KEY_STORE));
+        information.setStoreType(getArgument(cmd, STORE_TYPE));
+        return information;
+
+    }
+
+    /**
+     * Factory method to create options
+     *
+     * @return Options object
+     */
+    private static Options getOptions() {
+
+        Options options = new Options();
+
+        Option keyStore = new Option(KEY_STORE, true, "Private key entry KeyStore");
+        Option storeType = new Option(STORE_TYPE, true, " KeyStore type");
+        Option storePassword = new Option(STORE_PASS, true, "Password for keyStore access");
+        Option keyPassword = new Option(KEY_PASS, true, "Password for access private key entry");
+        Option alias = new Option(ALIAS, true, "Alias name for identify key owner");
+        Option trusted = new Option(TRUSTED, false, "Is this KeyStore trusted one");
+
+        Option keyFile = new Option(KEY_FILE, true, "private key from a file");
+        Option cipherType = new Option(CIPHER_TYPE, true, "Cipher type");
+        Option opMode = new Option(OP_MODE, true, "encrypt or decrypt");
+
+        Option algorithm = new Option(ALGORITHM, true, "Algorithm to be used");
+        Option source = new Option(SOURCE_IN_LINED, true, "Plain text in-lined");
+        Option sourceFile = new Option(SOURCE_FILE, true, "Plain text from a file");
+        Option targetFile = new Option(TARGET_FILE, true, "Target file");
+        Option outType = new Option(OUT_TYPE, true, "encode type for output");
+        Option intType = new Option(IN_TYPE, true, "encode type of input source");
+
+        options.addOption(keyStore);
+        options.addOption(storeType);
+        options.addOption(storePassword);
+        options.addOption(keyPassword);
+        options.addOption(alias);
+        options.addOption(trusted);
+
+        options.addOption(keyFile);
+
+        options.addOption(algorithm);
+        options.addOption(cipherType);
+        options.addOption(opMode);
+
+        options.addOption(source);
+        options.addOption(sourceFile);
+        options.addOption(targetFile);
+        options.addOption(outType);
+        options.addOption(intType);
+
+        return options;
+    }
+
+    /**
+     * Factory method to retrieve a previously stored key in a file
+     *
+     * @param filePath Path to file
+     * @return Retrieved key
+     */
+    private static Key getKey(String filePath) {
+
+        if (filePath == null || "".equals(filePath)) {
+            handleException("File path cannot be empty or null");
+        }
+
+        File keyFile = new File(filePath);
+        if (!keyFile.exists()) {
+            handleException("File cannot be found in : " + filePath);
+        }
+
+        ObjectInputStream in = null;
+        try {
+            in = new ObjectInputStream(new FileInputStream(keyFile));
+            Object object = in.readObject();
+            if (object instanceof Key) {
+                return (Key) object;
+            }
+
+        } catch (IOException e) {
+            handleException("Error reading ", e);
+        } catch (ClassNotFoundException e) {
+            handleException("Canot load a key from the file" + filePath, e);
+        } finally {
+            if (in != null) {
+                try {
+                    in.close();
+                } catch (IOException ignored) {
+                }
+            }
+        }
+        return null;
+    }
+
+    private static void handleException(String msg, Exception e) {
+        log.error(msg, e);
+        throw new SynapseException(msg, e);
+    }
+
+    private static void handleException(String msg) {
+        log.error(msg);
+        throw new SynapseException(msg);
+    }
+
+}

Added: synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/wrappers/CipherWrapper.java
URL: http://svn.apache.org/viewvc/synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/wrappers/CipherWrapper.java?rev=673760&view=auto
==============================================================================
--- synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/wrappers/CipherWrapper.java (added)
+++ synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/wrappers/CipherWrapper.java Thu Jul  3 11:55:10 2008
@@ -0,0 +1,150 @@
+/*
+*  Licensed to the Apache Software Foundation (ASF) under one
+*  or more contributor license agreements.  See the NOTICE file
+*  distributed with this work for additional information
+*  regarding copyright ownership.  The ASF licenses this file
+*  to you under the Apache License, Version 2.0 (the
+*  "License"); you may not use this file except in compliance
+*  with the License.  You may obtain a copy of the License at
+*
+*   http://www.apache.org/licenses/LICENSE-2.0
+*
+*  Unless required by applicable law or agreed to in writing,
+*  software distributed under the License is distributed on an
+*   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+*  KIND, either express or implied.  See the License for the
+*  specific language governing permissions and limitations
+*  under the License.
+*/
+package org.apache.synapse.security.wrappers;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.SynapseException;
+import org.apache.synapse.security.bean.CipherInformation;
+import org.apache.synapse.security.tool.CipherTool;
+import sun.misc.BASE64Decoder;
+import sun.misc.BASE64Encoder;
+
+import javax.crypto.Cipher;
+import javax.crypto.CipherOutputStream;
+import javax.crypto.NoSuchPaddingException;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.security.InvalidKeyException;
+import java.security.Key;
+import java.security.NoSuchAlgorithmException;
+
+/**
+ * Wraps the cipher and expose abstraction need for synapse ciphering
+ */
+public class CipherWrapper {
+
+    private static Log log = LogFactory.getLog(CipherWrapper.class);
+
+    /* Underlying cipher instance*/
+    private Cipher cipher;
+    /* Bean containing information required for cipher */
+    private CipherInformation information;
+
+    /**
+     * Cipher needs a key and some information to work. Therefore, constructs the cipher with
+     * providing those
+     *
+     * @param information Encapsulated object contains all information required to cipher
+     * @param key         The key that will be used by the cipher either for encryption and secryption
+     */
+    public CipherWrapper(CipherInformation information, Key key) {
+        this.information = information;
+        String algorithm = information.getAlgorithm();
+        String opMode = information.getOperationMode();
+
+        if (log.isDebugEnabled()) {
+            log.debug("Initializing cipher with algorithm " +
+                    "'" + algorithm + "' in mode '" + opMode + "'");
+        }
+        try {
+            cipher = Cipher.getInstance(algorithm);
+            if (CipherTool.ENCRYPT.equals(opMode)) {
+                cipher.init(Cipher.ENCRYPT_MODE, key);
+            } else if (CipherTool.DECRYPT.equals(opMode)) {
+                cipher.init(Cipher.DECRYPT_MODE, key);
+            } else {
+                handleException("Invalid mode : " + opMode);
+            }
+
+        } catch (NoSuchAlgorithmException e) {
+            handleException("There is no algorithm support for " +
+                    "'" + algorithm + "' in the operation mode '" + opMode + "'" + e);
+        } catch (NoSuchPaddingException e) {
+            handleException("There is no padding scheme  for " +
+                    "'" + algorithm + "' in the operation mode '" + opMode + "'" + e);
+        } catch (InvalidKeyException e) {
+            handleException("Invalid key ", e);
+        }
+    }
+
+    /**
+     * Returns the output of the cipher operation.
+     * This expose the 'getSecret' abstraction and hide operation of the underlying cipher
+     *
+     * @param inputStream Input as a stream. This can be either cipher or plain text
+     * @return Secret as String.This can be either cipher or plain text
+     */
+    public String getSecret(InputStream inputStream) {
+
+        if (CipherTool.BASE64.equals(information.getInType())) {
+            try {
+                if (log.isDebugEnabled()) {
+                    log.debug("base64 decoding on input  ");
+                }
+                inputStream = new ByteArrayInputStream(
+                        new BASE64Decoder().decodeBuffer(inputStream));
+            } catch (IOException e) {
+                handleException("Error decoding input ", e);
+            }
+        }
+
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        CipherOutputStream out = new CipherOutputStream(baos, cipher);
+
+        byte[] buffer = new byte[8];
+        int length;
+        try {
+            while ((length = inputStream.read(buffer)) != -1) {
+                out.write(buffer, 0, length);
+            }
+        } catch (IOException e) {
+            handleException("IOError !! ", e);
+        } finally {
+            try {
+                inputStream.close();
+                out.close();
+                out.flush();
+            } catch (IOException ignored) {
+
+            }
+        }
+
+        if (CipherTool.BASE64.equals(information.getOutType())) {
+            if (log.isDebugEnabled()) {
+                log.debug("base64 encoding on output ");
+            }
+            return new BASE64Encoder().encode(baos.toByteArray());
+        } else {
+            return baos.toString();
+        }
+    }
+
+    private static void handleException(String msg, Exception e) {
+        log.error(msg, e);
+        throw new SynapseException(msg, e);
+    }
+
+    private static void handleException(String msg) {
+        log.error(msg);
+        throw new SynapseException(msg);
+    }
+}

Added: synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/wrappers/IdentityKeyStoreWrapper.java
URL: http://svn.apache.org/viewvc/synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/wrappers/IdentityKeyStoreWrapper.java?rev=673760&view=auto
==============================================================================
--- synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/wrappers/IdentityKeyStoreWrapper.java (added)
+++ synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/wrappers/IdentityKeyStoreWrapper.java Thu Jul  3 11:55:10 2008
@@ -0,0 +1,98 @@
+/*
+*  Licensed to the Apache Software Foundation (ASF) under one
+*  or more contributor license agreements.  See the NOTICE file
+*  distributed with this work for additional information
+*  regarding copyright ownership.  The ASF licenses this file
+*  to you under the Apache License, Version 2.0 (the
+*  "License"); you may not use this file except in compliance
+*  with the License.  You may obtain a copy of the License at
+*
+*   http://www.apache.org/licenses/LICENSE-2.0
+*
+*  Unless required by applicable law or agreed to in writing,
+*  software distributed under the License is distributed on an
+*   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+*  KIND, either express or implied.  See the License for the
+*  specific language governing permissions and limitations
+*  under the License.
+*/
+package org.apache.synapse.security.wrappers;
+
+import org.apache.synapse.security.bean.KeyStoreInformation;
+
+import javax.crypto.SecretKey;
+import java.security.Key;
+import java.security.PrivateKey;
+
+/**
+ * Represents the private keyStore entry
+ * To provide that abstraction , this class exposes both getter methods to public, private and secret keys
+ */
+public class IdentityKeyStoreWrapper extends KeyStoreWrapper {
+
+    /**
+     * @param information   @see KeyStoreWrapper
+     * @param storePassword @see KeyStoreWrapper
+     * @param keyPassword   @see KeyStoreWrapper
+     * @see org.apache.synapse.security.wrappers.KeyStoreWrapper
+     */
+    public void init(KeyStoreInformation information, String storePassword, String keyPassword) {
+        super.init(information, storePassword, keyPassword);
+    }
+
+    /**
+     * Returns the private or secret  key based on given password and alias
+     *
+     * @param alias       The alias of the certificate in the specified keyStore
+     * @param keyPassword Password to access private key
+     * @return PrivateKey if there is a one , otherwise null
+     */
+    public PrivateKey getPrivateKey(String alias, String keyPassword) {
+        Key key = super.getKey(alias, keyPassword);
+        if (key instanceof PrivateKey) {
+            return (PrivateKey) key;
+        }
+        return null;
+    }
+
+    /**
+     * Returns the private key based on initilization data
+     *
+     * @return PrivateKey if there is a one , otherwise null
+     */
+    public PrivateKey getPrivateKey() {
+        Key key = super.getKey();
+        if (key instanceof PrivateKey) {
+            return (PrivateKey) key;
+        }
+        return null;
+    }
+
+    /**
+     * Returns the secret key
+     *
+     * @param alias       The alias of the certificate in the specified keyStore
+     * @param keyPassword Password to access secret key
+     * @return SecretKey if there is a one , otherwise null
+     */
+    public SecretKey getSecretKey(String alias, String keyPassword) {
+        Key key = super.getKey(alias, keyPassword);
+        if (key instanceof SecretKey) {
+            return (SecretKey) key;
+        }
+        return null;
+    }
+
+    /**
+     * Returns the secret key based on initilization data
+     *
+     * @return SecretKey if there is a one , otherwise null
+     */
+    public SecretKey getSecretKey() {
+        Key key = super.getKey();
+        if (key instanceof SecretKey) {
+            return (SecretKey) key;
+        }
+        return null;
+    }
+}

Added: synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/wrappers/KeyStoreWrapper.java
URL: http://svn.apache.org/viewvc/synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/wrappers/KeyStoreWrapper.java?rev=673760&view=auto
==============================================================================
--- synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/wrappers/KeyStoreWrapper.java (added)
+++ synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/wrappers/KeyStoreWrapper.java Thu Jul  3 11:55:10 2008
@@ -0,0 +1,199 @@
+/*
+*  Licensed to the Apache Software Foundation (ASF) under one
+*  or more contributor license agreements.  See the NOTICE file
+*  distributed with this work for additional information
+*  regarding copyright ownership.  The ASF licenses this file
+*  to you under the Apache License, Version 2.0 (the
+*  "License"); you may not use this file except in compliance
+*  with the License.  You may obtain a copy of the License at
+*
+*   http://www.apache.org/licenses/LICENSE-2.0
+*
+*  Unless required by applicable law or agreed to in writing,
+*  software distributed under the License is distributed on an
+*   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+*  KIND, either express or implied.  See the License for the
+*  specific language governing permissions and limitations
+*  under the License.
+*/
+package org.apache.synapse.security.wrappers;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.SynapseException;
+import org.apache.synapse.security.bean.KeyStoreInformation;
+
+import java.io.BufferedInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.security.*;
+import java.security.cert.Certificate;
+import java.security.cert.CertificateException;
+
+/**
+ * Wraps the keyStore and provide abstraction need for ciphering in the synapse.
+ */
+public abstract class KeyStoreWrapper {
+    protected Log log;
+    /* Bean that encapsulates the information about KeyStore */
+    private KeyStoreInformation keyStoreInformation;
+    /* Underlying KeyStore */
+    private KeyStore keyStore;
+    /* Password to access private key entries*/
+    private String keyPassword;
+
+    protected KeyStoreWrapper() {
+        log = LogFactory.getLog(this.getClass());
+    }
+
+    /**
+     * Initialize the KeyStore wrapper based on provided KeyStoreinformation and passwords
+     *
+     * @param information   The object that has encapsulated all information for a
+     *                      keyStore excepts passwords
+     * @param storePassword Specifies the password for the keyStore file
+     * @param keyPassword   Specifies the password of the key within the keyStore
+     */
+    protected void init(KeyStoreInformation information, String storePassword, String keyPassword) {
+
+        if (information == null) {
+            handleException("KeyStore information cannot be found");
+        }
+
+        if (storePassword == null || "".equals(storePassword)) {
+            handleException("KeyStore password need to be provided ");
+        }
+
+        this.keyStoreInformation = information;
+        this.keyPassword = keyPassword;
+
+        String store = information.getLocation();
+        File keyStoreFile = new File(store);
+        if (!keyStoreFile.exists()) {
+            handleException("KeyStore can not be found at ' " + keyStoreFile + " '");
+        }
+
+        String storeType = information.getStoreType();
+        BufferedInputStream bis = null;
+        try {
+            if (log.isDebugEnabled()) {
+                log.debug("Loading KeyStore form : " + store);
+            }
+            bis = new BufferedInputStream(new FileInputStream(keyStoreFile));
+            keyStore = KeyStore.getInstance(storeType);
+            keyStore.load(bis, storePassword.toCharArray());
+
+        } catch (KeyStoreException e) {
+            handleException("Error loading keyStore from ' " + store + " ' ", e);
+        } catch (IOException e) {
+            handleException("IOError loading keyStore from ' " + store + " ' ", e);
+        } catch (NoSuchAlgorithmException e) {
+            handleException("Error loading keyStore from ' " + store + " ' ", e);
+        } catch (CertificateException e) {
+            handleException("Error loading keyStore from ' " + store + " ' ", e);
+        } finally {
+            if (bis != null) {
+                try {
+                    bis.close();
+                } catch (IOException ignored) {
+                }
+            }
+        }
+
+    }
+
+    /**
+     * Returns the key based on provided alias and key password
+     *
+     * @param alias       The alias of the certificate in the specified keyStore
+     * @param keyPassword Password for key within the KeyStrore
+     * @return Key if there is a one , otherwise null
+     */
+    protected Key getKey(String alias, String keyPassword) {
+
+        if (alias == null || "".equals(alias)) {
+            handleException("The alias need to provided to get certificate");
+        }
+        if (keyPassword != null) {
+            try {
+                return keyStore.getKey(alias, keyPassword.toCharArray());
+            } catch (KeyStoreException e) {
+                handleException("Error loading key for alias : " + alias, e);
+            } catch (NoSuchAlgorithmException e) {
+                handleException("Error loading key for alias : " + alias, e);
+            } catch (UnrecoverableKeyException e) {
+                handleException("Error loading key for alias : " + alias, e);
+            }
+        }
+        return null;
+    }
+
+    /**
+     * Returns the key based on certificate of the owner to who given alias belong
+     *
+     * @param alias The alias of the certificate in the specified keyStore
+     * @return Key , if there is a one , otherwise null
+     */
+    protected Key getKey(String alias) {
+        try {
+            Certificate certificate = keyStore.getCertificate(alias);
+            if (certificate != null) {
+                return certificate.getPublicKey();
+            }
+        } catch (KeyStoreException e) {
+            handleException("Error loading key for alias : " + alias, e);
+        }
+        return null;
+    }
+
+    /**
+     * Retunrs the key based on default alias or password
+     *
+     * @return Key , if there is a one , otherwise null
+     */
+    protected Key getKey() {
+        if (keyPassword != null) {
+            return getKey(keyStoreInformation.getAlias(), keyPassword);
+        } else {
+            return getKey(keyStoreInformation.getAlias());
+        }
+    }
+
+    /**
+     * Returns the public key for the given alias
+     *
+     * @param alias The alias of the certificate in the specified keyStore
+     * @return PublicKey if there is a one , otherwise null
+     */
+    public PublicKey getPublicKey(String alias) {
+        Key key = getKey(alias);
+        if (key instanceof PublicKey) {
+            return (PublicKey) key;
+        }
+        return null;
+    }
+
+    /**
+     * Returns the public key based on initilization data
+     *
+     * @return PublicKey if there is a one , otherwise null
+     */
+    public PublicKey getPublicKey() {
+        Key key = getKey();
+        if (key instanceof PublicKey) {
+            return (PublicKey) key;
+        }
+        return null;
+    }
+
+    protected void handleException(String msg, Exception e) {
+        log.error(msg, e);
+        throw new SynapseException(msg, e);
+    }
+
+    protected void handleException(String msg) {
+        log.error(msg);
+        throw new SynapseException(msg);
+    }
+}

Added: synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/wrappers/TrustKeyStoreWrapper.java
URL: http://svn.apache.org/viewvc/synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/wrappers/TrustKeyStoreWrapper.java?rev=673760&view=auto
==============================================================================
--- synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/wrappers/TrustKeyStoreWrapper.java (added)
+++ synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/security/wrappers/TrustKeyStoreWrapper.java Thu Jul  3 11:55:10 2008
@@ -0,0 +1,35 @@
+/*
+*  Licensed to the Apache Software Foundation (ASF) under one
+*  or more contributor license agreements.  See the NOTICE file
+*  distributed with this work for additional information
+*  regarding copyright ownership.  The ASF licenses this file
+*  to you under the Apache License, Version 2.0 (the
+*  "License"); you may not use this file except in compliance
+*  with the License.  You may obtain a copy of the License at
+*
+*   http://www.apache.org/licenses/LICENSE-2.0
+*
+*  Unless required by applicable law or agreed to in writing,
+*  software distributed under the License is distributed on an
+*   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+*  KIND, either express or implied.  See the License for the
+*  specific language governing permissions and limitations
+*  under the License.
+*/
+package org.apache.synapse.security.wrappers;
+
+import org.apache.synapse.security.bean.KeyStoreInformation;
+
+/**
+ * Represents the abstraction for trusted KeyStore
+ * Only expose to get public keys
+ */
+public class TrustKeyStoreWrapper extends KeyStoreWrapper {
+    /**
+     * @see org.apache.synapse.security.wrappers.KeyStoreWrapper
+     *      There is no keyPassword as trusted Store doesn't keep private or secret keys
+     */
+    public void init(KeyStoreInformation information, String storePassword) {
+        super.init(information, storePassword, null);
+    }
+}

Added: synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/util/MiscellaneousUtil.java
URL: http://svn.apache.org/viewvc/synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/util/MiscellaneousUtil.java?rev=673760&view=auto
==============================================================================
--- synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/util/MiscellaneousUtil.java (added)
+++ synapse/trunk/java/modules/core/src/main/java/org/apache/synapse/util/MiscellaneousUtil.java Thu Jul  3 11:55:10 2008
@@ -0,0 +1,111 @@
+/*
+*  Licensed to the Apache Software Foundation (ASF) under one
+*  or more contributor license agreements.  See the NOTICE file
+*  distributed with this work for additional information
+*  regarding copyright ownership.  The ASF licenses this file
+*  to you under the Apache License, Version 2.0 (the
+*  "License"); you may not use this file except in compliance
+*  with the License.  You may obtain a copy of the License at
+*
+*   http://www.apache.org/licenses/LICENSE-2.0
+*
+*  Unless required by applicable law or agreed to in writing,
+*  software distributed under the License is distributed on an
+*   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+*  KIND, either express or implied.  See the License for the
+*  specific language governing permissions and limitations
+*  under the License.
+*/
+package org.apache.synapse.util;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.SynapseConstants;
+import org.apache.synapse.SynapseException;
+
+import java.util.Properties;
+import java.io.InputStream;
+import java.io.File;
+import java.io.IOException;
+
+/**
+ *
+ */
+public class MiscellaneousUtil {
+    private static Log log = LogFactory.getLog(MiscellaneousUtil.class);
+
+    private MiscellaneousUtil() {
+    }
+
+    /**
+     * Helper method to get the value of the property from a given property bag
+     *
+     * @param dsProperties The property collection
+     * @param name         The name of the property
+     * @param def          The default value for the property
+     * @return The value of the property if it is found , otherwise , default value
+     */
+    public static String getProperty(Properties dsProperties, String name, String def) {
+
+        String result = dsProperties.getProperty(name);
+        if ((result == null || result.length() == 0 || "".equals(result)) && def != null) {
+            if (log.isDebugEnabled()) {
+                log.debug("The name with ' " + name + " ' cannot be found. " +
+                        "Using default value " + def);
+            }
+            result = def;
+        }
+        if (result != null) {
+            return result.trim();
+        } else {
+            return def;
+        }
+    }
+
+    /**
+     * Loads the properties from a given property file path
+     *
+     * @param filePath Path of the property file
+     * @return Properties loaded from given file
+     */
+    public static Properties loadProperties(String filePath) {
+
+        Properties properties = new Properties();
+        ClassLoader cl = Thread.currentThread().getContextClassLoader();
+
+        if (log.isDebugEnabled()) {
+            log.debug("Loading a file ' " + filePath + " ' from classpath");
+        }
+
+        InputStream in = cl.getResourceAsStream(filePath);
+        if (in == null) {
+            if (log.isDebugEnabled()) {
+                log.debug("Unable to load file  ' " + filePath + " '");
+            }
+
+            filePath = SynapseConstants.CONF_DIRECTORY +
+                    File.separatorChar + filePath;
+            if (log.isDebugEnabled()) {
+                log.debug("Loading a file ' " + filePath + " ' from classpath");
+            }
+
+            in = cl.getResourceAsStream(filePath);
+            if (in == null) {
+                if (log.isDebugEnabled()) {
+                    log.debug("Unable to load file  ' " + filePath + " '");
+                }
+            }
+        }
+        if (in != null) {
+            try {
+                properties.load(in);
+            } catch (IOException e) {
+                String msg = "Error loading properties from a file at :" + filePath;
+                log.error(msg, e);
+                throw new SynapseException(msg, e);
+            }
+        }
+        return properties;
+    }
+
+}

Added: synapse/trunk/java/repository/conf/cipher-text.properties
URL: http://svn.apache.org/viewvc/synapse/trunk/java/repository/conf/cipher-text.properties?rev=673760&view=auto
==============================================================================
--- synapse/trunk/java/repository/conf/cipher-text.properties (added)
+++ synapse/trunk/java/repository/conf/cipher-text.properties Thu Jul  3 11:55:10 2008
@@ -0,0 +1,7 @@
+#aliases=synapse,password
+#
+## configuration  per each plaintext
+#synapse.secret=EsY65tztE9R5b9pErVxLp8Br5d3ol6vRdWAkYHdc7XkZteGf37VJ+iNlCenqxYSEto0vcjpcmmzwf7K2wd9u3KQtVGKEoNLSe2LYZtrm3tKmGd6PX9YpdN72ml3JISNXPJ69yybFi6DVUIJfE5MFOd7gswWfCnkmZ3eJ6M1nuiI=
+#synapse.secret.algorithm=RSA
+#synapse.secret.alias=synapse
+#synapse.secret.keystore=identity

Added: synapse/trunk/java/repository/conf/secret-manager.properties
URL: http://svn.apache.org/viewvc/synapse/trunk/java/repository/conf/secret-manager.properties?rev=673760&view=auto
==============================================================================
--- synapse/trunk/java/repository/conf/secret-manager.properties (added)
+++ synapse/trunk/java/repository/conf/secret-manager.properties Thu Jul  3 11:55:10 2008
@@ -0,0 +1,12 @@
+#keystore.identity.location=lib/identity.jks
+#keystore.identity.type=JKS
+#keystore.identity.alias=synapse
+#
+#keystore.trust.location=lib/trust.jks
+#keystore.trust.type=JKS
+#keystore.trust.alias=synapse
+#
+#secretRepositories=file
+#
+#secretRepositories.file.type=file
+#secretRepositories.file.location=cipher-text.properties

Modified: synapse/trunk/java/src/main/assembly/bin.xml
URL: http://svn.apache.org/viewvc/synapse/trunk/java/src/main/assembly/bin.xml?rev=673760&r1=673759&r2=673760&view=diff
==============================================================================
--- synapse/trunk/java/src/main/assembly/bin.xml (original)
+++ synapse/trunk/java/src/main/assembly/bin.xml Thu Jul  3 11:55:10 2008
@@ -290,7 +290,7 @@
                 <exclude>axis:axis-ant:jar</exclude>
                 <exclude>javax.servlet:servlet-api:jar</exclude>
                 <exclude>commons-discovery:commons-discovery:jar</exclude>
-                <exclude>commons-cli:commons-cli:jar</exclude>
+                <!--<exclude>commons-cli:commons-cli:jar</exclude>-->
                 <exclude>org.apache.geronimo.specs:geronimo-javamail:jar</exclude>
                 <exclude>xml-apis:xml-apis:jar</exclude>
                 <exclude>xerces:xercesImpl:jar</exclude>