/*
 *     Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 *     WSO2 Inc. 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.wso2.identity.integration.test.encryption;

import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.wso2.carbon.core.util.CryptoUtil;
import org.wso2.carbon.integration.common.utils.mgt.ServerConfigurationManager;
import org.wso2.identity.integration.common.utils.ISIntegrationTest;
import org.wso2.identity.integration.test.util.Utils;
import org.xml.sax.SAXException;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

public class EventPublisherPasswordEncryptionTestCase extends ISIntegrationTest {

    private ServerConfigurationManager serverConfigurationManager;
    private String eventPublisherDeploymentDirectory;
    String eventPublisherFileName = "IsAnalytics-Publisher-wso2event-AuthenticationData.xml";

    @BeforeClass(alwaysRun = true)
    public void testInit() throws Exception {

        super.init();
        serverConfigurationManager = new ServerConfigurationManager(isServer);

        eventPublisherDeploymentDirectory =
                Utils.getResidentCarbonHome() + File.separator + "repository" + File.separator +
                        "deployment" + File.separator + "server" + File.separator + "eventpublishers";
    }

    @Test(groups = "wso2.is",
            description = "Test encryption of password in user store configuration xml",
            priority = 1)
    public void testCustomPasswordEncryptionOfEventPublishers() throws Exception {

        File eventPublisherFile = new File(eventPublisherDeploymentDirectory + File.separator + eventPublisherFileName);
        decryptEventPublisherpassword(eventPublisherFile);
    }

    private void decryptEventPublisherpassword(File eventPublisherFile) throws Exception {

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        DocumentBuilder builder;
        Document doc;
        try {
            builder = documentBuilderFactory.newDocumentBuilder();
            doc = builder.parse(eventPublisherFile);
            XPathFactory xpathFactory = XPathFactory.newInstance();
            XPath xpath = xpathFactory.newXPath();
            NodeList data;
            data = getEncryptedPayload(doc, xpath);
            if (data.getLength() > 0) {
                for (int i = 0; i < data.getLength(); i++) {
                    String newEncryptedPassword = data.item(i).getNodeValue();
                    byte[] decryptedtext = CryptoUtil.getDefaultCryptoUtil()
                            .base64DecodeAndDecrypt(newEncryptedPassword);
                    String decryptedPasswordString = new String(decryptedtext);
                    Assert.assertEquals(decryptedPasswordString, "admin", "Password encryption failed when adding" +
                            " eventpublisher");
                }
            }

        } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) {

            throw new Exception(
                    "Error occurred while decrypting event publisher password for " + eventPublisherFileName);
        }

    }

    private static NodeList getEncryptedPayload(Document doc, XPath xpath)
            throws XPathExpressionException {

        XPathExpression expr = xpath
                .compile("//*[local-name()='property'][@*[local-name()='encrypted']='true']/text()");
        return (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
    }

    @AfterClass(alwaysRun = true)
    public void cleanup() throws Exception {

        serverConfigurationManager.restoreToLastConfiguration();
    }
}

@@ -760,24 +760,52 @@
 ncryption;%0A%0A
+import org.json.JSONObject;%0A
 import org.t
@@ -1001,53 +1001,8 @@
 st;%0A
-import org.wso2.carbon.core.util.CryptoUtil;%0A
 impo
@@ -1238,58 +1238,8 @@
 n;%0A%0A
-import java.io.File;%0Aimport java.io.IOException;%0A%0A
 impo
@@ -1574,16 +1574,132 @@
 Factory;
+%0Aimport java.io.File;%0Aimport java.io.IOException;%0Aimport java.nio.charset.StandardCharsets;%0Aimport java.util.Base64;
 %0A%0Apublic
@@ -1896,24 +1896,32 @@
 ectory;%0A    
+private 
 String event
@@ -2805,33 +2805,33 @@
 ptEventPublisher
-p
+P
 assword(eventPub
@@ -2888,17 +2888,17 @@
 ublisher
-p
+P
 assword(
@@ -3683,127 +3683,215 @@
     
-byte%5B%5D decryptedtext = CryptoUtil.getDefaultCryptoUtil()%0A                            .base64DecodeAndDecrypt(newEncrypt
+String decodedPasswordData = new String(Base64.getDecoder().decode(newEncryptedPassword),%0A                            StandardCharsets.UTF_8);%0A                    JSONObject jsonObject = new JSONObject(decod
 edPa
@@ -3896,16 +3896,20 @@
 Password
+Data
 );%0A     
@@ -3934,58 +3934,41 @@
 ing 
-decryptedPasswordString = new String(decryptedtext
+tValue = jsonObject.getString(%22t%22
 );%0A 
@@ -4010,39 +4010,34 @@
 als(
-decryptedPasswordString, %22adm
+tValue, %22AES/GCM/NoPadd
 in
+g
 %22, %22
@@ -4060,26 +4060,31 @@
 ion 
-failed when adding
+has used an unexpected 
 %22 +%0A
@@ -4116,23 +4116,17 @@
    %22
- eventpublisher
+algorithm
 %22);%0A
@@ -4153,25 +4153,24 @@
           %7D%0A
-%0A
         %7D ca
@@ -4264,17 +4264,16 @@
 on e) %7B%0A
-%0A
         
@@ -4414,25 +4414,24 @@
 ;%0A        %7D%0A
-%0A
     %7D%0A%0A    p

Fix test case failure