Fix sonar block in Encryption Tool 23/10923/2
authorSkip Wonnell <skip@att.com>
Thu, 7 Sep 2017 19:42:29 +0000 (14:42 -0500)
committerMarcus Williams <marcus.williams@intel.com>
Thu, 7 Sep 2017 22:45:06 +0000 (22:45 +0000)
Fix blockers and other Sonar findings.
Update license text

Issue-ID: APPC-186
Change-Id: Ib45020d85bde95f79b112ebd85fedfe62469b58f
Signed-off-by: Skip Wonnell <skip@att.com>
appc-config/appc-encryption-tool/provider/src/main/java/org/openecomp/appc/encryptiontool/wrapper/EncryptionTool.java
appc-config/appc-encryption-tool/provider/src/main/java/org/openecomp/appc/encryptiontool/wrapper/EncryptionToolDGWrapper.java
appc-config/appc-encryption-tool/provider/src/main/java/org/openecomp/appc/encryptiontool/wrapper/WrapperEncryptionTool.java

index 3a1b25f..934eb9c 100644 (file)
@@ -1,9 +1,11 @@
 /*-
  * ============LICENSE_START=======================================================
- * ONAP : APP-C
+ * ONAP : APPC
  * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property.  All rights reserved.
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
+ * Copyright (C) 2017 Amdocs
+ * =============================================================================
  * Licensed 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
  * 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.
+ * 
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.appc.encryptiontool.wrapper;
 
 import java.security.Provider;
 import java.security.Provider.Service;
 import java.security.Security;
 
-import javax.crypto.Cipher;
-
 import org.jasypt.contrib.org.apache.commons.codec_1_3.binary.Base64;
-import org.jasypt.util.text.BasicTextEncryptor;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
- * This class is used to encapsulate the encryption and decryption support in one place and to provide a utility to
- * encrypt and decrypt data.
+ * This class is used to encapsulate the encryption and decryption support in one place and to
+ * provide a utility to encrypt and decrypt data.
  */
 public class EncryptionTool {
 
     /**
-     * This lock object is used ONLY if the singleton has not been set up.
-     */
-    private static final Object lock = new Object();
-
-    /**
-     * The salt is used to initialize the PBE (password Based Encrpytion) algorithm.
+     * The prefix we insert onto any data we encrypt so that we can tell if it is encrpyted later and
+     * therefore decrypt it
      */
-    private static final byte[] DEFAULT_SALT = {
-        (byte) 0xc7, (byte) 0x73, (byte) 0x21, (byte) 0x8c, (byte) 0x7e, (byte) 0xc8, (byte) 0xee, (byte) 0x99
-    };
-
-    /**
-     * The prefix we insert onto any data we encrypt so that we can tell if it is encrpyted later and therefore decrypt
-     * it
-     */
-    @SuppressWarnings("nls")
     public static final String ENCRYPTED_VALUE_PREFIX = "enc:";
 
     /**
@@ -61,57 +48,30 @@ public class EncryptionTool {
      */
     private static EncryptionTool instance = null;
 
-    /**
-     * The iteration count used to initialize the PBE algorithm and to generate the key spec
-     */
-    private static final int ITERATION_COUNT = 20;
-
     /**
      * The logger for this class.
      */
     private static final Logger LOG = LoggerFactory.getLogger(EncryptionTool.class);
 
     /**
-     * The secret passphrase (PBE) that we use to perform encryption and decryption. The algorithm we are using is a
-     * symmetrical cipher.
+     * The secret passphrase (PBE) that we use to perform encryption and decryption. The algorithm we
+     * are using is a symmetrical cipher.
      */
-    private static char[] secret = {
-        'C', '_', 'z', 'l', '!', 'K', '!', '4', '?', 'O', 'z', 'E', 'K', 'E', '>', 'U', 'R', '/', '%', 'Y', '\\', 'f',
-        'b', '"', 'e', 'n', '{', '"', 'l', 'U', 'F', '+', 'E', '\'', 'R', 'T', 'p', '1', 'V', '4', 'l', 'a', '9', 'w',
-        'v', '5', 'Z', '#', 'i', 'V', '"', 'd', 'l', '!', 'L', 'M', 'g', 'L', 'Q', '{', 'v', 'v', 'K', 'V'
-    };
+    private static char[] secret = {'C', '_', 'z', 'l', '!', 'K', '!', '4', '?', 'O', 'z', 'E', 'K', 'E', '>', 'U', 'R',
+            '/', '%', 'Y', '\\', 'f', 'b', '"', 'e', 'n', '{', '"', 'l', 'U', 'F', '+', 'E', '\'', 'R', 'T', 'p', '1',
+            'V', '4', 'l', 'a', '9', 'w', 'v', '5', 'Z', '#', 'i', 'V', '"', 'd', 'l', '!', 'L', 'M', 'g', 'L', 'Q',
+            '{', 'v', 'v', 'K', 'V'};
 
-    /**
-     * The algorithm to encrypt and decrpyt data is "Password (or passphrase) Based Encryption with Message Digest #5
-     * and the Data Encryption Standard", i.e., PBEWithMD5AndDES.
-     */
-    @SuppressWarnings("nls")
-    private static final String SECURITY_ALGORITHM = "PBEWITHMD5AND256BITAES";// "PBEWithMD5AndDES";
-
-    /**
-     * The decryption cipher object
-     */
-    private Cipher decryptCipher = null;
-
-    /**
-     * The encryption cipher object
-     */
-    private Cipher encryptCipher = null;
 
-    private BasicTextEncryptor encryptor;
 
     /**
      * Get an instance of the EncryptionTool
      *
      * @return The encryption tool to be used
      */
-    public static final EncryptionTool getInstance() {
+    public static final synchronized EncryptionTool getInstance() {
         if (instance == null) {
-            synchronized (lock) {
-                if (instance == null) {
-                    instance = new EncryptionTool();
-                }
-            }
+            instance = new EncryptionTool();
         }
         return instance;
     }
@@ -119,34 +79,32 @@ public class EncryptionTool {
     /**
      * Create the EncryptionTool instance
      */
-    @SuppressWarnings("nls")
     private EncryptionTool() {
-        // encryptor = new BasicTextEncryptor();
-        // encryptor.setPassword(secret.toString());
-        String out = "Found the following security algorithms:";
+
+        StringBuilder sb = new StringBuilder("Found the following security algorithms:");
         for (Provider p : Security.getProviders()) {
             for (Service s : p.getServices()) {
                 String algo = s.getAlgorithm();
-                out +=
-                    String.format("\n  -Algorithm [ %s ] in provider [ %s ] and service [ %s ]", algo, p.getName(),
-                        s.getClassName());
+                sb.append(String.format("%n -Algorithm [ %s ] in provider [ %s ] and service [ %s ]", algo, p.getName(),
+                        s.getClassName()));
             }
         }
-        LOG.debug(out);
+        if (LOG.isDebugEnabled()) {
+            LOG.debug(sb.toString());
+        }
     }
 
     /**
      * Decrypt the provided encrypted text
      *
-     * @param cipherText
-     *            THe cipher text to be decrypted. If the ciphertext is not encrypted, then it is returned as is.
-     * @return the clear test of the (possibly) encrypted value. The original value if the string is not encrypted.
+     * @param cipherText THe cipher text to be decrypted. If the ciphertext is not encrypted, then it is
+     *        returned as is.
+     * @return the clear test of the (possibly) encrypted value. The original value if the string is not
+     *         encrypted.
      */
-    @SuppressWarnings("nls")
     public synchronized String decrypt(String cipherText) {
         if (isEncrypted(cipherText)) {
             String encValue = cipherText.substring(ENCRYPTED_VALUE_PREFIX.length());
-            // return encryptor.decrypt(encValue);
             byte[] plainByte = Base64.decodeBase64(encValue.getBytes());
             byte[] decryptByte = xorWithSecret(plainByte);
             return new String(decryptByte);
@@ -159,13 +117,11 @@ public class EncryptionTool {
     /**
      * Encrypt the provided clear text
      *
-     * @param clearText
-     *            The clear text to be encrypted
-     * @return the encrypted text. If the clear text is empty (null or zero length), then an empty string is returned.
-     *         If the clear text is already encrypted, it is not encrypted again and is returned as is. Otherwise, the
-     *         clear text is encrypted and returned.
+     * @param clearText The clear text to be encrypted
+     * @return the encrypted text. If the clear text is empty (null or zero length), then an empty
+     *         string is returned. If the clear text is already encrypted, it is not encrypted again and
+     *         is returned as is. Otherwise, the clear text is encrypted and returned.
      */
-    @SuppressWarnings("nls")
     public synchronized String encrypt(String clearText) {
         if (clearText != null) {
             byte[] encByte = xorWithSecret(clearText.getBytes());
@@ -180,8 +136,7 @@ public class EncryptionTool {
      * Is a value encrypted? A value is considered to be encrypted if it begins with the
      * {@linkplain #ENCRYPTED_VALUE_PREFIX encrypted value prefix}.
      *
-     * @param value
-     *            the value to check.
+     * @param value the value to check.
      * @return true/false;
      */
     private static boolean isEncrypted(final String value) {
@@ -189,16 +144,15 @@ public class EncryptionTool {
     }
 
     /**
-     * XORs the input byte array with the secret key, padding 0x0 to the end of the secret key if the input is longer
-     * and returns a byte array the same size as input
+     * XORs the input byte array with the secret key, padding 0x0 to the end of the secret key if the
+     * input is longer and returns a byte array the same size as input
      *
-     * @param inp
-     *            The byte array to be XORed with secret
+     * @param inp The byte array to be XORed with secret
      * @return A byte array the same size as inp or null if input is null.
      */
     private byte[] xorWithSecret(byte[] inp) {
         if (inp == null) {
-            return null;
+            return new byte[0];
         }
 
         byte[] secretBytes = new String(secret).getBytes();
index 7a187d1..cb07041 100644 (file)
@@ -1,9 +1,11 @@
 /*-
  * ============LICENSE_START=======================================================
- * ONAP : APP-C
+ * ONAP : APPC
  * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property.  All rights reserved.
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
+ * Copyright (C) 2017 Amdocs
+ * =============================================================================
  * Licensed 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
@@ -15,6 +17,8 @@
  * 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.
+ * 
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
  * ============LICENSE_END=========================================================
  */
 
@@ -24,56 +28,51 @@ import java.util.Map;
 
 import org.apache.commons.configuration.PropertiesConfiguration;
 import org.apache.commons.lang.StringUtils;
-
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
 import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin;
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
 
 public class EncryptionToolDGWrapper implements SvcLogicJavaPlugin {
 
     private static final EELFLogger log = EELFManager.getInstance().getLogger(EncryptionToolDGWrapper.class);
 
-    public void runEncryption(Map<String, String> inParams, SvcLogicContext ctx) throws SvcLogicException
-    {
-        String responsePrefix = inParams.get("prefix");
+    public void runEncryption(Map<String, String> inParams, SvcLogicContext ctx) throws SvcLogicException {
         String userName = inParams.get("userName");
         String password = inParams.get("password");
-        String vnf_type = inParams.get("vnf_type");
+        String vnfType = inParams.get("vnf_type");
 
-        try{
-            responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""  ;
-            if(StringUtils.isBlank(userName) || StringUtils.isBlank(password) || StringUtils.isBlank(vnf_type)){
-                throw new Exception("username or Password is missing");
+        try {
+            if (StringUtils.isBlank(userName) || StringUtils.isBlank(password) || StringUtils.isBlank(vnfType)) {
+                throw new SvcLogicException("username or Password is missing");
             }
 
-            String [] input = new String[] {vnf_type,userName,password};
+            String[] input = new String[] {vnfType, userName, password};
             WrapperEncryptionTool.main(input);
-        }
-        catch (Exception e)
-        {
+
+        } catch (Exception e) {
             throw new SvcLogicException(e.getMessage());
         }
 
     }
-    public void getProperty(Map<String, String> inParams, SvcLogicContext ctx) throws SvcLogicException
-    {
+
+    public void getProperty(Map<String, String> inParams, SvcLogicContext ctx) throws SvcLogicException {
         String responsePrefix = inParams.get("prefix");
         String propertyName = inParams.get("propertyName");
 
-        try{
-            responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix+".") : ""  ;
-            PropertiesConfiguration conf = new PropertiesConfiguration(Constants.APPC_CONFIG_DIR + "/appc_southbound.properties");
+        try {
+            responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix + ".") : "";
+            PropertiesConfiguration conf =
+                    new PropertiesConfiguration(Constants.APPC_CONFIG_DIR + "/appc_southbound.properties");
             conf.setBasePath(null);
             EncryptionTool et = EncryptionTool.getInstance();
 
             ctx.setAttribute(responsePrefix + "propertyName", et.decrypt(conf.getProperty(propertyName).toString()));
-        }
-        catch (Exception e) {
+        } catch (Exception e) {
             ctx.setAttribute(responsePrefix + "status", "failure");
             ctx.setAttribute(responsePrefix + "error-message", e.getMessage());
-            e.printStackTrace();
+            log.info("Caught exception", e);
             throw new SvcLogicException(e.getMessage());
         }
     }
index a0472e6..cf596e9 100644 (file)
@@ -1,9 +1,11 @@
 /*-
  * ============LICENSE_START=======================================================
- * ONAP : APP-C
+ * ONAP : APPC
  * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property.  All rights reserved.
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
+ * Copyright (C) 2017 Amdocs
+ * =============================================================================
  * Licensed 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
  * 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.
+ * 
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
  * ============LICENSE_END=========================================================
  */
 
 package org.openecomp.appc.encryptiontool.wrapper;
 
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.OutputStream;
 import java.util.ArrayList;
-import java.util.Properties;
 
 import javax.sql.rowset.CachedRowSet;
 
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 import org.apache.commons.configuration.PropertiesConfiguration;
 import org.onap.ccsdk.sli.core.dblib.DBResourceManager;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 public class WrapperEncryptionTool {
 
-    private static final Logger log = LoggerFactory
-            .getLogger(WrapperEncryptionTool.class);
+    private static final Logger log = LoggerFactory.getLogger(WrapperEncryptionTool.class);
 
-    public static void main(String[] args)
-    {
+    public static void main(String[] args) {
         int rowCount = 0;
-        String vnf_type=args[0];
+        String vnfType = args[0];
         String user = args[1];
         String password = args[2];
         String action = args[3];
         String port = args[4];
         String url = args[5];
 
-        if("".equals(vnf_type))
-        {
-            System.out.println("ERROR-VNF_TYPE can not be null");
+        if ("".equals(vnfType)) {
+            log.info("ERROR-VNF_TYPE can not be null");
             return;
         }
-        if("".equals(user))
-        {
-            System.out.println("ERROR-USER can not be null");
+        if ("".equals(user)) {
+            log.info("ERROR-USER can not be null");
             return;
         }
-        if("".equals(password))
-        {
-            System.out.println("ERROR-PASSWORD can not be null");
+        if ("".equals(password)) {
+            log.info("ERROR-PASSWORD can not be null");
             return;
         }
 
-        EncryptionTool encryptionTool = EncryptionTool.getInstance();
-        String enPass = encryptionTool.encrypt(password);
+        EncryptionTool et = EncryptionTool.getInstance();
+        String enPass = et.encrypt(password);
 
-        if(action != null && !action.isEmpty()){
-            updateProperties(user,vnf_type , enPass, action, port, url);
-            return ;
+        if (action != null && !action.isEmpty()) {
+            updateProperties(user, vnfType, enPass, action, port, url);
+            return;
         }
 
         ArrayList<String> argList = new ArrayList<>();
-        argList.add(vnf_type);
+        argList.add(vnfType);
         argList.add(user);
-        String clause = " vnf_type = ? and user_name = ? ";
+        String clause = " vnfType = ? and user_name = ? ";
         String setClause = " password = ? ";
         String getselectData = " * ";
         DBResourceManager dbResourceManager = null;
-        try
-        {
+        try (CachedRowSet data = DbServiceUtil.getData(Constants.DEVICE_AUTHENTICATION, argList,
+                Constants.SCHEMA_SDNCTL, getselectData, clause);) {
             dbResourceManager = DbServiceUtil.initDbLibService();
-            CachedRowSet data = DbServiceUtil.getData(Constants.DEVICE_AUTHENTICATION, 
-                argList, Constants.SCHEMA_SDNCTL, getselectData,clause );
-            while(data.next())
-            {
-                rowCount ++;
+
+            while (data.next()) {
+                rowCount++;
             }
-            if(rowCount == 0)
-                log.info("APPC-MESSAGE: ERROR - No record Found for VNF_TYPE: " + vnf_type + ", User " + user );
-            else
-            {
+            if (rowCount == 0)
+                log.info("APPC-MESSAGE: ERROR - No record Found for VNF_TYPE: %, User % ", vnfType, user);
+            else {
                 argList.clear();
                 argList.add(enPass);
-                argList.add(vnf_type);
+                argList.add(vnfType);
                 argList.add(user);
-                DbServiceUtil.updateDB(Constants.DEVICE_AUTHENTICATION, argList, 
-                    Constants.SCHEMA_SDNCTL, clause, setClause);
+                DbServiceUtil.updateDB(Constants.DEVICE_AUTHENTICATION, argList, Constants.SCHEMA_SDNCTL, clause,
+                        setClause);
                 log.info("APPC-MESSAGE: Password Updated Successfully");
             }
-        }
-        catch (Exception e)
-        {
-            e.printStackTrace();
+        } catch (Exception e) {
+            log.info("Caught exception", e);
             log.info("APPC-MESSAGE:" + e.getMessage());
-        }
-        finally
-        {
-            dbResourceManager.cleanUp();
-            System.exit(0);
+        } finally {
+            if (dbResourceManager != null) {
+                dbResourceManager.cleanUp();
+            }
         }
     }
 
-    private static void updateProperties(String user, String vnf_type, String password, 
-            String action, String port, String url) {
+    private static void updateProperties(String user, String vnfType, String password, String action, String port,
+            String url) {
 
-        log.info("Received Inputs User:" + user + " vnf_type:"  + vnf_type + " action:" + action );
+        log.info("Received Inputs User:%s vnfType:%s action:%s", user, vnfType, action);
+        String property = vnfType + "." + action + ".";
 
-        String property =  vnf_type + "." + action + ".";
 
         try {
-            PropertiesConfiguration conf = new PropertiesConfiguration(Constants.APPC_CONFIG_DIR  + "/appc_southbound.properties");
-            conf.setProperty(property + "user",  user);
-            if(port != null && !port.isEmpty() )
-                conf.setProperty(property + "port",  port);
-            if(password != null && !password.isEmpty() )
-                conf.setProperty(property + "password",  password);
-            if(url != null && !url.isEmpty() )
-            conf.setProperty(property + "url",  url);
+            PropertiesConfiguration conf =
+                    new PropertiesConfiguration(Constants.APPC_CONFIG_DIR + "/appc_southbound.properties");
+            conf.setProperty(property + "user", user);
+            if (port != null && !port.isEmpty())
+                conf.setProperty(property + "port", port);
+            if (password != null && !password.isEmpty())
+                conf.setProperty(property + "password", password);
+            if (url != null && !url.isEmpty())
+                conf.setProperty(property + "url", url);
 
             conf.save();
 
+        } catch (Exception e) {
+            log.info("Caught Exception", e);
         }
-        catch (Exception e ) {
-            e.printStackTrace();
-            log.info("APPC-MESSAGE:" + e.getMessage());
-        }
-
     }
 }