Skip to content

Commit

Permalink
MOSIP-34075 removed secret keys
Browse files Browse the repository at this point in the history
Signed-off-by: Sohan Kumar Dey <[email protected]>
Sohandey committed Jul 11, 2024

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
2 parents a788c74 + a0340cb commit dd91731
Showing 33 changed files with 2,866 additions and 444 deletions.
135 changes: 101 additions & 34 deletions apitest-commons/pom.xml
Original file line number Diff line number Diff line change
@@ -39,6 +39,7 @@
<properties>
<!-- kernel versions -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<kernel-websubclient-api.version>1.2.0.1-SNAPSHOT</kernel-websubclient-api.version>

<!-- maven -->
<maven.compiler.target>11</maven.compiler.target>
@@ -190,11 +191,10 @@
<rest.assured.version>3.0.7</rest.assured.version>
<testng.version>6.11</testng.version>
<zt.zip.version>1.13</zt.zip.version>
<fileName>apitest-commons-1.2.0.1-SNAPSHOT-jar-with-dependencies</fileName>
<fileName>apitest-commons-1.2.1-SNAPSHOT-jar-with-dependencies</fileName>

</properties>
<dependencies>

<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
@@ -294,20 +294,21 @@
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.10.1</version>
<version>2.12.1</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.1</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.5</version>
<version>2.12.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
@@ -410,11 +411,7 @@
</dependency>

<!-- https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk15on -->
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.70</version>
</dependency>

<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
<dependency>
<groupId>commons-codec</groupId>
@@ -481,21 +478,6 @@
</dependency>
<!-- Encryption Decryption Util Jar -->

<dependency>
<groupId>io.mosip.testrig.authentication.demo</groupId>
<artifactId>authentication-demo-service</artifactId>
<version>1.2.0.1-SNAPSHOT</version>
<exclusions>
<exclusion>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-tools</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.mosip.kernel</groupId>
<artifactId>kernel-core</artifactId>
@@ -532,9 +514,86 @@
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>compile</scope>
</dependency>
<version>1.18.32</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.70</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpkix-jdk15on</artifactId>
<version>1.70</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>io.mosip.authentication</groupId>
<artifactId>authentication-core</artifactId>
<version>1.2.0.1-B3</version>
<exclusions>
<exclusion>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</exclusion>
</exclusions>
</dependency>

<dependency>
<groupId>io.mosip.kernel</groupId>
<artifactId>kernel-core</artifactId>
<version>1.2.0.1-SNAPSHOT</version>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>
spring-boot-starter-security
</artifactId>
</exclusion>
<exclusion>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.mosip.kernel</groupId>
<artifactId>kernel-websubclient-api</artifactId>
<version>${kernel-websubclient-api.version}</version>
</dependency>

<dependency>
<groupId>io.mosip.kernel</groupId>
<artifactId>kernel-templatemanager-velocity</artifactId>
<version>1.2.0.1-SNAPSHOT</version>
</dependency>

<dependency>
<groupId>io.mosip.kernel</groupId>
<artifactId>kernel-keymanager-service</artifactId>
<version>1.2.0.1-SNAPSHOT</version>
<classifier>lib</classifier>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>
spring-boot-starter-security
</artifactId>
</exclusion>
</exclusions>
</dependency>

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.14</version>
</dependency>

</dependencies>
<dependencyManagement>
<dependencies>
@@ -555,6 +614,14 @@
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<plugins>
@@ -784,4 +851,4 @@
</build>
</profile>
</profiles>
</project>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package io.mosip.testrig.apirig.admin.fw.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import io.mosip.kernel.crypto.jce.core.CryptoCore;

@Configuration
@Import({ CryptoCore.class })
@ComponentScan(basePackages = { "io.mosip.testrig.apirig", "io.mosip.testrig.dslrig"})
public class BeanConfig {
int i = 0;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package io.mosip.testrig.apirig.dto;

import lombok.Data;

import java.util.Map;

@Data
public class EncryptionRequestDto {

private Map<String, Object> identityRequest;

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package io.mosip.testrig.apirig.dto;

import lombok.Data;

@Data
public class EncryptionResponseDto {
String encryptedSessionKey;
String encryptedIdentity;
String requestHMAC;
}
Original file line number Diff line number Diff line change
@@ -19,4 +19,5 @@ public class TestCaseDTO {
private boolean checkErrorsOnlyInResponse;
private String allowedErrorCodes;
private String[] kycFields;
private String description;
}
Original file line number Diff line number Diff line change
@@ -270,7 +270,7 @@ protected void writeSuiteSummary() {

// Left column: "Tested Component Details" with central alignment
writer.print("<th style=\"text-align: center; vertical-align: middle;\" colspan=\"2\"><span class=\"not-bold\"><pre>");
writer.print(Utils.escapeHtml("Tested Components & End Points"));
writer.print(Utils.escapeHtml("End Points used"));
writer.print("</span></th>");

// Right column: Details from AdminTestUtil.getServerComponentsDetails() without bold formatting
Original file line number Diff line number Diff line change
@@ -21,6 +21,8 @@
import org.apache.log4j.PropertyConfigurator;
import org.json.JSONArray;
import org.json.simple.JSONObject;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.ITestContext;
import org.testng.annotations.AfterSuite;

@@ -29,6 +31,7 @@
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
import com.nimbusds.jose.jwk.RSAKey;

import io.mosip.testrig.apirig.admin.fw.config.BeanConfig;
import io.mosip.testrig.apirig.dbaccess.DBManager;
import io.mosip.testrig.apirig.utils.AdminTestUtil;
import io.mosip.testrig.apirig.utils.AuthTestsUtil;
@@ -48,8 +51,8 @@
* All suite level before and after tests will be completed here.
*
*/

public class BaseTestCase {
@ContextConfiguration(classes = {BeanConfig.class})
public class BaseTestCase extends AbstractTestNGSpringContextTests {

protected static Logger logger = Logger.getLogger(BaseTestCase.class);
protected static MockSMTPListener mockSMTPListener = null;
@@ -95,7 +98,7 @@ public class BaseTestCase {
public String mobileAuthCookie = null;
public String autoTstUsrCkie = null;
public static String currentModule = GlobalConstants.MASTERDATA;
public static String certsForModule = "DSL-IDA";
public static String certsForModule = "DSL";
public static List<String> listOfModules = null;
public static List<String> languageList = new ArrayList<>();
public static String languageCode = null;
@@ -114,7 +117,7 @@ public class BaseTestCase {
public static Map<?, ?> residentQueries;
public static Map<?, ?> partnerQueries;
public static boolean insertDevicedata = false;
public static boolean proxy = false;
public static boolean proxy = true;

public static String ApplnURI;
public static String ApplnURIForKeyCloak;
@@ -266,8 +269,8 @@ public static void suiteSetup() {
BaseTestCase.certsForModule = "IDA";
AuthTestsUtil.initiateAuthTest();

mockSMTPListener = new MockSMTPListener();
mockSMTPListener.run();
// mockSMTPListener = new MockSMTPListener();
// mockSMTPListener.run();
}
if (listOfModules.contains("idrepo")) {
setReportName("idrepo");
Original file line number Diff line number Diff line change
@@ -28,6 +28,7 @@
import io.mosip.testrig.apirig.utils.ConfigManager;
import io.mosip.testrig.apirig.utils.EncryptionDecrptionUtil;
import io.mosip.testrig.apirig.utils.GlobalConstants;
import io.mosip.testrig.apirig.utils.GlobalMethods;
import io.mosip.testrig.apirig.utils.JWKKeyUtil;
import io.mosip.testrig.apirig.utils.KeyCloakUserAndAPIKeyGeneration;
import io.mosip.testrig.apirig.utils.KeycloakUserManager;
@@ -71,15 +72,14 @@ public static void main(String[] arg) {
ConfigManager.init();
BaseTestCase.suiteSetup();
setLogLevels();
AdminTestUtil.encryptDecryptUtil = new EncryptionDecrptionUtil();

// For now we are not doing health check for qa-115.
if (BaseTestCase.isTargetEnvLTS()) {
HealthChecker healthcheck = new HealthChecker();
healthcheck.setCurrentRunningModule(BaseTestCase.currentModule);
Thread trigger = new Thread(healthcheck);
trigger.start();
}
// if (BaseTestCase.isTargetEnvLTS()) {
// HealthChecker healthcheck = new HealthChecker();
// healthcheck.setCurrentRunningModule(BaseTestCase.currentModule);
// Thread trigger = new Thread(healthcheck);
// trigger.start();
// }
KeycloakUserManager.removeUser();
KeycloakUserManager.createUsers();
KeycloakUserManager.closeKeycloakInstance();
@@ -150,7 +150,6 @@ public static void main(String[] arg) {
DBManager.clearKeyManagerDbData();
}


System.exit(0);

}
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
package io.mosip.testrig.apirig.utils;

import static io.restassured.RestAssured.given;

import de.mkammerer.argon2.Argon2;
import de.mkammerer.argon2.Argon2Factory;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
@@ -32,6 +33,8 @@
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
@@ -52,8 +55,6 @@
import java.util.Set;
import java.util.TimeZone;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import javax.ws.rs.core.MediaType;
@@ -77,7 +78,9 @@
import org.testng.SkipException;
import org.yaml.snakeyaml.Yaml;

import java.lang.Double;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.jknack.handlebars.Context;
import com.github.jknack.handlebars.Handlebars;
@@ -114,6 +117,8 @@
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* @author Ravi Kant
@@ -175,13 +180,13 @@ public class AdminTestUtil extends BaseTestCase {
public static final String AUTH_HEADER_VALUE = "Some String";
public static final String SIGNATURE_HEADERNAME = GlobalConstants.SIGNATURE;
public static String updatedPolicyId = "";
public static BioDataUtility bioDataUtil = new BioDataUtility();

public static BioDataUtility getBioDataUtil() {
return bioDataUtil;
}
// public static BioDataUtility bioDataUtil = new BioDataUtility();
//
// public static BioDataUtility getBioDataUtil() {
// return bioDataUtil;
// }

public static EncryptionDecrptionUtil encryptDecryptUtil = null;
// public static EncryptionDecrptionUtil encryptDecryptUtil = null;
protected static String idField = null;
protected static String identityHbs = null;
protected static String draftHbs = null;
@@ -413,12 +418,66 @@ protected Response postWithBodyAndCookie(String url, String jsonInput, boolean a
String role, String testCaseName) {
return postWithBodyAndCookie(url, jsonInput, auditLogCheck, cookieName, role, testCaseName, false);
}

protected Response postWithBodyAndCookie(String url, String jsonInput, boolean auditLogCheck, String cookieName,
String role, String testCaseName, String idKeyName) {
return postWithBodyAndCookie(url, jsonInput, auditLogCheck, cookieName, role, testCaseName, false, idKeyName);
}

protected Response postWithBodyAndCookie(String url, String jsonInput, boolean auditLogCheck, String cookieName,
String role, String testCaseName, boolean bothAccessAndIdToken) {
Response response = null;
String inputJson = inputJsonKeyWordHandeler(jsonInput, testCaseName);
url = uriKeyWordHandelerUri(url, testCaseName);
if (BaseTestCase.currentModule.equals(GlobalConstants.PREREG) || BaseTestCase.currentModule.equals("auth")
|| BaseTestCase.currentModule.equals(GlobalConstants.RESIDENT)
|| BaseTestCase.currentModule.equals(GlobalConstants.MASTERDATA)) {
inputJson = smtpOtpHandler(inputJson, testCaseName);
}

if (bothAccessAndIdToken) {
token = kernelAuthLib.getTokenByRole(role, ACCESSTOKENCOOKIENAME);
idToken = kernelAuthLib.getTokenByRole(role, IDTOKENCOOKIENAME);
} else {

if (testCaseName.contains("NOAUTH")) {
token = "";
} else {
token = kernelAuthLib.getTokenByRole(role);
}

}
logger.info(GlobalConstants.POST_REQ_URL + url);
GlobalMethods.reportRequest(null, inputJson, url);
try {
if (bothAccessAndIdToken) {
response = RestClient.postRequestWithCookie(url, inputJson, MediaType.APPLICATION_JSON,
MediaType.APPLICATION_JSON, cookieName, token, IDTOKENCOOKIENAME, idToken);
} else {
response = RestClient.postRequestWithCookie(url, inputJson, MediaType.APPLICATION_JSON,
MediaType.APPLICATION_JSON, cookieName, token);
}

if (auditLogCheck) {
JSONObject jsonObject = new JSONObject(inputJson);
String timeStamp1 = jsonObject.getString(GlobalConstants.REQUESTTIME);
String dbChecker = GlobalConstants.TEST_FULLNAME + BaseTestCase.getLanguageList().get(0);
checkDbAndValidate(timeStamp1, dbChecker);
}
GlobalMethods.reportResponse(response.getHeaders().asList().toString(), url, response);

} catch (Exception e) {
logger.error(GlobalConstants.EXCEPTION_STRING_2 + e);
}

return response;
}

protected Response postWithBodyAndCookie(String url, String jsonInput, boolean auditLogCheck, String cookieName,
String role, String testCaseName, boolean bothAccessAndIdToken, String idKeyName) {
Response response = null;
String inputJson = inputJsonKeyWordHandeler(jsonInput, testCaseName);
url = uriKeyWordHandelerUri(url, testCaseName);
if (BaseTestCase.currentModule.equals(GlobalConstants.PREREG) || BaseTestCase.currentModule.equals("auth")
|| BaseTestCase.currentModule.equals(GlobalConstants.RESIDENT)
|| BaseTestCase.currentModule.equals(GlobalConstants.MASTERDATA)
@@ -458,6 +517,10 @@ protected Response postWithBodyAndCookie(String url, String jsonInput, boolean a
checkDbAndValidate(timeStamp1, dbChecker);
}
GlobalMethods.reportResponse(response.getHeaders().asList().toString(), url, response);

if (testCaseName.toLowerCase().contains("_sid")) {
writeAutoGeneratedId(response, idKeyName, testCaseName);
}

} catch (Exception e) {
logger.error(GlobalConstants.EXCEPTION_STRING_2 + e);
@@ -2039,14 +2102,14 @@ protected Response getWithPathParamAndCookie(String url, String jsonInput, boole
GlobalConstants.ERROR_STRING_1 + jsonInput + GlobalConstants.EXCEPTION_STRING_1 + e.getMessage());
}

if (map.containsKey(GlobalConstants.HEADERTRANSACTIONID)) {
if (map != null && map.containsKey(GlobalConstants.HEADERTRANSACTIONID)) {
headerTransactionID = map.get(GlobalConstants.HEADERTRANSACTIONID).toString();
cookiesMap.put(GlobalConstants.TRANSACTION_ID_KEY, headerTransactionID);
cookiesMap.put(GlobalConstants.XSRF_TOKEN, token);
map.remove(GlobalConstants.HEADERTRANSACTIONID);
}

if (map.containsKey(GlobalConstants.VERIFIEDTRANSACTIONID)) {
if (map != null && map.containsKey(GlobalConstants.VERIFIEDTRANSACTIONID)) {
headerTransactionID = map.get(GlobalConstants.VERIFIEDTRANSACTIONID).toString();
cookiesMap.put(GlobalConstants.VERIFIED_TRANSACTION_ID_KEY, headerTransactionID);
cookiesMap.put(GlobalConstants.XSRF_TOKEN, token);
@@ -3175,6 +3238,7 @@ public String inputJsonKeyWordHandeler(String jsonString, String testCaseName) {

// Need to handle int replacement
if (jsonString.contains("$HIERARCHYLEVEL$"))
getLocationData();
jsonString = replaceKeywordWithValue(jsonString, "$HIERARCHYLEVEL$", String.valueOf(hierarchyLevel));

if (jsonString.contains("$HIERARCHYNAME$"))
@@ -4074,10 +4138,10 @@ public String getAutoGeneratedFieldValue(String inputFromYml, String testCaseNam

public String updateTimestampOtp(String otpIdentyEnryptRequest) {
otpIdentyEnryptRequest = JsonPrecondtion.parseAndReturnJsonContent(otpIdentyEnryptRequest,
generateCurrentUTCTimeStamp(), "identityRequest.timestamp");
generateCurrentUTCTimeStamp(), "timestamp");
if (proxy)
otpIdentyEnryptRequest = JsonPrecondtion.parseAndReturnJsonContent(otpIdentyEnryptRequest,
properties.getProperty("proxyOTP"), "identityRequest.otp");
properties.getProperty("proxyOTP"), "otp");
else
return otpIdentyEnryptRequest;

@@ -4381,7 +4445,7 @@ public String generateSignatureWithRequest(String request, String partnerId) {
String singResponse = null;
try {
singResponse = sign(request, false, true, false, null, getKeysDirPath(), partnerId);
} catch (NoSuchAlgorithmException | UnrecoverableEntryException | KeyStoreException | CertificateException
} catch (NoSuchAlgorithmException | UnrecoverableEntryException | KeyStoreException | CertificateException
| OperatorCreationException | JoseException | IOException e) {
logger.error(e.getMessage());
}
@@ -4557,10 +4621,18 @@ public String sign(String dataToSign, boolean includePayload, boolean includeCer

}

public String getKeysDirPath() {
String path = System.getProperty("java.io.tmpdir") + "/" + "IDA-" + environment + ".mosip.net";
logger.info("certificate path is::" + path);
return new File(path).getAbsolutePath();
public static String getKeysDirPath() {
// String path = "/Users/kamalsingh/mosip/authcerts" + "/" + "IDA-" + environment + ".mosip.net";
// logger.info("certificate path is::" + path);
// return new File(path).getAbsolutePath();

String certsTargetDir = System.getProperty("java.io.tmpdir") + File.separator + System.getProperty("parent.certs.folder.name", "AUTHCERTS");

if (System.getProperty("os.name").toLowerCase().contains("windows") == false) {
certsTargetDir = "/home/mosip/authcerts";
}

return certsTargetDir + File.separator + certsForModule + "-IDA-" + environment + ".mosip.net";
}

public static String buildIdentityRequest(String identityRequest) {
@@ -7125,4 +7197,4 @@ public String getPasswordPattern() {
return password;
}

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,275 @@
package io.mosip.testrig.apirig.utils;

import com.fasterxml.jackson.databind.ObjectMapper;

import io.mosip.authentication.core.constant.IdAuthenticationErrorConstants;
import io.mosip.authentication.core.exception.IdAuthenticationAppException;
import io.mosip.authentication.core.exception.IdAuthenticationBusinessException;
import io.mosip.authentication.core.indauth.dto.IdType;
import io.mosip.authentication.core.spi.indauth.match.MatchType;
import io.mosip.kernel.core.exception.ExceptionUtils;
import io.mosip.kernel.core.exception.ServiceError;
import io.mosip.kernel.core.templatemanager.spi.TemplateManager;
import io.mosip.kernel.core.util.CryptoUtil;
import io.mosip.kernel.core.util.DateUtils;
import io.mosip.testrig.apirig.dto.CertificateChainResponseDto;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.bouncycastle.operator.OperatorCreationException;
import org.jose4j.lang.JoseException;
import org.json.JSONException;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;


import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.xml.bind.DatatypeConverter;
import java.io.*;
import java.net.URI;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
import java.util.*;
import java.util.function.BiFunction;
import java.util.stream.Stream;

public class AuthUtil {

public AuthUtil() {
mapper = new ObjectMapper();
}

private ObjectMapper mapper;
private static final String PIN = "pin";

private static final String BIO = "bio";

private static final String DEMO = "demo";

private static final String OTP = "otp";
private static final String BEGIN_CERTIFICATE = "-----BEGIN CERTIFICATE-----";
private static final String END_CERTIFICATE = "-----END CERTIFICATE-----";

private static final String LINE_SEPARATOR = System.getProperty("line.separator");

private static final String TIMESTAMP = "timestamp";

private static final String ID = "id";

private static final String AUTH_TYPE = "authType";

private static final String SECONDARY_LANG_CODE = "secondaryLangCode";

private static final String TXN = "txn";

private static final String VER = "ver";

private static final String ENV = "env";

private static final String DOMAIN_URI = "domainUri";

private static final String IDA_API_VERSION = "ida.api.version";

private static final String MOSIP_ENV = "Staging";

private static final String MOSIP_DOMAINURI = "mosip.base.url";
public static final String BIOMETRICS = "biometrics";

private static final String IDA_AUTH_REQUEST_TEMPLATE = "ida.authRequest.template";

private static final String DATE_TIME = "dateTime";

private static final String TRANSACTION_ID = "transactionId";

private static final String IDENTITY = "Identity";

private static final String TEMPLATE = "Template";


public void clearKeys(String certsDir, String moduleName, String targetEnv) throws IOException {
KeyMgrUtility keyMgrUtil = new KeyMgrUtility();
keyMgrUtil.deleteFile(new File(keyMgrUtil.getKeysDirPath(certsDir, moduleName, targetEnv).toString()));
}

public CertificateChainResponseDto generatePartnerKeys(
PartnerTypes partnerType, String partnerName, boolean keyFileNameByPartnerName, String certsDir, String moduleName, String targetEnv) throws UnrecoverableEntryException, CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException, OperatorCreationException {
KeyMgrUtility keyMgrUtil = new KeyMgrUtility();
return keyMgrUtil.getPartnerCertificates(partnerType, keyMgrUtil.getKeysDirPath(certsDir, moduleName, targetEnv), partnerName,
keyFileNameByPartnerName);
}

public String updatePartnerCertificate(
PartnerTypes partnerType, String partnerName, boolean keyFileNameByPartnerName, Map<String, String> requestData, String certsDir,
String moduleName, String targetEnv) throws CertificateException,
IOException, NoSuchAlgorithmException, UnrecoverableEntryException, KeyStoreException {
KeyMgrUtility keyMgrUtil = new KeyMgrUtility();
String certificateData = requestData.get("certData");
String filePrepend = partnerType.getFilePrepend();

X509Certificate x509Cert = (X509Certificate) keyMgrUtil.convertToCertificate(certificateData);
System.out.println("certificateType: " + partnerType.toString());
System.out.println("filePrepend: " + filePrepend);
boolean isUpdated = keyMgrUtil.updatePartnerCertificate(filePrepend, x509Cert, keyMgrUtil.getKeysDirPath(certsDir, moduleName, targetEnv),
partnerName, keyFileNameByPartnerName);
return isUpdated ? "Update Success" : "Update Failed";
}

public String uploadIDACertificate(
CertificateTypes certificateType,
Map<String, String> requestData,
String certsDir,
String moduleName,
String targetEnv)
throws CertificateException, IOException {
KeyMgrUtility keyMgrUtil = new KeyMgrUtility();

String certificateData = requestData.get("certData");
String fileName = certificateType.getFileName();
System.out.println("certificateType: " + certificateType.toString());
System.out.println("FileName: " + fileName);

X509Certificate x509Cert = (X509Certificate) keyMgrUtil.convertToCertificate(certificateData);
Base64.Encoder base64Encoder = Base64.getMimeEncoder(64, LINE_SEPARATOR.getBytes());
byte[] certificateBytes = x509Cert.getEncoded();
String encodedCertificateData = new String(base64Encoder.encode(certificateBytes));
StringBuilder strBuilder = new StringBuilder();
strBuilder.append(BEGIN_CERTIFICATE);
strBuilder.append(LINE_SEPARATOR);
strBuilder.append(encodedCertificateData);
strBuilder.append(LINE_SEPARATOR);
strBuilder.append(END_CERTIFICATE);
String certificateStr = strBuilder.toString();

String keysDirPath = keyMgrUtil.getKeysDirPath(certsDir, moduleName, targetEnv);

Path parentPath = Paths.get(keysDirPath + "/" + fileName).getParent();
if (parentPath != null && !Files.exists(parentPath)) {
Files.createDirectories(parentPath);
}

boolean isErrored = false;
try (BufferedWriter writer = new BufferedWriter(new FileWriter(keysDirPath + "/" + fileName))) {
writer.write(certificateStr);
writer.flush();
} catch (Exception e) {
System.err.println(e.getMessage());
isErrored = true;
}

return isErrored ? "Upload Failed" : "Upload Success";
}

private String digest(byte[] hash) throws NoSuchAlgorithmException {
return DatatypeConverter.printHexBinary(hash).toUpperCase();
}

public byte[] getCertificateThumbprint(Certificate cert) throws CertificateEncodingException {
return DigestUtils.sha256(cert.getEncoded());
}

// private void idValuesMap(String id, boolean isKyc, boolean isInternal, Map<String, Object> reqValues,
// String transactionId, String utcCurrentDateTimeString) {
// reqValues.put(ID, id);
// if (isInternal) {
// reqValues.put(AUTH_TYPE, "auth.internal");
// } else {
// if (isKyc) {
// reqValues.put(AUTH_TYPE, "kyc");
// reqValues.put(SECONDARY_LANG_CODE, PropertiesReader.readProperty("mosip.secondary-language"));
// } else {
// reqValues.put(AUTH_TYPE, "auth");
// }
// }
//
// reqValues.put(TIMESTAMP, utcCurrentDateTimeString);
// reqValues.put(TXN, transactionId == null ? "1234567890" : transactionId);
// reqValues.put(VER, PropertiesReader.readProperty(IDA_API_VERSION));
// reqValues.put(DOMAIN_URI, PropertiesReader.readProperty(MOSIP_DOMAINURI));
// reqValues.put(ENV, MOSIP_ENV);
// }

private void getAuthTypeMap(String reqAuth, Map<String, Object> reqValues, Map<String, Object> request) {
String[] reqAuthArr;
if (reqAuth == null) {
BiFunction<String, String, Optional<String>> authTypeMapFunction = (key, authType) -> Optional
.ofNullable(request).filter(map -> map.containsKey(key)).map(map -> authType);
reqAuthArr = Stream
.of(authTypeMapFunction.apply("demographics", "demo"), authTypeMapFunction.apply(BIOMETRICS, "bio"),
authTypeMapFunction.apply("otp", "otp"), authTypeMapFunction.apply("staticPin", "pin"))
.filter(Optional::isPresent).map(Optional::get).toArray(size -> new String[size]);
} else {
reqAuth = reqAuth.trim();
if (reqAuth.contains(",")) {
reqAuthArr = reqAuth.split(",");
} else {
reqAuthArr = new String[]{reqAuth};
}
}

for (String authType : reqAuthArr) {
authTypeSelectionMap(reqValues, authType);
}
}

private void authTypeSelectionMap(Map<String, Object> reqValues, String authType) {

if (authType.equalsIgnoreCase(MatchType.Category.OTP.getType())) {
reqValues.put(OTP, true);
} else if (authType.equalsIgnoreCase(MatchType.Category.DEMO.getType())) {
reqValues.put(DEMO, true);
} else if (authType.equalsIgnoreCase(MatchType.Category.BIO.getType())) {
reqValues.put(BIO, true);
} else if (authType.equalsIgnoreCase(MatchType.Category.SPIN.getType())) {
reqValues.put("pin", true);
}
}

private void applyRecursively(Object obj, String key, String value) {
if (obj instanceof Map) {
Map<String, Object> map = (Map<String, Object>) obj;
Optional<String> matchingKey = map.keySet().stream().filter(k -> k.equalsIgnoreCase(key)).findFirst();
if (matchingKey.isPresent()) {
map.put(matchingKey.get(), value);
}

for (Object val : map.values()) {
applyRecursively(val, key, value);
}
} else if (obj instanceof List) {
List<?> list = (List<?>) obj;
for (Object object : list) {
applyRecursively(object, key, value);
}
}
}

public String signRequest(
PartnerTypes partnerType,
String partnerName,
boolean keyFileNameByPartnerName,
String request,
String certsDir,
String moduleName,
String targetEnv)
throws JoseException, NoSuchAlgorithmException, UnrecoverableEntryException, KeyStoreException,
CertificateException, IOException, OperatorCreationException {
KeyMgrUtility keyMgrUtil = new KeyMgrUtility();
JWSSignAndVerifyController jWSSignAndVerifyController = new JWSSignAndVerifyController();
return jWSSignAndVerifyController.sign(request, false,
true, false, null, keyMgrUtil.getKeysDirPath(certsDir, moduleName, targetEnv), partnerType, partnerName, keyFileNameByPartnerName);
}


}
Original file line number Diff line number Diff line change
@@ -4,7 +4,6 @@
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.HashMap;
import java.util.regex.Pattern;

import javax.ws.rs.core.MediaType;
@@ -13,12 +12,14 @@
import org.apache.commons.codec.binary.Hex;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import io.mosip.kernel.core.util.CryptoUtil;
import io.mosip.kernel.core.util.HMACUtils;
import io.mosip.testrig.apirig.testrunner.BaseTestCase;
import io.mosip.testrig.apirig.testrunner.JsonPrecondtion;
import io.restassured.response.Response;
import io.mosip.testrig.apirig.utils.Encrypt.SplittedEncryptedData;

/**
* The class to perform or construct biometric identity data which involves
@@ -28,10 +29,14 @@
* @author Ravi Kant
*
*/

@Component
public class BioDataUtility extends AdminTestUtil {

private static final Logger logger = Logger.getLogger(BioDataUtility.class);
@Autowired
private EncryptionDecrptionUtil encryptDecryptUtil;
@Autowired
private Encrypt encrypt;


private String encryptIsoBioValue(String isoBiovalue, String timestamp, String bioValueEncryptionTemplateJson,
@@ -57,12 +62,42 @@ private String encryptIsoBioValue(String isoBiovalue, String timestamp, String b

residentCookie = kernelAuthLib.getTokenByRole(GlobalConstants.RESIDENT);


// try {
// String json = encryptDecryptUtil.encrypt(jsonContent);
// logger.info("json is" + json);
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }

String content = RestClient.postRequestWithCookie(cryptoEncryptUrl, jsonContent, MediaType.APPLICATION_JSON,
MediaType.APPLICATION_JSON, COOKIENAME, residentCookie).asString();
String data = JsonPrecondtion.getValueFromJson(content, "response.data");
logger.info("data is" + data);
return EncryptionDecrptionUtil.splitEncryptedData(data);

SplittedEncryptedData splittedEncryptedData = null;
JSONObject splittedEncryptedDataJson = new JSONObject();


try {
splittedEncryptedData = encrypt.splitEncryptedData(data);
logger.info("EncryptedSessionKey is " + splittedEncryptedData.getEncryptedSessionKey());
logger.info("EncryptedData is " + splittedEncryptedData.getEncryptedData());
logger.info("Thumbprint is " + splittedEncryptedData.getThumbprint());
splittedEncryptedDataJson.put("encryptedSessionKey", splittedEncryptedData.getEncryptedSessionKey());
splittedEncryptedDataJson.put("encryptedData", splittedEncryptedData.getEncryptedData());
splittedEncryptedDataJson.put("thumbprint", splittedEncryptedData.getThumbprint());

} catch (Exception e) {
logger.error(e.getMessage());
}

// return EncryptionDecrptionUtil.splitEncryptedData(data);
return splittedEncryptedDataJson.toString();
}



private String getHash(String content) {
return HMACUtils.digestAsPlainText(HMACUtils.generateHash(content.getBytes()));
@@ -116,7 +151,7 @@ public String constractBioIdentityRequest(String identityRequest, String bioValu
byte [] previousDataByteArr = "".getBytes(StandardCharsets.UTF_8);
previousBioDataHash = generateHash(previousDataByteArr);
for (int i = 0; i < count; i++) {
String biometricsMapper = "identityRequest.(biometrics)[" + i + "]";
String biometricsMapper = "(biometrics)[" + i + "]";
if (!isInternal) {
String digitalId = JsonPrecondtion.getJsonValueFromJson(identityRequest,
biometricsMapper + ".data.digitalId");
@@ -135,6 +170,15 @@ public String constractBioIdentityRequest(String identityRequest, String bioValu
String encryptedContent = encryptIsoBioValue(bioValue, timestamp, bioValueencryptionTemplateJson,
transactionId, isInternal);
String encryptedBioValue = JsonPrecondtion.getValueFromJson(encryptedContent, "encryptedData");



identityRequest = JsonPrecondtion.parseAndReturnJsonContent(identityRequest, BaseTestCase.ApplnURI,
biometricsMapper + ".data.domainUri");



logger.info(identityRequest);
String encryptedSessionKey = JsonPrecondtion.getValueFromJson(encryptedContent, "encryptedSessionKey");
identityRequest = JsonPrecondtion.parseAndReturnJsonContent(identityRequest, encryptedBioValue,
biometricsMapper + ".data.bioValue");
@@ -171,7 +215,7 @@ public String constractBioIdentityRequest(String identityRequest, String bioValu
}

identityRequest = JsonPrecondtion.parseAndReturnJsonContent(identityRequest,
AdminTestUtil.generateCurrentUTCTimeStamp(), "identityRequest.timestamp");
AdminTestUtil.generateCurrentUTCTimeStamp(), "timestamp");

return identityRequest;
}
@@ -189,27 +233,52 @@ private String getSignedBiometrics(String identityDataBlock, String key) {

private String generateSignatureWithBioMetric(String identityDataBlock, String string, String key) {

String singResponse = null;
String EncryptUtilBaseUrl = ConfigManager.getAuthDemoServiceUrl() + "/";

residentCookie = kernelAuthLib.getTokenByRole(GlobalConstants.RESIDENT);
HashMap<String, String> pathParamsMap = new HashMap<>();
pathParamsMap.put("partnerType", key);
pathParamsMap.put("moduleName", BaseTestCase.certsForModule);
pathParamsMap.put("certsDir", ConfigManager.getauthCertsPath());
Response response = RestClient.postRequestWithQueryParamBodyAndCookie(
EncryptUtilBaseUrl + properties.get("signRequest"), identityDataBlock, pathParamsMap,
MediaType.TEXT_PLAIN, MediaType.TEXT_PLAIN, GlobalConstants.AUTHORIZATION,
residentCookie);
PartnerTypes partnerTypeEnum = null;
if (key.equals("RELYING_PARTY")) {
partnerTypeEnum = PartnerTypes.RELYING_PARTY;
} else if (key.equals("DEVICE")) {
partnerTypeEnum = PartnerTypes.DEVICE;
}else if (key.equals("FTM")) {
partnerTypeEnum = PartnerTypes.FTM;
}else if (key.equals("EKYC")) {
partnerTypeEnum = PartnerTypes.EKYC;
}else if (key.equals("MISP")) {
partnerTypeEnum = PartnerTypes.MISP;
}
AuthUtil authUtil = new AuthUtil();
String response = null;
try {
response = authUtil.signRequest(partnerTypeEnum, null, false, identityDataBlock,"", BaseTestCase.certsForModule, ApplnURI.replace("https://", ""));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


// String singResponse = null;
// String EncryptUtilBaseUrl = ConfigManager.getAuthDemoServiceUrl() + "/";
//
// residentCookie = kernelAuthLib.getTokenByRole(GlobalConstants.RESIDENT);
// HashMap<String, String> pathParamsMap = new HashMap<>();
// pathParamsMap.put("partnerType", key);
// pathParamsMap.put("moduleName", BaseTestCase.certsForModule);
// pathParamsMap.put("certsDir", ConfigManager.getauthCertsPath());
//
//
// Response response = RestClient.postRequestWithQueryParamBodyAndCookie(
// EncryptUtilBaseUrl + properties.get("signRequest"), identityDataBlock, pathParamsMap,
// MediaType.TEXT_PLAIN, MediaType.TEXT_PLAIN, GlobalConstants.AUTHORIZATION,
// residentCookie);
//
byte[] bytePayload = identityDataBlock.getBytes();
String payloadData = Base64.getUrlEncoder().encodeToString(bytePayload);
payloadData= payloadData.replace("=", "");
String signNewResponse = response.asString().replace("..", "."+ payloadData +".");

String signNewResponse = response.replace("..", "."+ payloadData +".");
logger.info(signNewResponse);


singResponse = response.asString();
//singResponse = response.asString();

return signNewResponse;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package io.mosip.testrig.apirig.utils;

import lombok.Data;

@Data
public class CertificateChainResponseDto {

String caCertificate;

String interCertificate;

String partnerCertificate;
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
package io.mosip.testrig.apirig.utils;

import java.io.File;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.util.HashMap;

import javax.ws.rs.core.MediaType;
@@ -30,12 +33,12 @@ public static void getThumbprints() {
return ;
}
String appId = properties.getProperty("appIdForCertificate");
getAndUploadIdaCertificate(appId, properties.getProperty("partnerrefId"), properties.getProperty("uploadPartnerurl"));
getAndUploadIdaCertificate(appId, properties.getProperty("internalrefId"), properties.getProperty("uploadInternalurl"));
getAndUploadIdaCertificate(appId, properties.getProperty("idaFirRefId"), properties.getProperty("uploadIdaFirurl"));
getAndUploadIdaCertificate(appId, properties.getProperty("partnerrefId"), CertificateTypes.PARTNER);
getAndUploadIdaCertificate(appId, properties.getProperty("internalrefId"), CertificateTypes.INTERNAL);
getAndUploadIdaCertificate(appId, properties.getProperty("idaFirRefId"), CertificateTypes.IDA_FIR);
}

public static void getAndUploadIdaCertificate(String applicationId, String referenceId, String endPoint) {
public static void getAndUploadIdaCertificate(String applicationId, String referenceId, CertificateTypes certificateType) {
String token = kernelAuthLib.getTokenByRole(GlobalConstants.RESIDENT);
String url = ApplnURI + properties.getProperty("getIdaCertificateUrl");
HashMap<String, String> map = new HashMap<>();
@@ -48,20 +51,30 @@ public static void getAndUploadIdaCertificate(String applicationId, String refer
JSONObject responseValue = (JSONObject) responseJson.get("response");
String idaCertValue = responseValue.getString("certificate");

JSONObject request = new JSONObject();
request.put("certData", idaCertValue);
// JSONObject request = new JSONObject();
// request.put("certData", idaCertValue);
// actualrequest.put(GlobalConstants.REQUEST, request);

if (endPoint.contains("$MODULENAME$")) {
endPoint = endPoint.replace("$MODULENAME$", BaseTestCase.certsForModule);
// if (endPoint.contains("$MODULENAME$")) {
// endPoint = endPoint.replace("$MODULENAME$", BaseTestCase.certsForModule);
// }
//
// if (endPoint.contains("$CERTSDIR$")) {
// endPoint = endPoint.replace("$CERTSDIR$", ConfigManager.getauthCertsPath());
// }
HashMap<String, String> requestBodyMap = new HashMap<>();
requestBodyMap.put("certData", idaCertValue);

AuthUtil authUtil = new AuthUtil();
try {
authUtil.uploadIDACertificate(certificateType, requestBodyMap, null, BaseTestCase.certsForModule, ApplnURI.replace("https://", ""));
} catch (CertificateException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

if (endPoint.contains("$CERTSDIR$")) {
endPoint = endPoint.replace("$CERTSDIR$", ConfigManager.getauthCertsPath());
}

Response reponse = RestClient.postRequest(ConfigManager.getAuthDemoServiceUrl() + "/" + endPoint,
request.toMap(), MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN);

// Response reponse = RestClient.postRequest(ConfigManager.getAuthDemoServiceUrl() + "/" + endPoint,
// request.toMap(), MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package io.mosip.testrig.apirig.utils;

public enum CertificateTypes {

INTERNAL("ida-internal.cer"),
PARTNER("ida-partner.cer"),
IDA_FIR("ida-fir.cer");

private String fileName;

private CertificateTypes(String fileName) {
this.fileName = fileName;
}

public String getFileName() {
return this.fileName;
}
}
Original file line number Diff line number Diff line change
@@ -4,7 +4,9 @@
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;
@@ -135,6 +137,9 @@ public class ConfigManager {
private static String ADMIN_USER_NAME = "admin_userName";

private static String PARTNER_URL_SUFFIX = "partnerUrlSuffix";

private static String MOSIP_COMPONENTS_BASE_URLS = "mosip_components_base_urls";
private static Map<String, String> mosip_components_base_urls = new HashMap<>();

private static String partnerUrlSuffix;

@@ -448,6 +453,26 @@ public static void init() {
userAdminName = System.getenv(ADMIN_USER_NAME) == null ? propsKernel.getProperty(ADMIN_USER_NAME)
: System.getenv(ADMIN_USER_NAME);
propsKernel.setProperty(ADMIN_USER_NAME, userAdminName);

String components_base_urls = System.getenv(MOSIP_COMPONENTS_BASE_URLS) == null
? propsKernel.getProperty(MOSIP_COMPONENTS_BASE_URLS)
: System.getenv(MOSIP_COMPONENTS_BASE_URLS);
loadComponentBaseURLs(components_base_urls);
}

public static void loadComponentBaseURLs(String components_base_urls) {
if (components_base_urls != null && !components_base_urls.isEmpty()) {
// Split the input string by semicolons
String[] pairs = components_base_urls.split(";");

// Iterate over the pairs and split each by the equals sign to get key and value
for (String pair : pairs) {
String[] keyValue = pair.split("=");
if (keyValue.length == 2) {
mosip_components_base_urls.put(keyValue[0], keyValue[1]);
}
}
}
}

public static boolean isInServiceNotDeployedList(String stringToFind) {
@@ -501,6 +526,10 @@ public static boolean isInTobeExecuteList(String stringToFind) {
return false;
}

public static String getComponentBaseURL(String component) {
return mosip_components_base_urls.get(component);
}

public static String getServerErrorsToMonitor() {
return serverErrorsToMonitor;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,353 @@
package io.mosip.testrig.apirig.utils;

import io.mosip.kernel.core.crypto.exception.InvalidParamSpecException;
import io.mosip.kernel.core.util.CryptoUtil;
import io.mosip.kernel.crypto.jce.constant.SecurityExceptionCodeConstant;
import io.mosip.kernel.crypto.jce.util.CryptoUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.digests.SHA256Digest;
import org.bouncycastle.crypto.encodings.OAEPEncoding;
import org.bouncycastle.crypto.engines.RSAEngine;
import org.bouncycastle.crypto.params.RSAKeyParameters;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.*;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.OAEPParameterSpec;
import javax.crypto.spec.PSource.PSpecified;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigInteger;
import java.security.*;
import java.security.KeyStore.PrivateKeyEntry;
import java.security.cert.Certificate;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.MGF1ParameterSpec;
import java.util.Arrays;
import java.util.Objects;

import static java.util.Arrays.copyOfRange;

@Slf4j
@Component
public class CryptoCoreUtil {

private final static String RSA_ECB_OAEP_PADDING = "RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING";

private final static int THUMBPRINT_LENGTH = 32;
private final static int NONCE = 12;
private final static int AADSize = 32;
public static final byte[] VERSION_RSA_2048 = "VER_R2".getBytes();

private static final String MGF1 = "MGF1";

private static final String HASH_ALGO = "SHA-256";

private static final String PKCS11_STORE_TYPE = "PKCS11";

// Used as a hack for softhsm oeap padding decryption usecase will be when we
// will use in HSM
@SuppressWarnings("java:S106")
private static final String RSA_ECB_NO_PADDING = "RSA/ECB/NoPadding"; // NOSONAR using the padding for allowing OAEP padding in PKCS11 library


@Value("${mosip.prependThumbprint:true}")
private boolean isThumbprint;

@Value("${mosip.kernel.crypto.asymmetric-algorithm-name:" + RSA_ECB_OAEP_PADDING + "}")
private String asymmetricAlgorithm;

@Value("${mosip.kernel.keymanager.hsm.keystore-type:PKCS11}")
private String keystoreType;

@Value("${mosip.kernel.keygenerator.asymmetric-key-length:2048}")
private int asymmetricKeyLength;


public String decrypt(String data, PrivateKeyEntry privateKeyEntry) throws Exception {
try {
byte[] dataBytes = CryptoUtil.decodeURLSafeBase64(data);
byte[] decryptedDataBytes = decryptData(dataBytes, privateKeyEntry);
return new String(decryptedDataBytes);
}catch (Exception e){
log.error( "Not able to decrypt the data : {}", e);
}
throw new Exception("Unknown decryption exception.");
}

public byte[] decryptData(byte[] requestData, PrivateKeyEntry privateKey) throws Exception {
String keySplitter = "#KEY_SPLITTER#";
SecretKey symmetricKey = null;
byte[] encryptedData = null;
byte[] encryptedSymmetricKey = null;
final int cipherKeyandDataLength = requestData.length;
final int keySplitterLength = keySplitter.length();

int keyDemiliterIndex = getSplitterIndex(requestData, 0, keySplitter);
byte[] encryptedKey = copyOfRange(requestData, 0, keyDemiliterIndex);
byte[] headerBytes = parseEncryptKeyHeader(encryptedKey);
byte[] decryptedSymmetricKey = null;
try {
encryptedData = copyOfRange(requestData, keyDemiliterIndex + keySplitterLength, cipherKeyandDataLength);
if (Arrays.equals(headerBytes, VERSION_RSA_2048)) {
encryptedSymmetricKey = Arrays.copyOfRange(encryptedKey, THUMBPRINT_LENGTH + VERSION_RSA_2048.length,
encryptedKey.length);
byte[] aad = Arrays.copyOfRange(encryptedData, 0, AADSize);
byte[] nonce = Arrays.copyOfRange(aad, 0, NONCE);
byte[] encData = Arrays.copyOfRange(encryptedData, AADSize, encryptedData.length);
decryptedSymmetricKey = asymmetricDecrypt(privateKey.getPrivateKey(),
((RSAPrivateKey) privateKey.getPrivateKey()).getModulus(), encryptedSymmetricKey);
symmetricKey = new SecretKeySpec(decryptedSymmetricKey, 0, decryptedSymmetricKey.length, "AES");
return symmetricDecrypt(symmetricKey, encData, nonce, aad);
} else if (isThumbprint) {
encryptedSymmetricKey = Arrays.copyOfRange(encryptedKey, THUMBPRINT_LENGTH, encryptedKey.length);
decryptedSymmetricKey = asymmetricDecrypt(privateKey.getPrivateKey(),
((RSAPrivateKey) privateKey.getPrivateKey()).getModulus(), encryptedSymmetricKey);
symmetricKey = new SecretKeySpec(decryptedSymmetricKey, 0, decryptedSymmetricKey.length, "AES");
return symmetricDecrypt(symmetricKey, encryptedData, null);
} else {
decryptedSymmetricKey = asymmetricDecrypt(privateKey.getPrivateKey(),
((RSAPrivateKey) privateKey.getPrivateKey()).getModulus(), encryptedKey);
symmetricKey = new SecretKeySpec(decryptedSymmetricKey, 0, decryptedSymmetricKey.length, "AES");
return symmetricDecrypt(symmetricKey, encryptedData, null);
}
} catch (Exception e) {
log.error( "Not able to decrypt the data : {}", e);
}
throw new Exception("Unknown decryption exception.");
}

public byte[] parseEncryptKeyHeader(byte[] encryptedKey) {
byte[] versionHeaderBytes = Arrays.copyOfRange(encryptedKey, 0, VERSION_RSA_2048.length);
if (!Arrays.equals(versionHeaderBytes, VERSION_RSA_2048)) {
return new byte[0];
}
return versionHeaderBytes;
}

private static int getSplitterIndex(byte[] encryptedData, int keyDemiliterIndex, String keySplitter) {
final byte keySplitterFirstByte = keySplitter.getBytes()[0];
final int keySplitterLength = keySplitter.length();
for (byte data : encryptedData) {
if (data == keySplitterFirstByte) {
final String keySplit = new String(
copyOfRange(encryptedData, keyDemiliterIndex, keyDemiliterIndex + keySplitterLength));
if (keySplitter.equals(keySplit)) {
break;
}
}
keyDemiliterIndex++;
}
return keyDemiliterIndex;
}

/**
*
* @param privateKey
* @param keyModulus
* @param data
* @return
* @throws IllegalBlockSizeException
* @throws BadPaddingException
* @throws NoSuchAlgorithmException
* @throws NoSuchPaddingException
* @throws InvalidAlgorithmParameterException
* @throws InvalidKeyException
*/
private static byte[] asymmetricDecrypt(PrivateKey privateKey, BigInteger keyModulus, byte[] data)
throws IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException,
InvalidAlgorithmParameterException, InvalidKeyException {

Cipher cipher;
try {
cipher = Cipher.getInstance(RSA_ECB_OAEP_PADDING);
OAEPParameterSpec oaepParams = new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256,
PSpecified.DEFAULT);
cipher.init(Cipher.DECRYPT_MODE, privateKey, oaepParams);
return cipher.doFinal(data);
} catch (NoSuchAlgorithmException e) {
log.error("Not able to decrypt the data : {}" , e);
throw new NoSuchAlgorithmException(e);
} catch (NoSuchPaddingException e) {
throw new NoSuchPaddingException(e.getMessage());
} catch (InvalidKeyException e) {
throw new InvalidKeyException(e);
} catch (InvalidAlgorithmParameterException e) {
throw new InvalidAlgorithmParameterException(e);
}
}

private static byte[] symmetricDecrypt(SecretKey key, byte[] data, byte[] aad) {
byte[] output = null;
try {
Cipher cipher = Cipher.getInstance("AES/GCM/PKCS5Padding");
byte[] randomIV = Arrays.copyOfRange(data, data.length - cipher.getBlockSize(), data.length);
SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "AES");
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, randomIV);

cipher.init(Cipher.DECRYPT_MODE, keySpec, gcmParameterSpec);
if (aad != null && aad.length != 0) {
cipher.updateAAD(aad);
}
output = cipher.doFinal(Arrays.copyOf(data, data.length - cipher.getBlockSize()));
} catch (Exception e) {

}
return output;
}

public byte[] symmetricDecrypt(SecretKey key, byte[] data, byte[] nonce, byte[] aad)
throws Exception {
// Objects.requireNonNull(key, null);
// CryptoUtils.verifyData(data);
byte[] output = null;
Cipher cipher;
try {
cipher = Cipher.getInstance("AES/GCM/PKCS5Padding");
SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "AES");
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, nonce);
cipher.init(Cipher.DECRYPT_MODE, keySpec, gcmParameterSpec);
if (aad != null) {
cipher.updateAAD(aad);
}
output = cipher.doFinal(data, 0, data.length);
} catch (InvalidAlgorithmParameterException e) {
throw new Exception("Invalid key exception.", e);
} catch (IllegalBlockSizeException e) {
throw new Exception("Invalid key exception.", e);
} catch (BadPaddingException e) {
throw new Exception("Certificate thumbprint error.", e);
} catch (NoSuchAlgorithmException e) {
throw new Exception("Certificate thumbprint error.", e);
} catch (NoSuchPaddingException e) {
throw new Exception("Certificate thumbprint error.", e);
} catch (InvalidKeyException e) {
throw new Exception("Invalid key exception.", e);
}
return output;
}

public static byte[] getCertificateThumbprint(Certificate cert) throws Exception {
try {
return DigestUtils.sha256(cert.getEncoded());
} catch (java.security.cert.CertificateEncodingException e) {
throw new Exception("Invalid key exception.", e);
}
}

public byte[] asymmetricEncrypt(PublicKey key, byte[] data) throws GeneralSecurityException {
Objects.requireNonNull(key, SecurityExceptionCodeConstant.MOSIP_INVALID_KEY_EXCEPTION.getErrorMessage());
CryptoUtils.verifyData(data);
Cipher cipher;
try {
cipher = Cipher.getInstance(asymmetricAlgorithm);
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
throw e;
}
final OAEPParameterSpec oaepParams = new OAEPParameterSpec(HASH_ALGO, MGF1, MGF1ParameterSpec.SHA256,
PSpecified.DEFAULT);
try {
cipher.init(Cipher.ENCRYPT_MODE, key, oaepParams);
} catch (InvalidKeyException e) {
throw e;
} catch (InvalidAlgorithmParameterException e) {
throw new InvalidParamSpecException(
SecurityExceptionCodeConstant.MOSIP_INVALID_PARAM_SPEC_EXCEPTION.getErrorCode(),
SecurityExceptionCodeConstant.MOSIP_INVALID_PARAM_SPEC_EXCEPTION.getErrorMessage(), e);
}
return doFinal(data, cipher);
}

public byte[] asymmetricDecrypt(PrivateKey privateKey, byte[] data) throws GeneralSecurityException, InvalidCipherTextException {
if (PKCS11_STORE_TYPE.equalsIgnoreCase(keystoreType)) {
BigInteger keyModulus = ((RSAPrivateKey) privateKey).getModulus();
return asymmetricDecrypt(privateKey, keyModulus, data, null);
}
return jceAsymmetricDecrypt(privateKey, data, null);
}

private byte[] asymmetricDecrypt(PrivateKey privateKey, BigInteger keyModulus, byte[] data, String storeType) throws GeneralSecurityException, InvalidCipherTextException {
Objects.requireNonNull(privateKey, SecurityExceptionCodeConstant.MOSIP_INVALID_KEY_EXCEPTION.getErrorMessage());
CryptoUtils.verifyData(data);
Cipher cipher;
try {
cipher = Objects.isNull(storeType) ? Cipher.getInstance(RSA_ECB_NO_PADDING) : // NOSONAR using the padding for allowing OAEP padding in PKCS11 library
Cipher.getInstance(RSA_ECB_NO_PADDING, storeType); // NOSONAR using the padding for allowing OAEP padding in PKCS11 library
} catch (NoSuchAlgorithmException | NoSuchPaddingException | NoSuchProviderException e) {
throw e;
}

try {
cipher.init(Cipher.DECRYPT_MODE, privateKey);
} catch (InvalidKeyException e) {
throw e;
}
/*
* This is a hack of removing OEAP padding after decryption with NO Padding as
* SoftHSM does not support it.Will be removed after HSM implementation
*/
byte[] paddedPlainText = doFinal(data, cipher);
if (paddedPlainText.length < asymmetricKeyLength / 8) {
byte[] tempPipe = new byte[asymmetricKeyLength / 8];
System.arraycopy(paddedPlainText, 0, tempPipe, tempPipe.length - paddedPlainText.length,
paddedPlainText.length);
paddedPlainText = tempPipe;
}

return unpadOAEPPadding(paddedPlainText, keyModulus);
}

// This is a hack of removing OEAP padding after decryption with NO Padding as
// SoftHSM does not support it.Will be removed after HSM implementation
/**
*
* @param paddedPlainText
* @param privateKey
* @return
* @throws InvalidCipherTextException
*/
private byte[] unpadOAEPPadding(byte[] paddedPlainText, BigInteger keyModulus) throws InvalidCipherTextException {

try {
OAEPEncoding encode = new OAEPEncoding(new RSAEngine(), new SHA256Digest());
BigInteger exponent = new BigInteger("1");
RSAKeyParameters keyParams = new RSAKeyParameters(false, keyModulus, exponent);
encode.init(false, keyParams);
return encode.processBlock(paddedPlainText, 0, paddedPlainText.length);
} catch (InvalidCipherTextException e) {
throw e;
}
}

private byte[] jceAsymmetricDecrypt(PrivateKey privateKey, byte[] data, String storeType) throws GeneralSecurityException{
Objects.requireNonNull(privateKey, SecurityExceptionCodeConstant.MOSIP_INVALID_KEY_EXCEPTION.getErrorMessage());
CryptoUtils.verifyData(data);
Cipher cipher;
try {
cipher = Objects.isNull(storeType) ? Cipher.getInstance(asymmetricAlgorithm) :
Cipher.getInstance(asymmetricAlgorithm, storeType);
OAEPParameterSpec oaepParams = new OAEPParameterSpec(HASH_ALGO, MGF1, MGF1ParameterSpec.SHA256,
PSpecified.DEFAULT);
cipher.init(Cipher.DECRYPT_MODE, privateKey, oaepParams);
return doFinal(data, cipher);
} catch (NoSuchAlgorithmException | NoSuchPaddingException | NoSuchProviderException e) {
throw e;
} catch (InvalidKeyException e) {
throw e;
} catch (InvalidAlgorithmParameterException e) {
throw e;
}
}

private byte[] doFinal(byte[] data, Cipher cipher) throws IllegalBlockSizeException, BadPaddingException {
try {
return cipher.doFinal(data);
} catch (IllegalBlockSizeException e) {
throw e;
} catch (BadPaddingException e) {
throw e;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
package io.mosip.testrig.apirig.utils;

import io.mosip.kernel.core.crypto.spi.CryptoCoreSpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.crypto.*;
import java.security.*;


/**
* The Class CryptoUtility is used for encryption and decryption.
*
* @author Arun Bose S
* The Class CryptoUtil.
*/
@Component
public class CryptoUtil {

/** The Constant SYM_ALGORITHM. */
private static final String SYM_ALGORITHM = "AES";

/** The Constant SYM_ALGORITHM_LENGTH. */
private static final int SYM_ALGORITHM_LENGTH = 256;

/** The bouncy castle provider. */
private static BouncyCastleProvider bouncyCastleProvider;

static {
bouncyCastleProvider = addProvider();
}

/**
* {@link CryptoCoreSpec} instance for cryptographic functionalities.
*/
@Autowired
private CryptoCoreSpec<byte[], byte[], SecretKey, PublicKey, PrivateKey, String> cryptoCore;



/**
* Symmetric encrypt.
*
* @param data the data
* @param secretKey the secret key
* @return the byte[]
* @throws NoSuchAlgorithmException the no such algorithm exception
* @throws NoSuchPaddingException the no such padding exception
* @throws InvalidKeyException the invalid key exception
* @throws InvalidAlgorithmParameterException the invalid algorithm parameter exception
* @throws IllegalBlockSizeException the illegal block size exception
* @throws BadPaddingException the bad padding exception
*/
public byte[] symmetricEncrypt(byte[] data, SecretKey secretKey)
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
return cryptoCore.symmetricEncrypt(secretKey, data, null);

}



/**
* Symmetric decrypt.
*
* @param secretKey the secret key
* @param encryptedDataByteArr the encrypted data byte arr
* @return the byte[]
* @throws NoSuchAlgorithmException the no such algorithm exception
* @throws NoSuchPaddingException the no such padding exception
* @throws InvalidKeyException the invalid key exception
* @throws IllegalBlockSizeException the illegal block size exception
* @throws BadPaddingException the bad padding exception
* @throws InvalidAlgorithmParameterException the invalid algorithm parameter exception
*/
public byte[] symmetricDecrypt(SecretKey secretKey, byte[] encryptedDataByteArr) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException {
return cryptoCore.symmetricDecrypt(secretKey, encryptedDataByteArr, null);
}

/**
* Adds the provider.
*
* @return the bouncy castle provider
*/
private static BouncyCastleProvider addProvider() {
BouncyCastleProvider bouncyCastleProvider = new BouncyCastleProvider();
Security.addProvider(bouncyCastleProvider);
return bouncyCastleProvider;
}

/**
* Gen sec key.
*
* @return the secret key
* @throws NoSuchAlgorithmException the no such algorithm exception
*/
public SecretKey genSecKey() throws NoSuchAlgorithmException {
KeyGenerator keyGen;
SecretKey secretKey = null;
keyGen = KeyGenerator.getInstance(CryptoUtil.SYM_ALGORITHM, bouncyCastleProvider);
keyGen.init(CryptoUtil.SYM_ALGORITHM_LENGTH, new SecureRandom());
secretKey = keyGen.generateKey();
return secretKey;

}

/**
* Asymmetric encrypt.
*
* @param data the data
* @param publicKey the public key
* @return the byte[]
* @throws NoSuchAlgorithmException the no such algorithm exception
* @throws NoSuchPaddingException the no such padding exception
* @throws InvalidKeyException the invalid key exception
* @throws IllegalBlockSizeException the illegal block size exception
* @throws BadPaddingException the bad padding exception
*/
public byte[] asymmetricEncrypt(byte[] data, PublicKey publicKey) throws NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
return cryptoCore.asymmetricEncrypt(publicKey, data);
}

public byte[] symmetricEncrypt(byte[] data, SecretKey secretKey, byte[] iv, byte[] aad)
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
return cryptoCore.symmetricEncrypt(secretKey, data, iv, aad);

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,288 @@
package io.mosip.testrig.apirig.utils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.IntStream;

import javax.crypto.SecretKey;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.xml.bind.DatatypeConverter;

import org.apache.commons.codec.binary.Base64;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpRequest;
import org.springframework.http.ResponseCookie;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.util.UriComponentsBuilder;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

import io.mosip.authentication.core.constant.IdAuthConfigKeyConstants;
import io.mosip.kernel.core.http.RequestWrapper;
import io.mosip.kernel.core.util.DateUtils;
import io.mosip.kernel.core.util.HMACUtils2;
import io.mosip.testrig.apirig.dto.EncryptionRequestDto;
import io.mosip.testrig.apirig.dto.EncryptionResponseDto;
@Component
public class Encrypt {

private static final String SSL = "SSL";
String publicKeyURL = "${mosip.ida.publicKey-url}";
String appID = "${application.id}";

String keySplitter = "#KEY_SPLITTER#";

@Autowired
CryptoUtil cryptoUtil;

// public EncryptionResponseDto encrypt(EncryptionRequestDto encryptionRequestDto,
// String refId,
// boolean isInternal,
// boolean isBiometrics) throws Exception {
// if (refId == null) {
// refId = getRefId(isInternal, isBiometrics);
// }
// return kernelEncrypt(encryptionRequestDto, refId);
// }

// private EncryptionResponseDto kernelEncrypt(EncryptionRequestDto encryptionRequestDto, String refId)
// throws Exception {
// ObjectMapper objMapper = new ObjectMapper();
//
// String identityBlock = objMapper.writeValueAsString(encryptionRequestDto.getIdentityRequest());
// SecretKey secretKey = cryptoUtil.genSecKey();
// EncryptionResponseDto encryptionResponseDto = new EncryptionResponseDto();
// byte[] encryptedIdentityBlock = cryptoUtil.symmetricEncrypt(identityBlock.getBytes(StandardCharsets.UTF_8),
// secretKey);
// encryptionResponseDto.setEncryptedIdentity(Base64.encodeBase64URLSafeString(encryptedIdentityBlock));
// X509Certificate x509Cert = getCertificate(refId);
// PublicKey publicKey = x509Cert.getPublicKey();
// byte[] encryptedSessionKeyByte = cryptoUtil.asymmetricEncrypt((secretKey.getEncoded()), publicKey);
// encryptionResponseDto.setEncryptedSessionKey(Base64.encodeBase64URLSafeString(encryptedSessionKeyByte));
// byte[] byteArr = cryptoUtil.symmetricEncrypt(Encrypt
// .digestAsPlainText(HMACUtils2.generateHash(identityBlock.getBytes(StandardCharsets.UTF_8))).getBytes(),
// secretKey);
// encryptionResponseDto.setRequestHMAC(Base64.encodeBase64URLSafeString(byteArr));
// return encryptionResponseDto;
// }

// private String getRefId(boolean isInternal, boolean isBiometrics) {
// String refId;
// if (isBiometrics) {
// if (isInternal) {
// refId = PropertiesReader.readProperty(IdAuthConfigKeyConstants.INTERNAL_BIO_REFERENCE_ID);
// } else {
// refId = PropertiesReader.readProperty(IdAuthConfigKeyConstants.PARTNER_BIO_REFERENCE_ID);
// }
// } else {
// if (isInternal) {
// refId = PropertiesReader.readProperty(IdAuthConfigKeyConstants.INTERNAL_REFERENCE_ID);
// } else {
// refId = PropertiesReader.readProperty(IdAuthConfigKeyConstants.PARTNER_REFERENCE_ID);
// }
// }
// return refId;
// }

// @SuppressWarnings({"unchecked", "rawtypes"})
// public X509Certificate getCertificate(String refId) throws IOException, KeyManagementException,
// NoSuchAlgorithmException, JSONException, CertificateException {
// turnOffSslChecking();
// RestTemplate restTemplate = new RestTemplate();
// ClientHttpRequestInterceptor interceptor = new ClientHttpRequestInterceptor() {
//
// @Override
// public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
// throws IOException {
// String authToken = generateAuthToken();
// if (authToken != null && !authToken.isEmpty()) {
// request.getHeaders().set("Cookie", "Authorization=" + authToken);
// }
// return execution.execute(request, body);
// }
// };
//
// restTemplate.setInterceptors(Collections.singletonList(interceptor));
//
// Map<String, String> uriParams = new HashMap<>();
// UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(publicKeyURL)
// .queryParam("applicationId", appID).queryParam("referenceId", refId);
// ResponseEntity<Map> response = restTemplate.exchange(builder.build(uriParams), HttpMethod.GET, null, Map.class);
// String certificate = (String) ((Map<String, Object>) response.getBody().get("response")).get("certificate");
//
// certificate = JWSSignAndVerifyController.trimBeginEnd(certificate);
// CertificateFactory cf = CertificateFactory.getInstance("X.509");
// X509Certificate x509cert = (X509Certificate) cf
// .generateCertificate(new ByteArrayInputStream(java.util.Base64.getDecoder().decode(certificate)));
// return x509cert;
// }

private static String digestAsPlainText(byte[] data) {
return DatatypeConverter.printHexBinary(data).toUpperCase();
}

public static void turnOffSslChecking() throws NoSuchAlgorithmException, KeyManagementException {
// Install the all-trusting trust manager
final SSLContext sc = SSLContext.getInstance(Encrypt.SSL);
sc.init(null, UNQUESTIONING_TRUST_MANAGER, null);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}

private static final TrustManager[] UNQUESTIONING_TRUST_MANAGER = new TrustManager[]{new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}

public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
throws CertificateException {
}

public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String arg1)
throws CertificateException {
}
}};

// private String generateAuthToken() {
//
// ObjectMapper objMapper = new ObjectMapper();
// ObjectNode requestBody = objMapper.createObjectNode();
//// requestBody.put("clientId", env.getProperty("auth-token-generator.rest.clientId"));
//// requestBody.put("secretKey", env.getProperty("auth-token-generator.rest.secretKey"));
//// requestBody.put("appId", env.getProperty("auth-token-generator.rest.appId"));
// requestBody.put("clientId", "mosip-resident-client");
// requestBody.put("secretKey", "SnZQ6nnVwN9YWvdM");
// requestBody.put("appId", "resident");
// RequestWrapper<ObjectNode> request = new RequestWrapper<>();
// request.setRequesttime(DateUtils.getUTCCurrentDateTime());
// request.setRequest(requestBody);
// ClientResponse response = WebClient.create(PropertiesReader.readProperty("auth-token-generator.rest.uri")).post()
// .syncBody(request).exchange().block();
// List<ResponseCookie> list = response.cookies().get("Authorization");
// if (list != null && !list.isEmpty()) {
// ResponseCookie responseCookie = list.get(0);
// return responseCookie.getValue();
// }
// return "";
// }

public SplittedEncryptedData splitEncryptedData(String data) throws Exception {
//boolean encryptedDataHasVersion = env.getProperty("encryptedDataHasVersion", boolean.class, false);
boolean encryptedDataHasVersion = false;
byte[] dataBytes = io.mosip.kernel.core.util.CryptoUtil.decodeURLSafeBase64(data);
byte[][] splits = splitAtFirstOccurance(dataBytes, keySplitter.getBytes());
byte[] thumbPrintAndSessionKey = splits[0];
byte[] sessionKey;
byte[] thumbPrint;

if (thumbPrintAndSessionKey.length >= 288) {
thumbPrint = Arrays.copyOfRange(thumbPrintAndSessionKey, thumbPrintAndSessionKey.length - 288,
thumbPrintAndSessionKey.length - 256);// Skip the 6 bytes version and take 32 bytes
sessionKey = Arrays.copyOfRange(thumbPrintAndSessionKey, thumbPrintAndSessionKey.length - 256,
thumbPrintAndSessionKey.length);
} else {
throw new Exception("Invalid Encrypted Session Key");
}

byte[] encryptedData = splits[1];
return new SplittedEncryptedData(io.mosip.kernel.core.util.CryptoUtil.encodeToURLSafeBase64(sessionKey), io.mosip.kernel.core.util.CryptoUtil.encodeToURLSafeBase64(encryptedData), digestAsPlainText(thumbPrint));
}

public static class SplittedEncryptedData {
private String encryptedSessionKey;
private String encryptedData;
private String thumbprint;

public SplittedEncryptedData() {
super();
}

public SplittedEncryptedData(String encryptedSessionKey, String encryptedData) {
super();
this.encryptedData = encryptedData;
this.encryptedSessionKey = encryptedSessionKey;
}

public SplittedEncryptedData(String encryptedSessionKey, String encryptedData, String thumbprint) {
super();
this.encryptedData = encryptedData;
this.encryptedSessionKey = encryptedSessionKey;
this.thumbprint = thumbprint;
}

public String getEncryptedData() {
return encryptedData;
}

public void setEncryptedData(String encryptedData) {
this.encryptedData = encryptedData;
}

public String getEncryptedSessionKey() {
return encryptedSessionKey;
}

public void setEncryptedSessionKey(String encryptedSessionKey) {
this.encryptedSessionKey = encryptedSessionKey;
}

public String getThumbprint() {
return thumbprint;
}

public void setThumbprint(String thumbprint) {
this.thumbprint = thumbprint;
}
}

private static byte[][] splitAtFirstOccurance(byte[] strBytes, byte[] sepBytes) {
int index = findIndex(strBytes, sepBytes);
if (index >= 0) {
byte[] bytes1 = new byte[index];
byte[] bytes2 = new byte[strBytes.length - (bytes1.length + sepBytes.length)];
System.arraycopy(strBytes, 0, bytes1, 0, bytes1.length);
System.arraycopy(strBytes, (bytes1.length + sepBytes.length), bytes2, 0, bytes2.length);
return new byte[][]{bytes1, bytes2};
} else {
return new byte[][]{strBytes, new byte[0]};
}
}

private static int findIndex(byte arr[], byte[] subarr) {
int len = arr.length;
int subArrayLen = subarr.length;
return IntStream.range(0, len).filter(currentIndex -> {
if ((currentIndex + subArrayLen) <= len) {
byte[] sArray = new byte[subArrayLen];
System.arraycopy(arr, currentIndex, sArray, 0, subArrayLen);
return Arrays.equals(sArray, subarr);
}
return false;
}).findFirst() // first occurence
.orElse(-1); // No element found
}
}

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -21,6 +21,7 @@

import io.mosip.testrig.apirig.testrunner.JsonPrecondtion;


/**
* Class is to perform all file util such as create,read files
*
Original file line number Diff line number Diff line change
@@ -26,12 +26,74 @@ public class GlobalMethods {

public static Set<String> serverEndpoints = new HashSet<>();

// Define the regex pattern to extract the domain and the path after the domain
private static final String regex_1 = "https://([^/]+)/(v[0-9]+)?/(partnermanager|masterdata|idgenerator|policymanager|idauthentication|idrepository|auditmanager)/([^,]+)";
private static final String regex_2 = "https://([^/]+)/(partnermanager|masterdata|idgenerator|policymanager|idauthentication|idrepository|auditmanager)/(v[0-9]+)/([^,]+)";

// Compile the regex pattern
private static final Pattern pattern_1 = Pattern.compile(regex_1);
private static final Pattern pattern_2 = Pattern.compile(regex_2);

public static void main(String[] arg) {

}

public static String getUpdatedEndPointURL(String url) {
// Create a matcher for the current URL
Matcher matcher = pattern_1.matcher(url);
// Check if the first pattern matches
if (matcher.find()) {
String domain = matcher.group(1);
String version = matcher.group(2) != null ? matcher.group(2) : ""; // Handle null for optional group
String module = matcher.group(3);
String endpoint = version + "/" + module + "/" + matcher.group(4);

logger.info(
"Domain: " + domain + " ---- Module: " + module + " ---- End Point: " + removeNumerics(endpoint));

// Replace BaseURL if provided from outside
String newBaseURL = ConfigManager.getComponentBaseURL(module);

if (newBaseURL != null && !newBaseURL.isEmpty()) {
// Replace the part in the URL
return url.replace(domain, newBaseURL);
} else {
return url;
}
}

// RegEX didn't match, try with other pattern...

// Create a matcher for the current URL
Matcher matcher2 = pattern_2.matcher(url);
// Check if the second pattern matches
if (matcher.find()) {
String domain = matcher2.group(1);
String module = matcher2.group(2) != null ? matcher2.group(2) : ""; // Handle null for optional group
String version = matcher2.group(3);
String endpoint = module + "/" + version + "/" + matcher2.group(4);
logger.info(
"Domain: " + domain + " ---- Module: " + module + " ---- End Point: " + removeNumerics(endpoint));

// Replace BaseURL if provided from outside
String newBaseURL = ConfigManager.getComponentBaseURL(module);

if (newBaseURL != null && !newBaseURL.isEmpty()) {
// Replace the part in the URL
return url.replace(domain, newBaseURL);
} else {
return url;
}
}

// Both RegEx didn't match.. Needs revisit..
logger.error("Needs RegEx revisit...");
return url;
}

public static void addToServerEndPointMap(String url) {
serverEndpoints.add(url);
String updatedURL = getUpdatedEndPointURL(url);
serverEndpoints.add(updatedURL);
}

public static String removeNumerics(String url) {
@@ -53,59 +115,56 @@ public static String removeNumerics(String url) {

public static String getComponentDetails() {
// Define the regex pattern to extract the domain and the path after the domain
String regex = "https://([^/]+)/(v[0-9]+)?/(partnermanager|masterdata|idgenerator|policymanager|idauthentication|idrepository)/([^,]+)";
// Compile the regex pattern
Pattern pattern = Pattern.compile(regex);
// Set to store unique results
Set<String> uniqueResults = new HashSet<>();
// Iterate over the set of URLs
for (String url : serverEndpoints) {
// Create a matcher for the current URL
Matcher matcher = pattern.matcher(url);
// Find matches

while (matcher.find()) {
String domain = matcher.group(1);
String version = matcher.group(2) != null ? matcher.group(2) : ""; // Handle null for optional group
String module = matcher.group(3);
String endpoint = version + "/" + module + "/" + matcher.group(4);
String regex_1 = "https://([^/]+)/(v[0-9]+)?/(partnermanager|masterdata|idgenerator|policymanager|idauthentication|idrepository|auditmanager)/([^,]+)";
// Compile the regex pattern
Pattern pattern_1 = Pattern.compile(regex_1);

String regex_2 = "https://([^/]+)/(partnermanager|masterdata|idgenerator|policymanager|idauthentication|idrepository|auditmanager)/(v[0-9]+)/([^,]+)";
// Compile the regex pattern
Pattern pattern_2 = Pattern.compile(regex_2);

// Set to store unique results
Set<String> uniqueResults = new HashSet<>();
// Iterate over the set of URLs
for (String url : serverEndpoints) {

// Create a matcher for the current URL
Matcher matcher_1 = pattern_1.matcher(url);
// Find matches
if (matcher_1.find()) {
String domain = matcher_1.group(1);
String version = matcher_1.group(2) != null ? matcher_1.group(2) : ""; // Handle null for optional group
String module = matcher_1.group(3);
String endpoint = version + "/" + module + "/" + matcher_1.group(4);
String result = "Domain: " + domain + " ---- Module: " + module + " ---- End Point: "
+ removeNumerics(endpoint);
uniqueResults.add(result);
}
}

regex = "https://([^/]+)/(partnermanager|masterdata|idgenerator|policymanager|idauthentication|idrepository)/(v[0-9]+)/([^,]+)";
// Compile the regex pattern
pattern = Pattern.compile(regex);
// Iterate over the set of URLs
for (String url : serverEndpoints) {
// Create a matcher for the current URL
Matcher matcher = pattern.matcher(url);
// Find matches
while (matcher.find()) {
String domain = matcher.group(1);
String module = matcher.group(2) != null ? matcher.group(2) : ""; // Handle null for optional group
String version = matcher.group(3);
String endpoint = module + "/" + version + "/" + matcher.group(4);
String result = "Domain: " + domain + " ---- Module: " + module + " ---- End Point: "
+ removeNumerics(endpoint);
} else {
// Create a matcher for the current URL
Matcher matcher_2 = pattern_2.matcher(url);
// Find matches
if (matcher_2.find()) {
String domain = matcher_2.group(1);
String module = matcher_2.group(2) != null ? matcher_2.group(2) : ""; // Handle null for optional
// group
String version = matcher_2.group(3);
String endpoint = module + "/" + version + "/" + matcher_2.group(4);
String result = "Domain: " + domain + " ---- Module: " + module + " ---- End Point: "
+ removeNumerics(endpoint);
uniqueResults.add(result);
}
}
}

uniqueResults.add(result);
}
}



// Convert the set to an ArrayList
List<String> uniqueList = new ArrayList<>(uniqueResults);
StringBuilder stringBuilder = new StringBuilder();
// Print the unique results
for (String result : uniqueList) {
stringBuilder.append("\n").append(result);
}
return stringBuilder.toString();
}
// Convert the set to an ArrayList
List<String> uniqueList = new ArrayList<>(uniqueResults);
StringBuilder stringBuilder = new StringBuilder();
// Print the unique results
for (String result : uniqueList) {
stringBuilder.append("\n").append(result);
}
return stringBuilder.toString();
}

public static void reportServerError(Object code, Object errorMessage) {
serverFailuresMapS.put(code, errorMessage);
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package io.mosip.testrig.apirig.utils;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.UnrecoverableEntryException;
import java.security.KeyStore.PrivateKeyEntry;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

import io.swagger.annotations.Api;
import lombok.Data;



import org.bouncycastle.operator.OperatorCreationException;
import org.jose4j.jws.JsonWebSignature;
import org.jose4j.lang.JoseException;

public class JWSSignAndVerifyController {

private static final String SIGN_ALGO = "RS256";

public String sign(String dataToSign,
boolean includePayload,
boolean includeCertificate,
boolean includeCertHash,
String certificateUrl,
String dirPath,
PartnerTypes partnerType,
String organizationName,
boolean keyFileNameByPartnerName) throws JoseException, NoSuchAlgorithmException, UnrecoverableEntryException,
KeyStoreException, CertificateException, IOException, OperatorCreationException {

KeyMgrUtility keyMgrUtil = new KeyMgrUtility();
JsonWebSignature jwSign = new JsonWebSignature();
PrivateKeyEntry keyEntry = keyMgrUtil.getKeyEntry(dirPath, partnerType, organizationName,
keyFileNameByPartnerName);
if (Objects.isNull(keyEntry)) {
throw new KeyStoreException("Key file not available for partner type: " + partnerType.toString());
}

PrivateKey privateKey = keyEntry.getPrivateKey();
X509Certificate x509Certificate = (X509Certificate) keyEntry.getCertificate();
if (includeCertificate)
jwSign.setCertificateChainHeaderValue(new X509Certificate[] { x509Certificate });

if (includeCertHash)
jwSign.setX509CertSha256ThumbprintHeaderValue(x509Certificate);

if (Objects.nonNull(certificateUrl))
jwSign.setHeader("x5u", certificateUrl);

jwSign.setPayload(dataToSign);
jwSign.setAlgorithmHeaderValue(SIGN_ALGO);
jwSign.setKey(privateKey);
jwSign.setDoKeyValidation(false);
if (includePayload)
return jwSign.getCompactSerialization();

return jwSign.getDetachedContentCompactSerialization();

}
public static String trimBeginEnd(String pKey) {
pKey = pKey.replaceAll("-*BEGIN([^-]*)-*(\r?\n)?", "");
pKey = pKey.replaceAll("-*END([^-]*)-*(\r?\n)?", "");
pKey = pKey.replaceAll("\\s", "");
return pKey;
}
}
Original file line number Diff line number Diff line change
@@ -59,6 +59,7 @@




/**
* The Class KeyMgrUtil.
* @author Md. Taheer
@@ -371,7 +372,7 @@ public PrivateKeyEntry getKeyEntry(String dirPath, String parterId) throws NoSuc
KeyStoreException, CertificateException, IOException, OperatorCreationException {
String filePrepend = parterId;

String partnerFilePath = dirPath + '/' + filePrepend + PARTNER_P12_FILE_NAME;
String partnerFilePath = dirPath + '/' +PartnerRegistration.appendEkycOrRp+ filePrepend + PARTNER_P12_FILE_NAME;;
return getPrivateKeyEntry(partnerFilePath);
}

@@ -434,8 +435,8 @@ private char[] getP12Pass() {
* @return the keys dir path
*/
public String getKeysDirPath() {
String domain = System.getProperty(DOMAIN_URL, "localhost").replace("https://", "").replace("http://", "").replace("/", "");
return System.getProperty("java.io.tmpdir") + "/" + "IDA-" + domain;
String domain = System.getProperty("env.endpoint", "localhost").replace("https://", "").replace("http://", "").replace("/", "");
return System.getProperty("java.io.tmpdir") + "/" + "AUTHCERTS" + "/" + "IDA-" + domain;
}

/**
@@ -481,4 +482,30 @@ public static String trimBeginEnd(String pKey) {
pKey = pKey.replaceAll("\\s", "");
return pKey;
}

public X509Certificate getCertificate(String refId)
throws KeyStoreException, IOException, CertificateException {
String keysDirPath = getKeysDirPath();

String certFilePath = keysDirPath + '/' + "ida-partner.cer";
// String certFilePath = keysDirPath + '/' + "ida-" + "partner" + ".cer";
// String certFilePath = keysDirPath + '/' + "ida-internal.cer"; // bio auth
ByteArrayInputStream bIS = null;
try {
Path path = Paths.get(certFilePath);
if (Files.exists(path)) {
String cert = new String(Files.readAllBytes(path));

cert = trimBeginEnd(cert);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
bIS = new ByteArrayInputStream(Base64.getDecoder().decode(cert));
return (X509Certificate) cf
.generateCertificate(bIS);

}
return null;
} finally {
AdminTestUtil.closeByteArrayInputStream(bIS);
}
}
}

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package io.mosip.testrig.apirig.utils;

import java.io.File;
import java.util.HashMap;

import javax.ws.rs.core.MediaType;
@@ -8,6 +9,7 @@
import org.apache.log4j.Logger;
import org.json.JSONObject;

import io.mosip.testrig.apirig.dto.CertificateChainResponseDto;
import io.mosip.testrig.apirig.testrunner.BaseTestCase;
import io.restassured.response.Response;

@@ -31,9 +33,9 @@ public static void setLogLevel() {
}

public static String getAndUploadCertificatesAndGenerateMispLicKey() {
if (localHostUrl == null) {
localHostUrl = getLocalHostUrl();
}
// if (localHostUrl == null) {
// localHostUrl = getLocalHostUrl();
// }

mispPartnerGeneration();
JSONObject certificateValue = getCertificates(mispPartnerId, getPartnerType);
@@ -95,20 +97,50 @@ public static void mispPartnerGeneration() {
}

public static JSONObject getCertificates(String partnerId, String partnerType) {
String url = localHostUrl + properties.getProperty("getPartnerCertURL");

HashMap<String, String> map = new HashMap<>();

map.put("partnerName", partnerId);
map.put(GlobalConstants.PARTNERTYPE, partnerType);
map.put("moduleName", BaseTestCase.certsForModule);

Response response = RestClient.getRequestWithQueryParm(url, map, MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON);
lOGGER.info(response);
JSONObject responseJson = new JSONObject(response.asString());
lOGGER.info(responseJson);

AuthUtil authUtil = new AuthUtil();
PartnerTypes partnerTypeEnum = null;

if (partnerType.equals("RELYING_PARTY")) {
partnerTypeEnum = PartnerTypes.RELYING_PARTY;
} else if (partnerType.equals("DEVICE")) {
partnerTypeEnum = PartnerTypes.DEVICE;
}else if (partnerType.equals("FTM")) {
partnerTypeEnum = PartnerTypes.FTM;
}else if (partnerType.equals("EKYC")) {
partnerTypeEnum = PartnerTypes.EKYC;
}else if (partnerType.equals("MISP")) {
partnerTypeEnum = PartnerTypes.MISP;
}
boolean keyFileNameByPartnerName = false;
CertificateChainResponseDto certificateChainResponseDto = null;

try {
certificateChainResponseDto = authUtil.generatePartnerKeys(partnerTypeEnum, partnerId, keyFileNameByPartnerName, null, BaseTestCase.certsForModule, ApplnURI.replace("https://", ""));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject responseJson = new JSONObject();
responseJson.put("caCertificate", certificateChainResponseDto.getCaCertificate());
responseJson.put("interCertificate", certificateChainResponseDto.getInterCertificate());
responseJson.put("partnerCertificate", certificateChainResponseDto.getPartnerCertificate());
return responseJson;

// String url = localHostUrl + properties.getProperty("getPartnerCertURL");
//
// HashMap<String, String> map = new HashMap<>();
//
// map.put("partnerName", partnerId);
// map.put(GlobalConstants.PARTNERTYPE, partnerType);
// map.put("moduleName", BaseTestCase.certsForModule);
//
// Response response = RestClient.getRequestWithQueryParm(url, map, MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON);
// lOGGER.info(response);
// JSONObject responseJson = new JSONObject(response.asString());
// lOGGER.info(responseJson);
//
// return responseJson;
}

public static void uploadCACertificate(String certValueCA, String partnerDomain) {
@@ -191,20 +223,49 @@ public static JSONObject uploadPartnerCertificate(String certValuePartner, Strin
}

public static void uploadSignedCertificate(String certValueSigned, String partnerType) {
String url = localHostUrl + properties.getProperty("uploadSignedCertificateUrl");

HashMap<String, String> requestBody = new HashMap<>();
PartnerTypes partnerTypeEnum = null;
if (partnerType.equals("RELYING_PARTY")) {
partnerTypeEnum = PartnerTypes.RELYING_PARTY;
} else if (partnerType.equals("DEVICE")) {
partnerTypeEnum = PartnerTypes.DEVICE;
}else if (partnerType.equals("FTM")) {
partnerTypeEnum = PartnerTypes.FTM;
}else if (partnerType.equals("EKYC")) {
partnerTypeEnum = PartnerTypes.EKYC;
}else if (partnerType.equals("MISP")) {
partnerTypeEnum = PartnerTypes.MISP;
}


HashMap<String, String> requestBody = new HashMap<>();

requestBody.put("certData", certValueSigned);

HashMap<String, Object> queryParamMap = new HashMap<>();
AuthUtil authUtil = new AuthUtil();
try {
authUtil.updatePartnerCertificate(partnerTypeEnum, null, false, requestBody, null, BaseTestCase.certsForModule, ApplnURI.replace("https://", ""));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

queryParamMap.put(GlobalConstants.PARTNERTYPE, partnerType);
queryParamMap.put("moduleName", BaseTestCase.certsForModule);

Response response = RestClient.postRequestWithQueryParamsAndBody(url, requestBody, queryParamMap, MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN);

lOGGER.info(response);
// String url = localHostUrl + properties.getProperty("uploadSignedCertificateUrl");
//
// HashMap<String, String> requestBody = new HashMap<>();
//
// requestBody.put("certData", certValueSigned);
//
// HashMap<String, Object> queryParamMap = new HashMap<>();
//
// queryParamMap.put(GlobalConstants.PARTNERTYPE, partnerType);
// queryParamMap.put("moduleName", BaseTestCase.certsForModule);
//
// Response response = RestClient.postRequestWithQueryParamsAndBody(url, requestBody, queryParamMap, MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN);
//
// lOGGER.info(response);
}

public static String generateMispLicKey(String partnerId) {
Original file line number Diff line number Diff line change
@@ -617,5 +617,18 @@ public static void reportServerIssues(String responseString, TestCaseDTO testCas
}
}
}

public static Map<String, List<OutputValidationDto>> doJsonOutputValidation(String actualOutputJson,
String expOutputJson) {
try {
JsonPrecondtion jsonPrecondtion = new JsonPrecondtion();
Map<String, String> actual = jsonPrecondtion.retrieveMappingAndItsValueToPerformJsonOutputValidation(actualOutputJson);
Map<String, String> exp = jsonPrecondtion.retrieveMappingAndItsValueToPerformJsonOutputValidation(expOutputJson);
return compareActuExpValue(actual, exp, "expected vs actual");
} catch (Exception e) {
OUTPUTVALIDATION_LOGGER.error("Exceptione occured " + e.getMessage());
return null;
}
}

}
Original file line number Diff line number Diff line change
@@ -1,14 +1,22 @@
package io.mosip.testrig.apirig.utils;

import java.io.File;
import java.io.IOException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableEntryException;
import java.security.cert.CertificateException;
import java.util.Calendar;
import java.util.HashMap;

import javax.ws.rs.core.MediaType;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.bouncycastle.operator.OperatorCreationException;
import org.json.JSONObject;

import io.mosip.testrig.apirig.dto.CertificateChainResponseDto;
import io.mosip.testrig.apirig.testrunner.BaseTestCase;
import io.restassured.response.Response;

@@ -40,6 +48,7 @@ public class PartnerRegistration extends AdminTestUtil {
public static String updatedApiKey = "";
public static String kycApiKey = "";
public static String mispLicKey ="";
public static String appendEkycOrRp ="";
public static String policyGroup = AdminTestUtil.policyGroup;
public static String policyGroupForKyc = AdminTestUtil.policyGroup2;

@@ -58,10 +67,11 @@ public static String generateAndGetPartnerKeyUrl() {
partnerId = getPartnerIdFromPartnerURL(partnerKeyUrl);
return ConfigManager.getPartnerUrlSuffix();
}
getAndUploadCertificates();
ftmGeneration();
deviceGeneration();

getAndUploadCertificates();

apiKey = KeyCloakUserAndAPIKeyGeneration.createKCUserAndGetAPIKey();

mispLicKey = MispPartnerAndLicenseKeyGeneration.getAndUploadCertificatesAndGenerateMispLicKey();
@@ -133,7 +143,7 @@ public static void getAndUploadCertificates() {
JSONObject signedcertificateValue = uploadPartnerCertificate(partnerCertValue, "Auth", partnerId);

String certValueSigned = signedcertificateValue.getString("signedCertificateData");
lOGGER.info(certValueSigned);
lOGGER.info(certValueSigned);
uploadSignedCertificate(certValueSigned, getPartnerType, partnerId, true);

}
@@ -232,52 +242,112 @@ public static void partnerKycGeneration() {
}

public static JSONObject getCertificates(String partnerId, String partnerType) {
if (localHostUrl == null) {
localHostUrl = getLocalHostUrl();
// Need to update PartnerTypes.DEVICE with partnerType
PartnerTypes partnerTypeEnum = null;
if (partnerType.equals("RELYING_PARTY")) {
partnerTypeEnum = PartnerTypes.RELYING_PARTY;
} else if (partnerType.equals("DEVICE")) {
partnerTypeEnum = PartnerTypes.DEVICE;
}else if (partnerType.equals("FTM")) {
partnerTypeEnum = PartnerTypes.FTM;
}else if (partnerType.equals("EKYC")) {
partnerTypeEnum = PartnerTypes.EKYC;
}else if (partnerType.equals("MISP")) {
partnerTypeEnum = PartnerTypes.MISP;
}
AuthUtil authUtil = new AuthUtil();
boolean keyFileNameByPartnerName = true;
CertificateChainResponseDto certificateChainResponseDto = null;

try {
certificateChainResponseDto = authUtil.generatePartnerKeys(partnerTypeEnum, partnerId, keyFileNameByPartnerName, null, BaseTestCase.certsForModule, ApplnURI.replace("https://", ""));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String url = localHostUrl + properties.getProperty("getPartnerCertURL");

HashMap<String, String> map = new HashMap<>();

map.put("partnerName", partnerId);
map.put("partnerType", partnerType);
map.put("moduleName", BaseTestCase.certsForModule);
map.put("keyFileNameByPartnerName", GlobalConstants.TRUE_STRING);

String token = kernelAuthLib.getTokenByRole("partner");

Response response = RestClient.getRequestWithCookieAndQueryParm(url, map, MediaType.APPLICATION_JSON,
MediaType.APPLICATION_JSON, GlobalConstants.AUTHORIZATION, token);
lOGGER.info(response);
JSONObject responseJson = new JSONObject(response.asString());
lOGGER.info(responseJson);



// if (localHostUrl == null) {
// localHostUrl = getLocalHostUrl();
// }
// String url = localHostUrl + properties.getProperty("getPartnerCertURL");
//
// HashMap<String, String> map = new HashMap<>();
//
// map.put("partnerName", partnerId);
// map.put("partnerType", partnerType);
// map.put("moduleName", BaseTestCase.certsForModule);
// map.put("keyFileNameByPartnerName", GlobalConstants.TRUE_STRING);
//
// String token = kernelAuthLib.getTokenByRole("partner");

// Response response = RestClient.getRequestWithCookieAndQueryParm(url, map, MediaType.APPLICATION_JSON,
// MediaType.APPLICATION_JSON, GlobalConstants.AUTHORIZATION, token);
// lOGGER.info(response);
// JSONObject responseJson = new JSONObject(response.asString());
// lOGGER.info(responseJson);

JSONObject responseJson = new JSONObject();
responseJson.put("caCertificate", certificateChainResponseDto.getCaCertificate());
responseJson.put("interCertificate", certificateChainResponseDto.getInterCertificate());
responseJson.put("partnerCertificate", certificateChainResponseDto.getPartnerCertificate());
return responseJson;


}

public static JSONObject getDeviceCertificates(String partnerId, String partnerType) {
if (localHostUrl == null) {
localHostUrl = getLocalHostUrl();
}
String url = localHostUrl + properties.getProperty("getPartnerCertURL");

HashMap<String, String> map = new HashMap<>();

map.put("partnerName", partnerId);
map.put("partnerType", partnerType);
map.put("moduleName", BaseTestCase.certsForModule);
AuthUtil authUtil = new AuthUtil();
PartnerTypes partnerTypeEnum = null;

if (partnerType.equals("RELYING_PARTY")) {
partnerTypeEnum = PartnerTypes.RELYING_PARTY;
} else if (partnerType.equals("DEVICE")) {
partnerTypeEnum = PartnerTypes.DEVICE;
}else if (partnerType.equals("FTM")) {
partnerTypeEnum = PartnerTypes.FTM;
}else if (partnerType.equals("EKYC")) {
partnerTypeEnum = PartnerTypes.EKYC;
}else if (partnerType.equals("MISP")) {
partnerTypeEnum = PartnerTypes.MISP;
}
boolean keyFileNameByPartnerName = false;
CertificateChainResponseDto certificateChainResponseDto = null;
if (partnerType.equals("RELYING_PARTY") || partnerType.equals("MISP")) {
map.put("keyFileNameByPartnerName", GlobalConstants.TRUE_STRING);
keyFileNameByPartnerName = true;
}

String token = kernelAuthLib.getTokenByRole("partner");

Response response = RestClient.getRequestWithCookieAndQueryParm(url, map, MediaType.APPLICATION_JSON,
MediaType.APPLICATION_JSON, GlobalConstants.AUTHORIZATION, token);
lOGGER.info(response);
JSONObject responseJson = new JSONObject(response.asString());
lOGGER.info(responseJson);

try {
certificateChainResponseDto = authUtil.generatePartnerKeys(partnerTypeEnum, partnerId, keyFileNameByPartnerName, null, BaseTestCase.certsForModule, ApplnURI.replace("https://", ""));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// if (localHostUrl == null) {
// localHostUrl = getLocalHostUrl();
// }
// String url = localHostUrl + properties.getProperty("getPartnerCertURL");
//
// HashMap<String, String> map = new HashMap<>();
//
// map.put("partnerName", partnerId);
// map.put("partnerType", partnerType);
// map.put("moduleName", BaseTestCase.certsForModule);
// if (partnerType.equals("RELYING_PARTY") || partnerType.equals("MISP")) {
// map.put("keyFileNameByPartnerName", GlobalConstants.TRUE_STRING);
// }
//
// String token = kernelAuthLib.getTokenByRole("partner");
//
// Response response = RestClient.getRequestWithCookieAndQueryParm(url, map, MediaType.APPLICATION_JSON,
// MediaType.APPLICATION_JSON, GlobalConstants.AUTHORIZATION, token);
// lOGGER.info(response);
// JSONObject responseJson = new JSONObject(response.asString());
// lOGGER.info(responseJson);

JSONObject responseJson = new JSONObject();
responseJson.put("caCertificate", certificateChainResponseDto.getCaCertificate());
responseJson.put("interCertificate", certificateChainResponseDto.getInterCertificate());
responseJson.put("partnerCertificate", certificateChainResponseDto.getPartnerCertificate());
return responseJson;
}

@@ -365,27 +435,69 @@ public static JSONObject uploadPartnerCertificate(String certValuePartner, Strin

public static void uploadSignedCertificate(String certValueSigned, String partnerType, String partnerId,
Boolean keyFileNameByPartnerName) {
String url = localHostUrl + properties.getProperty("uploadSignedCertificateUrl");

PartnerTypes partnerTypeEnum = null;
if (partnerType.equals("RELYING_PARTY")) {
partnerTypeEnum = PartnerTypes.RELYING_PARTY;
} else if (partnerType.equals("DEVICE")) {
partnerTypeEnum = PartnerTypes.DEVICE;
}else if (partnerType.equals("FTM")) {
partnerTypeEnum = PartnerTypes.FTM;
}else if (partnerType.equals("EKYC")) {
partnerTypeEnum = PartnerTypes.EKYC;
}else if (partnerType.equals("MISP")) {
partnerTypeEnum = PartnerTypes.MISP;
}

keyFileNameByPartnerName = false;

if (partnerType.equals("RELYING_PARTY") || partnerType.equals("EKYC")) {
keyFileNameByPartnerName = true;
}
HashMap<String, String> requestBody = new HashMap<>();

requestBody.put("certData", certValueSigned);

HashMap<String, Object> queryParamMap = new HashMap<>();
queryParamMap.put("partnerName", partnerId);
queryParamMap.put("partnerType", partnerType);
queryParamMap.put("moduleName", BaseTestCase.certsForModule);
if (partnerType.equals("RELYING_PARTY")) {
queryParamMap.put("keyFileNameByPartnerName", keyFileNameByPartnerName);
}
if (partnerType.equals("EKYC")) {
queryParamMap.put("keyFileNameByPartnerName", keyFileNameByPartnerName);

AuthUtil authUtil = new AuthUtil();
try {
// String url = ConfigManager.getAuthDemoServiceUrl() + properties.getProperty("uploadSignedCertificateUrl");
//
//
// HashMap<String, Object> queryParamMap = new HashMap<>();
// queryParamMap.put("partnerName", partnerId);
// queryParamMap.put("partnerType", partnerType);
// queryParamMap.put("moduleName", BaseTestCase.certsForModule);
// if (partnerType.equals("RELYING_PARTY")) {
// queryParamMap.put("keyFileNameByPartnerName", keyFileNameByPartnerName);
// }
// if (partnerType.equals("EKYC")) {
// queryParamMap.put("keyFileNameByPartnerName", keyFileNameByPartnerName);
// }
//
// Response response = RestClient.postRequestWithQueryParamsAndBody(url, requestBody, queryParamMap,
// MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN);
//
// lOGGER.info(response);
String str = authUtil.updatePartnerCertificate(partnerTypeEnum, partnerId, keyFileNameByPartnerName, requestBody, null, BaseTestCase.certsForModule, ApplnURI.replace("https://", ""));
lOGGER.info("Is update partner certificate "+str);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Response response = RestClient.postRequestWithQueryParamsAndBody(url, requestBody, queryParamMap,
MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN);

lOGGER.info(response);

// String url = localHostUrl + properties.getProperty("uploadSignedCertificateUrl");
//
//
//
// HashMap<String, Object> queryParamMap = new HashMap<>();
// queryParamMap.put("partnerName", partnerId);
// queryParamMap.put("partnerType", partnerType);
// queryParamMap.put("moduleName", BaseTestCase.certsForModule);
//
//
// Response response = RestClient.postRequestWithQueryParamsAndBody(url, requestBody, queryParamMap,
// MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN);
//
// lOGGER.info(response);
}

public static void deviceGeneration() {
@@ -487,23 +599,29 @@ public static void deleteCertificates() {
// So use the predefined certificate folder and partnerkey
return ;
}


if (localHostUrl == null) {
localHostUrl = getLocalHostUrl();
}
String url = localHostUrl + properties.getProperty("clearCertificateURL");

if (url.contains("$MODULENAME$")) {
url = url.replace("$MODULENAME$", BaseTestCase.certsForModule);
}

if (url.contains("$CERTSDIR$")) {
url = url.replace("$CERTSDIR$", ConfigManager.getauthCertsPath());
AuthUtil authUtil = new AuthUtil();
try {
authUtil.clearKeys(null, BaseTestCase.certsForModule, ApplnURI.replace("https://", ""));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Response response = RestClient.deleteRequest(url, MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON);
lOGGER.info(response);

// if (localHostUrl == null) {
// localHostUrl = getLocalHostUrl();
// }
// String url = localHostUrl + properties.getProperty("clearCertificateURL");
//
// if (url.contains("$MODULENAME$")) {
// url = url.replace("$MODULENAME$", BaseTestCase.certsForModule);
// }
//
// if (url.contains("$CERTSDIR$")) {
// url = url.replace("$CERTSDIR$", ConfigManager.getauthCertsPath());
// }
//
// Response response = RestClient.deleteRequest(url, MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON);
// lOGGER.info(response);

}

Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package io.mosip.testrig.apirig.utils;

public enum PartnerTypes {

DEVICE("device"),
RELYING_PARTY("rp"),
FTM("ftm"),
EKYC("ekyc"),
MISP("misp");

private String filePrepend;

private PartnerTypes(String filePrepend) {
this.filePrepend = filePrepend;
}

public String getFilePrepend() {
return this.filePrepend;
}
}
Loading

0 comments on commit dd91731

Please sign in to comment.