From 67df855bb5642de1b1a2b2b1312ae8d15ca5eb0d Mon Sep 17 00:00:00 2001 From: mandeepdhiman123 Date: Thu, 2 Sep 2021 10:56:33 +0530 Subject: [PATCH 1/2] removed keymanager, Key-migrator, key-generator build from commons. --- .github/workflows/push_trigger.yml | 176 ----------------------------- kernel/pom.xml | 6 +- 2 files changed, 3 insertions(+), 179 deletions(-) diff --git a/.github/workflows/push_trigger.yml b/.github/workflows/push_trigger.yml index da3cccf4797..c0cd208d0b1 100644 --- a/.github/workflows/push_trigger.yml +++ b/.github/workflows/push_trigger.yml @@ -385,67 +385,6 @@ jobs: SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }} # required if: failure() # Pick up events even if the job fails or is canceled. - docker-kernel-keymanager-service: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: ${{ secrets. dev_namespace_docker_hub }} - SERVICE_NAME: kernel-keymanager-service - SERVICE_LOCATION: kernel/kernel-keymanager-service - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - echo ${{ env.BRANCH_NAME }} - - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the id-repository-vid-service - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - VERSION=$BRANCH_NAME - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - - uses: 8398a7/action-slack@v3 - with: - status: ${{ job.status }} - fields: repo,message,commit,author,action,eventName,ref,workflow,job,took # selectable (default: repo,message) - env: - SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }} # required - if: failure() # Pick up events even if the job fails or is canceled. - - docker-kernel-pridgenerator-service: needs: build @@ -685,118 +624,3 @@ jobs: env: SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }} # required if: failure() # Pick up events even if the job fails or is canceled. - - docker-kernel-keys-generator: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: ${{ secrets. dev_namespace_docker_hub }} - SERVICE_NAME: keys-generator - SERVICE_LOCATION: kernel/keys-generator - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - echo ${{ env.BRANCH_NAME }} - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the keys-generator - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - VERSION=$BRANCH_NAME - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - - uses: 8398a7/action-slack@v3 - with: - status: ${{ job.status }} - fields: repo,message,commit,author,action,eventName,ref,workflow,job,took # selectable (default: repo,message) - env: - SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }} # required - if: failure() # Pick up events even if the job fails or is canceled. - - docker-kernel-keys-migrator: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: ${{ secrets. dev_namespace_docker_hub }} - SERVICE_NAME: keys-migrator - SERVICE_LOCATION: kernel/keys-migrator - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - echo ${{ env.BRANCH_NAME }} - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the keys-migrator - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - VERSION=$BRANCH_NAME - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - - uses: 8398a7/action-slack@v3 - with: - status: ${{ job.status }} - fields: repo,message,commit,author,action,eventName,ref,workflow,job,took # selectable (default: repo,message) - env: - SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }} # required - if: failure() # Pick up events even if the job fails or is canceled. \ No newline at end of file diff --git a/kernel/pom.xml b/kernel/pom.xml index 9563f3e7bd4..ad6042cb6e6 100644 --- a/kernel/pom.xml +++ b/kernel/pom.xml @@ -157,15 +157,15 @@ kernel-notification-service kernel-auth-service kernel-ridgenerator-service - kernel-keymanager-service + kernel-idgenerator-service kernel-pridgenerator-service kernel-salt-generator kernel-biometrics-api kernel-biosdk-provider object-store - keys-generator - keys-migrator + + kernel-demographics-api From 42e682e5bfa9bfb8917da51ca4b10d1907b38acd Mon Sep 17 00:00:00 2001 From: mandeepdhiman123 Date: Thu, 2 Sep 2021 11:13:33 +0530 Subject: [PATCH 2/2] removed keymanager, Key-migrator, key-generator build from commons. --- kernel/kernel-keymanager-service/.gitignore | 22 - kernel/kernel-keymanager-service/Dockerfile | 121 -- .../Dockerfile_DO_NOT_BUILD | 56 - kernel/kernel-keymanager-service/README.md | 634 -------- .../configure_start.sh | 40 - kernel/kernel-keymanager-service/pom.xml | 394 ----- .../softhsm-application.conf | 4 - .../softhsm/Dockerfile-softhsm | 33 - .../src/main/java/META-INF/MANIFEST.MF | 3 - .../constant/ClientCryptoErrorConstants.java | 43 - .../constant/ClientCryptoManagerConstant.java | 24 - .../controller/ClientCryptoController.java | 129 -- .../clientcrypto/dto/PublicKeyRequestDto.java | 26 - .../dto/PublicKeyResponseDto.java | 21 - .../clientcrypto/dto/TpmCryptoRequestDto.java | 37 - .../dto/TpmCryptoResponseDto.java | 20 - .../clientcrypto/dto/TpmSignRequestDto.java | 24 - .../clientcrypto/dto/TpmSignResponseDto.java | 13 - .../dto/TpmSignVerifyRequestDto.java | 45 - .../dto/TpmSignVerifyResponseDto.java | 13 - .../exception/ClientCryptoException.java | 35 - .../service/impl/ClientCryptoFacade.java | 177 --- .../impl/ClientCryptoManagerServiceImpl.java | 77 - .../impl/LocalClientCryptoServiceImpl.java | 302 ---- .../impl/TPMClientCryptoServiceImpl.java | 311 ---- .../spi/ClientCryptoManagerService.java | 56 - .../service/spi/ClientCryptoService.java | 74 - .../SecurityExceptionCodeConstant.java | 71 - .../kernel/crypto/jce/core/CryptoCore.java | 548 ------- .../kernel/crypto/jce/core/JwsFactory.java | 15 - .../kernel/crypto/jce/util/CryptoUtils.java | 58 - .../kernel/crypto/jce/util/JWSValidation.java | 86 -- .../constant/CryptomanagerConstant.java | 43 - .../constant/CryptomanagerErrorCode.java | 104 -- .../controller/CryptomanagerController.java | 143 -- .../dto/CryptoWithPinRequestDto.java | 45 - .../dto/CryptoWithPinResponseDto.java | 32 - .../dto/CryptomanagerRequestDto.java | 86 -- .../dto/CryptomanagerResponseDto.java | 32 - .../dto/KeymanagerPublicKeyResponseDto.java | 42 - .../dto/KeymanagerSymmetricKeyRequestDto.java | 46 - .../KeymanagerSymmetricKeyResponseDto.java | 29 - .../cryptomanager/dto/PublicKeyResponse.java | 53 - .../CryptoManagerSerivceException.java | 39 - .../exception/KeymanagerServiceException.java | 34 - .../exception/ParseResponseException.java | 22 - .../service/CryptomanagerService.java | 58 - .../impl/CryptomanagerServiceImpl.java | 298 ---- .../util/CryptomanagerUtils.java | 226 --- .../util/KeymanagerSymmetricKeyConverter.java | 31 - .../bouncycastle/KeyGenerator.java | 69 - .../KeyGeneratorExceptionConstant.java | 77 - .../bouncycastle/util/KeyGeneratorUtils.java | 92 -- .../hsm/constant/KeymanagerConstant.java | 59 - .../hsm/constant/KeymanagerErrorCode.java | 67 - .../keymanager/hsm/impl/KeyStoreImpl.java | 316 ---- .../hsm/impl/offline/OLKeyStoreImpl.java | 169 -- .../hsm/impl/pkcs/PKCS11KeyStoreImpl.java | 607 -------- .../hsm/impl/pkcs/PKCS12KeyStoreImpl.java | 510 ------ .../hsm/util/CertificateUtility.java | 191 --- .../KeymanagerBootApplication.java | 30 - .../config/KeymanagerConfig.java | 44 - .../config/KeymanagerDaoConfig.java | 222 --- .../config/LoggerConfiguration.java | 30 - .../config/ReqResFilter.java | 54 - .../config/ResponseBodyAdviceConfig.java | 96 -- .../config/SwaggerConfig.java | 113 -- .../HibernatePersistenceConstant.java | 121 -- .../constant/KeymanagerConstant.java | 179 --- .../constant/KeymanagerErrorConstant.java | 88 -- .../controller/KeymanagerController.java | 175 --- .../dto/CSRGenerateRequestDto.java | 75 - .../dto/CertificateEntry.java | 24 - .../dto/CertificateInfo.java | 23 - .../dto/EncryptDataRequestDto.java | 40 - .../dto/EncryptDataResponseDto.java | 25 - .../dto/KeyPairGenerateRequestDto.java | 80 - .../dto/KeyPairGenerateResponseDto.java | 59 - .../dto/PublicKeyResponse.java | 53 - .../dto/RevokeKeyRequestDto.java | 45 - .../dto/RevokeKeyResponseDto.java | 26 - .../dto/SignatureCertificate.java | 68 - .../dto/SymmetricKeyGenerateRequestDto.java | 47 - .../dto/SymmetricKeyGenerateResponseDto.java | 26 - .../dto/SymmetricKeyRequestDto.java | 58 - .../dto/SymmetricKeyResponseDto.java | 28 - .../dto/UploadCertificateRequestDto.java | 46 - .../dto/UploadCertificateResponseDto.java | 26 - .../keymanagerservice/entity/BaseEntity.java | 61 - .../entity/CACertificateStore.java | 95 -- .../entity/DataEncryptKeystore.java | 48 - .../keymanagerservice/entity/KeyAlias.java | 67 - .../keymanagerservice/entity/KeyPolicy.java | 47 - .../keymanagerservice/entity/KeyStore.java | 53 - .../entity/PartnerCertificateStore.java | 107 -- .../entity/SecreteKeyStore.java | 50 - .../exception/CryptoException.java | 38 - .../InvalidApplicationIdException.java | 29 - .../InvalidResponseObjectTypeException.java | 29 - .../exception/KeyStoreException.java | 29 - .../exception/KeymanagerExceptionHandler.java | 373 ----- .../exception/KeymanagerServiceException.java | 38 - .../exception/NoUniqueAliasException.java | 29 - .../helper/KeymanagerDBHelper.java | 200 --- .../logger/KeymanagerLogger.java | 30 - .../CACertificateStoreRepository.java | 83 - .../DataEncryptKeystoreRepository.java | 45 - .../repository/EncryptionDao.java | 41 - .../repository/KeyAliasRepository.java | 37 - .../repository/KeyPolicyRepository.java | 38 - .../repository/KeyStoreRepository.java | 38 - .../PartnerCertificateStoreRepository.java | 62 - .../repository/SimpleAES.java | 98 -- .../service/KeymanagerService.java | 120 -- .../service/impl/KeymanagerServiceImpl.java | 1368 ----------------- .../util/KeymanagerUtil.java | 466 ------ .../constant/KeyMigratorConstants.java | 28 - .../controller/KeyMigratorController.java | 95 -- .../dto/KeyMigrateBaseKeyRequestDto.java | 70 - .../dto/KeyMigrateBaseKeyResponseDto.java | 32 - .../kernel/keymigrate/dto/ZKKeyDataDto.java | 37 - .../ZKKeyMigrateCertficateResponseDto.java | 39 - .../dto/ZKKeyMigrateRequestDto.java | 34 - .../dto/ZKKeyMigrateResponseDto.java | 28 - .../keymigrate/dto/ZKKeyResponseDto.java | 37 - .../service/impl/KeyMigratorServiceImpl.java | 367 ----- .../service/spi/KeyMigratorService.java | 41 - .../constant/LicenseKeyManagerErrorCodes.java | 35 - .../LicenseKeyManagerExceptionConstants.java | 59 - .../LicenseKeyManagerPropertyConstants.java | 35 - .../controller/LicenseKeyController.java | 95 -- .../dto/LicenseKeyFetchResponseDto.java | 20 - .../dto/LicenseKeyGenerationDto.java | 27 - .../dto/LicenseKeyGenerationResponseDto.java | 18 - .../lkeymanager/dto/LicenseKeyMappingDto.java | 28 - .../dto/LicenseKeyMappingResponseDto.java | 18 - .../lkeymanager/entity/LicenseKeyList.java | 91 -- .../entity/LicenseKeyPermission.java | 84 - .../lkeymanager/entity/LicenseKeyTspMap.java | 82 - .../entity/id/LicenseKeyPermissionID.java | 35 - .../entity/id/LicenseKeyTspMapID.java | 35 - .../exception/InvalidArgumentsException.java | 43 - .../exception/LicenseKeyServiceException.java | 39 - .../repository/LicenseKeyListRepository.java | 24 - .../LicenseKeyPermissionRepository.java | 44 - .../LicenseKeyTspMapRepository.java | 27 - .../impl/LicenseKeyManagerServiceImpl.java | 185 --- .../util/LicenseKeyManagerUtil.java | 170 -- .../constant/PartnerCertManagerConstants.java | 99 -- .../PartnerCertManagerErrorConstants.java | 75 - .../PartnerCertManagerController.java | 125 -- .../dto/CACertificateRequestDto.java | 38 - .../dto/CACertificateResponseDto.java | 26 - .../dto/CertificateTrustRequestDto.java | 38 - .../dto/CertificateTrustResponeDto.java | 20 - .../dto/PartnerCertDownloadRequestDto.java | 31 - .../dto/PartnerCertDownloadResponeDto.java | 26 - .../dto/PartnerCertificateRequestDto.java | 45 - .../dto/PartnerCertificateResponseDto.java | 32 - .../PartnerCertManagerException.java | 38 - .../helper/PartnerCertManagerDBHelper.java | 164 -- .../PartnerCertificateManagerServiceImpl.java | 546 ------- .../spi/PartnerCertificateManagerService.java | 54 - .../util/PartnerCertificateManagerUtil.java | 244 --- .../signature/constant/SignatureConstant.java | 43 - .../constant/SignatureErrorCode.java | 44 - .../controller/SignatureController.java | 115 -- .../signature/dto/JWTSignatureRequestDto.java | 62 - .../dto/JWTSignatureResponseDto.java | 29 - .../dto/JWTSignatureVerifyRequestDto.java | 60 - .../dto/JWTSignatureVerifyResponseDto.java | 32 - .../signature/dto/PDFSignatureRequestDto.java | 86 -- .../signature/dto/PublicKeyRequestDto.java | 20 - .../kernel/signature/dto/SignRequestDto.java | 16 - .../kernel/signature/dto/SignResponseDto.java | 32 - .../signature/dto/SignatureRequestDto.java | 54 - .../signature/dto/SignatureResponseDto.java | 33 - .../signature/dto/TimestampRequestDto.java | 26 - .../signature/dto/ValidatorResponseDto.java | 21 - .../CertificateNotValidException.java | 41 - .../exception/PublicKeyParseException.java | 30 - .../signature/exception/RequestException.java | 41 - .../exception/SignatureFailureException.java | 30 - .../signature/service/SignatureService.java | 52 - .../service/impl/SignatureServiceImpl.java | 420 ----- .../kernel/signature/util/SignatureUtil.java | 78 - .../constant/TokenIDGeneratorErrorCode.java | 53 - .../TokenIDGeneratorController.java | 31 - .../dto/TokenIDResponseDto.java | 24 - .../TokenIdGeneratorServiceException.java | 16 - .../generator/TokenIDGenerator.java | 29 - .../service/TokenIDGeneratorService.java | 23 - .../impl/TokenIDGeneratorServiceImpl.java | 37 - .../constant/ZKCryptoErrorConstants.java | 56 - .../constant/ZKCryptoManagerConstants.java | 50 - .../controller/ZKCryptoManagerController.java | 94 -- .../zkcryptoservice/dto/CryptoDataDto.java | 38 - .../dto/ReEncryptRandomKeyResponseDto.java | 20 - .../dto/ZKCryptoRequestDto.java | 40 - .../dto/ZKCryptoResponseDto.java | 37 - .../exception/ZKCryptoException.java | 38 - .../exception/ZKKeyDerivationException.java | 38 - .../ZKRandomKeyDecryptionException.java | 29 - .../impl/ZKCryptoManagerServiceImpl.java | 407 ----- .../service/spi/ZKCryptoManagerService.java | 43 - .../resources/application-local.properties | 125 -- .../src/main/resources/bootstrap.properties | 24 - .../src/main/resources/logback.xml | 11 - .../test/ClientCryptoTestBootApplication.java | 12 - .../clientcrypto/test/TestSecurityConfig.java | 67 - .../ClientCryptoControllerTest.java | 120 -- ...ryptoCoreNoSuchAlgorithmExceptionTest.java | 110 -- .../crypto/jce/test/CryptoCoreTest.java | 228 --- .../jce/test/CryptoJceBootApplication.java | 15 - .../crypto/jce/test/CryptoUtilTest.java | 39 - ...raphicServiceIntegrationExceptionTest.java | 200 --- .../CryptographicServiceIntegrationTest.java | 259 ---- .../util/CryptographicUtilExceptionTest.java | 91 -- .../CryptographicUtilWithKeyManagerTest.java | 94 -- .../test/KeyGeneratorBootApplication.java | 15 - .../test/KeyGeneratorExceptionTest.java | 24 - .../bouncycastle/test/KeyGeneratorTest.java | 36 - .../test/CertificateUtilityExceptionTest.java | 40 - .../hsm/test/KeyStoreImplExceptionTest.java | 120 -- .../keymanager/hsm/test/KeyStoreImplTest.java | 179 --- .../test/KeymanagerTestBootApplication.java | 27 - .../test/config/TestConfig.java | 40 - .../test/config/TestSecurityConfig.java | 77 - .../KeymanagerIntegrationTest.java | 372 ----- .../test/logger/KeymanagerLoggerTest.java | 24 - .../test/util/KeymanagerUtilTest.java | 88 -- .../LicenseKeyManagerControllerTest.java | 100 -- .../LicenseKeyManagerExceptionTest.java | 393 ----- .../service/LicenseKeyManagerServiceTest.java | 214 --- .../CryptoSignatureIntegrationTest.java | 156 -- .../TokenIdGeneratorIntegrationTest.java | 46 - .../src/test/resources/application.properties | 116 -- .../src/test/resources/bootstrap.properties | 19 - .../src/test/resources/dummy.pdf | Bin 13264 -> 0 bytes .../src/test/resources/logback.xml | 10 - kernel/keys-generator/.gitignore | 5 - kernel/keys-generator/Dockerfile | 65 - kernel/keys-generator/configure_start.sh | 40 - kernel/keys-generator/pom.xml | 351 ----- .../KeysGeneratorApplication.java | 34 - .../keygenerator/generator/KeysGenerator.java | 195 --- .../generator/RandomKeysGenerator.java | 123 -- .../resources/application-local.properties | 120 -- .../src/main/resources/bootstrap.properties | 26 - kernel/keys-migrator/Dockerfile | 65 - kernel/keys-migrator/configure_start.sh | 26 - kernel/keys-migrator/pom.xml | 97 -- .../migrate/MigrateBaseKeysApplication.java | 44 - .../kernel/migrate/impl/BaseKeysMigrator.java | 413 ----- .../resources/application-local.properties | 139 -- .../src/main/resources/bootstrap.properties | 26 - 256 files changed, 23983 deletions(-) delete mode 100644 kernel/kernel-keymanager-service/.gitignore delete mode 100644 kernel/kernel-keymanager-service/Dockerfile delete mode 100644 kernel/kernel-keymanager-service/Dockerfile_DO_NOT_BUILD delete mode 100644 kernel/kernel-keymanager-service/README.md delete mode 100644 kernel/kernel-keymanager-service/configure_start.sh delete mode 100644 kernel/kernel-keymanager-service/pom.xml delete mode 100644 kernel/kernel-keymanager-service/softhsm-application.conf delete mode 100644 kernel/kernel-keymanager-service/softhsm/Dockerfile-softhsm delete mode 100644 kernel/kernel-keymanager-service/src/main/java/META-INF/MANIFEST.MF delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/constant/ClientCryptoErrorConstants.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/constant/ClientCryptoManagerConstant.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/controller/ClientCryptoController.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/dto/PublicKeyRequestDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/dto/PublicKeyResponseDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/dto/TpmCryptoRequestDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/dto/TpmCryptoResponseDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/dto/TpmSignRequestDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/dto/TpmSignResponseDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/dto/TpmSignVerifyRequestDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/dto/TpmSignVerifyResponseDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/exception/ClientCryptoException.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/service/impl/ClientCryptoFacade.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/service/impl/ClientCryptoManagerServiceImpl.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/service/impl/LocalClientCryptoServiceImpl.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/service/impl/TPMClientCryptoServiceImpl.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/service/spi/ClientCryptoManagerService.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/service/spi/ClientCryptoService.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/crypto/jce/constant/SecurityExceptionCodeConstant.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/crypto/jce/core/CryptoCore.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/crypto/jce/core/JwsFactory.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/crypto/jce/util/CryptoUtils.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/crypto/jce/util/JWSValidation.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/constant/CryptomanagerConstant.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/constant/CryptomanagerErrorCode.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/controller/CryptomanagerController.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/dto/CryptoWithPinRequestDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/dto/CryptoWithPinResponseDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/dto/CryptomanagerRequestDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/dto/CryptomanagerResponseDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/dto/KeymanagerPublicKeyResponseDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/dto/KeymanagerSymmetricKeyRequestDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/dto/KeymanagerSymmetricKeyResponseDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/dto/PublicKeyResponse.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/exception/CryptoManagerSerivceException.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/exception/KeymanagerServiceException.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/exception/ParseResponseException.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/service/CryptomanagerService.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/service/impl/CryptomanagerServiceImpl.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/util/CryptomanagerUtils.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/util/KeymanagerSymmetricKeyConverter.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keygenerator/bouncycastle/KeyGenerator.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keygenerator/bouncycastle/constant/KeyGeneratorExceptionConstant.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keygenerator/bouncycastle/util/KeyGeneratorUtils.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanager/hsm/constant/KeymanagerConstant.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanager/hsm/constant/KeymanagerErrorCode.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanager/hsm/impl/KeyStoreImpl.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanager/hsm/impl/offline/OLKeyStoreImpl.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanager/hsm/impl/pkcs/PKCS11KeyStoreImpl.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanager/hsm/impl/pkcs/PKCS12KeyStoreImpl.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanager/hsm/util/CertificateUtility.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/KeymanagerBootApplication.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/config/KeymanagerConfig.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/config/KeymanagerDaoConfig.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/config/LoggerConfiguration.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/config/ReqResFilter.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/config/ResponseBodyAdviceConfig.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/config/SwaggerConfig.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/constant/HibernatePersistenceConstant.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/constant/KeymanagerConstant.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/constant/KeymanagerErrorConstant.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/controller/KeymanagerController.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/CSRGenerateRequestDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/CertificateEntry.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/CertificateInfo.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/EncryptDataRequestDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/EncryptDataResponseDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/KeyPairGenerateRequestDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/KeyPairGenerateResponseDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/PublicKeyResponse.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/RevokeKeyRequestDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/RevokeKeyResponseDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/SignatureCertificate.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/SymmetricKeyGenerateRequestDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/SymmetricKeyGenerateResponseDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/SymmetricKeyRequestDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/SymmetricKeyResponseDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/UploadCertificateRequestDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/UploadCertificateResponseDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/entity/BaseEntity.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/entity/CACertificateStore.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/entity/DataEncryptKeystore.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/entity/KeyAlias.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/entity/KeyPolicy.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/entity/KeyStore.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/entity/PartnerCertificateStore.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/entity/SecreteKeyStore.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/exception/CryptoException.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/exception/InvalidApplicationIdException.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/exception/InvalidResponseObjectTypeException.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/exception/KeyStoreException.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/exception/KeymanagerExceptionHandler.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/exception/KeymanagerServiceException.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/exception/NoUniqueAliasException.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/helper/KeymanagerDBHelper.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/logger/KeymanagerLogger.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/repository/CACertificateStoreRepository.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/repository/DataEncryptKeystoreRepository.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/repository/EncryptionDao.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/repository/KeyAliasRepository.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/repository/KeyPolicyRepository.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/repository/KeyStoreRepository.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/repository/PartnerCertificateStoreRepository.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/repository/SimpleAES.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/service/KeymanagerService.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/service/impl/KeymanagerServiceImpl.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/util/KeymanagerUtil.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/constant/KeyMigratorConstants.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/controller/KeyMigratorController.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/dto/KeyMigrateBaseKeyRequestDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/dto/KeyMigrateBaseKeyResponseDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/dto/ZKKeyDataDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/dto/ZKKeyMigrateCertficateResponseDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/dto/ZKKeyMigrateRequestDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/dto/ZKKeyMigrateResponseDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/dto/ZKKeyResponseDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/service/impl/KeyMigratorServiceImpl.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/service/spi/KeyMigratorService.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/constant/LicenseKeyManagerErrorCodes.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/constant/LicenseKeyManagerExceptionConstants.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/constant/LicenseKeyManagerPropertyConstants.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/controller/LicenseKeyController.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/dto/LicenseKeyFetchResponseDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/dto/LicenseKeyGenerationDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/dto/LicenseKeyGenerationResponseDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/dto/LicenseKeyMappingDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/dto/LicenseKeyMappingResponseDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/entity/LicenseKeyList.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/entity/LicenseKeyPermission.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/entity/LicenseKeyTspMap.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/entity/id/LicenseKeyPermissionID.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/entity/id/LicenseKeyTspMapID.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/exception/InvalidArgumentsException.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/exception/LicenseKeyServiceException.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/repository/LicenseKeyListRepository.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/repository/LicenseKeyPermissionRepository.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/repository/LicenseKeyTspMapRepository.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/service/impl/LicenseKeyManagerServiceImpl.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/util/LicenseKeyManagerUtil.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/constant/PartnerCertManagerConstants.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/constant/PartnerCertManagerErrorConstants.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/controller/PartnerCertManagerController.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/dto/CACertificateRequestDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/dto/CACertificateResponseDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/dto/CertificateTrustRequestDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/dto/CertificateTrustResponeDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/dto/PartnerCertDownloadRequestDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/dto/PartnerCertDownloadResponeDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/dto/PartnerCertificateRequestDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/dto/PartnerCertificateResponseDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/exception/PartnerCertManagerException.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/helper/PartnerCertManagerDBHelper.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/service/impl/PartnerCertificateManagerServiceImpl.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/service/spi/PartnerCertificateManagerService.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/util/PartnerCertificateManagerUtil.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/constant/SignatureConstant.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/constant/SignatureErrorCode.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/controller/SignatureController.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/JWTSignatureRequestDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/JWTSignatureResponseDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/JWTSignatureVerifyRequestDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/JWTSignatureVerifyResponseDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/PDFSignatureRequestDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/PublicKeyRequestDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/SignRequestDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/SignResponseDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/SignatureRequestDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/SignatureResponseDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/TimestampRequestDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/ValidatorResponseDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/exception/CertificateNotValidException.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/exception/PublicKeyParseException.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/exception/RequestException.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/exception/SignatureFailureException.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/service/SignatureService.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/service/impl/SignatureServiceImpl.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/util/SignatureUtil.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/tokenidgenerator/constant/TokenIDGeneratorErrorCode.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/tokenidgenerator/controller/TokenIDGeneratorController.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/tokenidgenerator/dto/TokenIDResponseDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/tokenidgenerator/exception/TokenIdGeneratorServiceException.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/tokenidgenerator/generator/TokenIDGenerator.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/tokenidgenerator/service/TokenIDGeneratorService.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/tokenidgenerator/service/impl/TokenIDGeneratorServiceImpl.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/constant/ZKCryptoErrorConstants.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/constant/ZKCryptoManagerConstants.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/controller/ZKCryptoManagerController.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/dto/CryptoDataDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/dto/ReEncryptRandomKeyResponseDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/dto/ZKCryptoRequestDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/dto/ZKCryptoResponseDto.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/exception/ZKCryptoException.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/exception/ZKKeyDerivationException.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/exception/ZKRandomKeyDecryptionException.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/service/impl/ZKCryptoManagerServiceImpl.java delete mode 100644 kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/service/spi/ZKCryptoManagerService.java delete mode 100644 kernel/kernel-keymanager-service/src/main/resources/application-local.properties delete mode 100644 kernel/kernel-keymanager-service/src/main/resources/bootstrap.properties delete mode 100644 kernel/kernel-keymanager-service/src/main/resources/logback.xml delete mode 100644 kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/clientcrypto/test/ClientCryptoTestBootApplication.java delete mode 100644 kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/clientcrypto/test/TestSecurityConfig.java delete mode 100644 kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/clientcrypto/test/integration/ClientCryptoControllerTest.java delete mode 100644 kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/crypto/jce/test/CryptoCoreNoSuchAlgorithmExceptionTest.java delete mode 100644 kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/crypto/jce/test/CryptoCoreTest.java delete mode 100644 kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/crypto/jce/test/CryptoJceBootApplication.java delete mode 100644 kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/crypto/jce/test/CryptoUtilTest.java delete mode 100644 kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/cryptomanager/test/integration/CryptographicServiceIntegrationExceptionTest.java delete mode 100644 kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/cryptomanager/test/integration/CryptographicServiceIntegrationTest.java delete mode 100644 kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/cryptomanager/test/util/CryptographicUtilExceptionTest.java delete mode 100644 kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/cryptomanager/test/util/CryptographicUtilWithKeyManagerTest.java delete mode 100644 kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keygenerator/bouncycastle/test/KeyGeneratorBootApplication.java delete mode 100644 kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keygenerator/bouncycastle/test/KeyGeneratorExceptionTest.java delete mode 100644 kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keygenerator/bouncycastle/test/KeyGeneratorTest.java delete mode 100644 kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keymanager/hsm/test/CertificateUtilityExceptionTest.java delete mode 100644 kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keymanager/hsm/test/KeyStoreImplExceptionTest.java delete mode 100644 kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keymanager/hsm/test/KeyStoreImplTest.java delete mode 100644 kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keymanagerservice/test/KeymanagerTestBootApplication.java delete mode 100644 kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keymanagerservice/test/config/TestConfig.java delete mode 100644 kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keymanagerservice/test/config/TestSecurityConfig.java delete mode 100644 kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keymanagerservice/test/integration/KeymanagerIntegrationTest.java delete mode 100644 kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keymanagerservice/test/logger/KeymanagerLoggerTest.java delete mode 100644 kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keymanagerservice/test/util/KeymanagerUtilTest.java delete mode 100644 kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/lkeymanager/test/controller/LicenseKeyManagerControllerTest.java delete mode 100644 kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/lkeymanager/test/exception/LicenseKeyManagerExceptionTest.java delete mode 100644 kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/lkeymanager/test/service/LicenseKeyManagerServiceTest.java delete mode 100644 kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/signature/test/integration/CryptoSignatureIntegrationTest.java delete mode 100644 kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/tokenidgenerator/test/integration/TokenIdGeneratorIntegrationTest.java delete mode 100644 kernel/kernel-keymanager-service/src/test/resources/application.properties delete mode 100644 kernel/kernel-keymanager-service/src/test/resources/bootstrap.properties delete mode 100644 kernel/kernel-keymanager-service/src/test/resources/dummy.pdf delete mode 100644 kernel/kernel-keymanager-service/src/test/resources/logback.xml delete mode 100644 kernel/keys-generator/.gitignore delete mode 100644 kernel/keys-generator/Dockerfile delete mode 100644 kernel/keys-generator/configure_start.sh delete mode 100644 kernel/keys-generator/pom.xml delete mode 100644 kernel/keys-generator/src/main/java/io/mosip/kernel/keygenerator/KeysGeneratorApplication.java delete mode 100644 kernel/keys-generator/src/main/java/io/mosip/kernel/keygenerator/generator/KeysGenerator.java delete mode 100644 kernel/keys-generator/src/main/java/io/mosip/kernel/keygenerator/generator/RandomKeysGenerator.java delete mode 100644 kernel/keys-generator/src/main/resources/application-local.properties delete mode 100644 kernel/keys-generator/src/main/resources/bootstrap.properties delete mode 100755 kernel/keys-migrator/Dockerfile delete mode 100755 kernel/keys-migrator/configure_start.sh delete mode 100755 kernel/keys-migrator/pom.xml delete mode 100755 kernel/keys-migrator/src/main/java/io/mosip/kernel/migrate/MigrateBaseKeysApplication.java delete mode 100755 kernel/keys-migrator/src/main/java/io/mosip/kernel/migrate/impl/BaseKeysMigrator.java delete mode 100755 kernel/keys-migrator/src/main/resources/application-local.properties delete mode 100755 kernel/keys-migrator/src/main/resources/bootstrap.properties diff --git a/kernel/kernel-keymanager-service/.gitignore b/kernel/kernel-keymanager-service/.gitignore deleted file mode 100644 index bc1b810c6c5..00000000000 --- a/kernel/kernel-keymanager-service/.gitignore +++ /dev/null @@ -1,22 +0,0 @@ -*.class -.mtj.tmp/ -*.jar -*.war -*.ear -hs_err_pid* -target/ -.metadata -.classpath -.project -.settings/ -bin/ -tmp/ -*.tmp -*.bak -*.swp -*~.nib -local.properties -.loadpath -.DS_Store -*.log -logs/ \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/Dockerfile b/kernel/kernel-keymanager-service/Dockerfile deleted file mode 100644 index cf09c0d7835..00000000000 --- a/kernel/kernel-keymanager-service/Dockerfile +++ /dev/null @@ -1,121 +0,0 @@ -FROM openjdk:11 - -# can be passed during Docker build as build time environment for github branch to pickup configuration from. -ARG spring_config_label - -# can be passed during Docker build as build time environment for spring profiles active -ARG active_profile - -# can be passed during Docker build as build time environment for config server URL -ARG spring_config_url - -# can be passed during Docker build as build time environment for glowroot -ARG is_glowroot - -# can be passed during Docker build as build time environment for artifactory URL -ARG artifactory_url - -# can be passed during Docker build as build time environment for hsm client zip file path -ARG hsm_client_zip_path - -# can be passed during Docker build as build time environment management rmi server hostname -#ARG management_rmi_server_hostname - -# can be passed during Docker build as build time environment management rmi server port -#ARG management_jmxremote_rmi_port - -# environment variable to pass active profile such as DEV, QA etc at docker runtime -ENV active_profile_env=${active_profile} - -# environment variable to pass github branch to pickup configuration from, at docker runtime -ENV spring_config_label_env=${spring_config_label} - -# environment variable to pass spring configuration url, at docker runtime -ENV spring_config_url_env=${spring_config_url} - -# environment variable to pass glowroot, at docker runtime -ENV is_glowroot_env=${is_glowroot} - -# environment variable to pass artifactory url, at docker runtime -ENV artifactory_url_env=${artifactory_url} -# environment variable to pass iam_adapter url, at docker runtime -ENV iam_adapter_url_env=${iam_adapter_url} - -# environment variable to pass hsm client zip file path, at docker runtime -ENV hsm_zip_file_path=${hsm_client_zip_path} - -# environment variable to pass management rmi server hostname, at docker runtime -#ENV management_rmi_server_hostname_env=${management_rmi_server_hostname} - -# environment variable to pass management rmi server port, at docker runtime -#ENV management_jmxremote_rmi_port_env=${management_jmxremote_rmi_port} - -# can be passed during Docker build as build time environment for github branch to pickup configuration from. -ARG container_user=mosip - -# can be passed during Docker build as build time environment for github branch to pickup configuration from. -ARG container_user_group=mosip - -# can be passed during Docker build as build time environment for github branch to pickup configuration from. -ARG container_user_uid=1001 - -# can be passed during Docker build as build time environment for github branch to pickup configuration from. -ARG container_user_gid=1001 - -ARG hsm_local_dir=hsm-client - -ENV hsm_local_dir_name=${hsm_local_dir} - -# install packages and create user -RUN apt-get -y update \ -&& apt-get install -y unzip sudo\ -&& groupadd -g ${container_user_gid} ${container_user_group} \ -&& useradd -u ${container_user_uid} -g ${container_user_group} -s /bin/sh -m ${container_user} \ -&& adduser ${container_user} sudo \ -&& echo "%sudo ALL=(ALL) NOPASSWD:/home/${container_user}/${hsm_local_dir}/install.sh" >> /etc/sudoers - -# set working directory for the user -WORKDIR /home/${container_user} - -ENV work_dir=/home/${container_user} - -ARG loader_path=${work_dir}/additional_jars/ - -RUN mkdir -p ${loader_path} - -ENV loader_path_env=${loader_path} - -ADD configure_start.sh configure_start.sh - -RUN chmod +x configure_start.sh - -# creating folder to copy additional supporting jar files required at run-time. -#RUN mkdir -p /home/${container_user}/additional-jars - -ADD ./target/*.jar /target/ -RUN find /target -name '*.jar' -executable -type f "-print0" | xargs "-0" cp -t / \ - && rm -rf /target \ - && mv /*.jar ${work_dir}/kernel-keymanager-service.jar - -# change permissions of file inside working dir -RUN chown -R ${container_user}:${container_user} /home/${container_user} - -# select container user for all tasks -USER ${container_user_uid}:${container_user_gid} - -EXPOSE 8088 -EXPOSE 9010 - -ENTRYPOINT [ "./configure_start.sh" ] -CMD if [ "$is_glowroot_env" = "present" ]; then \ - wget -q --show-progress "${artifactory_url_env}"/artifactory/libs-release-local/io/mosip/testing/glowroot.zip ; \ - unzip glowroot.zip ; \ - rm -rf glowroot.zip ; \ - sed -i 's//kernel-keymanager-service/g' glowroot/glowroot.properties ; \ - wget "${iam_adapter_url_env}" -O "${loader_path_env}"/kernel-auth-adapter.jar; \ - java -jar -javaagent:glowroot/glowroot.jar -Dloader.path="${loader_path_env}" -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -XX:HeapDumpPath=/home/ ./kernel-keymanager-service.jar ; \ - else \ - wget "${iam_adapter_url_env}" -O "${loader_path_env}"/kernel-auth-adapter.jar; \ - java -jar -Dloader.path="${loader_path_env}" -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" ./kernel-keymanager-service.jar ; \ - fi - diff --git a/kernel/kernel-keymanager-service/Dockerfile_DO_NOT_BUILD b/kernel/kernel-keymanager-service/Dockerfile_DO_NOT_BUILD deleted file mode 100644 index 11f2a91069a..00000000000 --- a/kernel/kernel-keymanager-service/Dockerfile_DO_NOT_BUILD +++ /dev/null @@ -1,56 +0,0 @@ -ARG docker_registry_url=docker-registry.mosip.io:51000 -FROM ${docker_registry_url}/kernel-keymanager-softhsm:0.1 - -# can be passed during Docker build as build time environment for github branch to pickup configuration from. -ARG spring_config_label - -# can be passed during Docker build as build time environment for spring profiles active -ARG active_profile - -# can be passed during Docker build as build time environment for config server URL -ARG spring_config_url - -# can be passed during Docker build as build time environment management rmi server hostname -ARG management_rmi_server_hostname - -# can be passed during Docker build as build time environment management rmi server port -ARG management_jmxremote_rmi_port - -# environment variable to pass active profile such as DEV, QA etc at docker runtime -ENV active_profile_env=${active_profile} - -# environment variable to pass github branch to pickup configuration from, at docker runtime -ENV spring_config_label_env=${spring_config_label} - -# environment variable to pass spring configuration url, at docker runtime -ENV spring_config_url_env=${spring_config_url} - -# environment variable to pass artifactory url, at docker runtime -ENV artifactory_url_env=${artifactory_url} - -# environment variable to pass iam_adapter url, at docker runtime -ENV iam_adapter_url_env=${iam_adapter_url} - -RUN mkdir /config - -COPY softhsm-application.conf /config - -COPY ./target/kernel-keymanager-service-1.2.0-rc2-SNAPSHOT.jar kernel-keymanager-service.jar - -VOLUME /softhsm - -EXPOSE 8088 -EXPOSE 9010 - -CMD if [ "$is_glowroot_env" = "present" ]; then \ - wget "${artifactory_url_env}"/artifactory/libs-release-local/io/mosip/testing/glowroot.zip ; \ - apt-get update && apt-get install -y unzip ; \ - unzip glowroot.zip ; \ - rm -rf glowroot.zip ; \ - sed -i 's//kernel-keymanager-service/g' glowroot/glowroot.properties ; \ - wget "${iam_adapter_url_env}" -O kernel-auth-adapter.jar; \ - java -jar -javaagent:glowroot/glowroot.jar -Dloader.path=./kernel-auth-adapter.jar -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -XX:HeapDumpPath=/home/ kernel-keymanager-service.jar ; \ - else \ - wget "${iam_adapter_url_env}" -O kernel-auth-adapter.jar; \ - java -jar -Dloader.path=./kernel-auth-adapter.jar -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" kernel-keymanager-service.jar ; \ - fi diff --git a/kernel/kernel-keymanager-service/README.md b/kernel/kernel-keymanager-service/README.md deleted file mode 100644 index f0a3fc6960f..00000000000 --- a/kernel/kernel-keymanager-service/README.md +++ /dev/null @@ -1,634 +0,0 @@ -## kernel-keymanager-service - -[Background & Design KEYMANAGER](../../docs/design/kernel/kernel-keymanager.md) - -[Background & Design CRYPTOMANAGER](../../docs/design/kernel/kernel-cryptomanager.md) - -[Background & Design SIGNATURE](../../docs/design/kernel/kernel-cryptography-digitalsignature.md) - -[Background & Design TOKENIDGENERATOR](../../docs/design/kernel/kernel-idgenerator-statictoken.md) - -[Background & Design -TBA- LICENSEKEYMANAGER](../../docs/design/kernel/kernel-licensekeymanager.md) - -[Api Documentation KEYMANAGER](https://github.com/mosip/mosip/wiki/Kernel-APIs#key-manager) - -[Api Documentation CRYPTOMANAGER](https://github.com/mosip/mosip/wiki/Kernel-APIs#crypto-manager) - -[Api Documentation SIGNATURE](https://github.com/mosip/mosip/wiki/Kernel-APIs#signature) - -[Api Documentation TOKENIDGENERATOR](https://github.com/mosip/mosip/wiki/Kernel-APIs#tokenid-generator) - -[Api Documentation -TBA- LICENSEKEYMANAGER](https://github.com/mosip/mosip/wiki/Kernel-APIs#licensekey-manager) - - -Default Port and Context Path - -``` -server.port=8088 -server.servlet.path=/keymanager - -``` - -localhost:8088/keymanager/swagger-ui.html - - -**Application Properties** - -[application-dev.properties](../../config/application-dev.properties) - -[kernel-keymanager-service-dev.properties](../../config/kernel-keymanager-service-dev.properties) - - -``` - -mosip.kernel.keymanager.softhsm.config-path=B\:\\softhsm2\\etc\\softhsm2-demo.conf -mosip.kernel.keymanager.softhsm.keystore-type=PKCS11 -mosip.kernel.keymanager.softhsm.keystore-pass=1234 - -mosip.kernel.keymanager.softhsm.certificate.common-name=www.mosip.io -mosip.kernel.keymanager.softhsm.certificate.organizational-unit=MOSIP -mosip.kernel.keymanager.softhsm.certificate.organization=IITB -mosip.kernel.keymanager.softhsm.certificate.country=IN - -#----------------------- Crypto -------------------------------------------------- -#Crypto asymmetric algorithm name -mosip.kernel.crypto.asymmetric-algorithm-name=RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING -#Crypto symmetric algorithm name -mosip.kernel.crypto.symmetric-algorithm-name=AES/GCM/PKCS5Padding -#Keygenerator asymmetric algorithm name -mosip.kernel.keygenerator.asymmetric-algorithm-name=RSA -#Keygenerator symmetric algorithm name -mosip.kernel.keygenerator.symmetric-algorithm-name=AES -#Asymmetric algorithm key length -mosip.kernel.keygenerator.asymmetric-key-length=2048 -#Symmetric algorithm key length -mosip.kernel.keygenerator.symmetric-key-length=256 - -#Encrypted data and encrypted symmetric key separator -mosip.kernel.data-key-splitter=#KEY_SPLITTER# -#GCM tag length -mosip.kernel.crypto.gcm-tag-length=128 -#Hash algo name -mosip.kernel.crypto.hash-algorithm-name=PBKDF2WithHmacSHA512 -#Symmtric key length used in hash -mosip.kernel.crypto.hash-symmetric-key-length=256 -#No of iterations in hash -mosip.kernel.crypto.hash-iteration=100000 -#Sign algo name -mosip.kernel.crypto.sign-algorithm-name=RS256 - - -keymanager.persistence.jdbc.driver=org.postgresql.Driver -keymanager_database_url=jdbc:postgresql://localhost:9001/mosip_kernel -keymanager_database_username=kerneluser -keymanager_database_password=Mosip@dev123 - -licensekeymanager.persistence.jdbc.driver=org.postgresql.Driver -licensekeymanager_database_url=jdbc:postgresql://localhost:9001/mosip_master -licensekeymanager_database_username=masteruser -licensekeymanager_database_password=Mosip@dev123 - -hibernate.hbm2ddl.auto=none -hibernate.dialect=org.hibernate.dialect.PostgreSQL95Dialect -hibernate.jdbc.lob.non_contextual_creation=true -hibernate.show_sql=false -hibernate.format_sql=false -hibernate.connection.charSet=utf8 -hibernate.cache.use_second_level_cache=false -hibernate.cache.use_query_cache=false -hibernate.cache.use_structured_entries=false -hibernate.generate_statistics=false -hibernate.current_session_context_class=org.springframework.orm.hibernate5.SpringSessionContext - -auth.server.validate.url=https://dev.mosip.io/v1/authmanager/authorize/admin/validateToken -auth.server.admin.validate.url=https://dev.mosip.io/v1/authmanager/authorize/admin/validateToken -auth.role.prefix=ROLE_ -auth.header.name=Authorization - -mosip.kernel.pdf_owner_password=PDFADMIN -#------ -mosip.kernel.signature.signature-request-id=SIGNATURE.REQUEST -mosip.kernel.signature.signature-version-id=v1.0 - -mosip.sign.applicationid=KERNEL -mosip.sign.refid=SIGN -mosip.sign-certificate-refid=SIGN -mosip.signed.header=response-signature -mosip.kernel.signature.encrypt-url=http://localhost:8088/v1/keymanager/sign -mosip.kernel.keymanager-service-publickey-url=http://localhost:8088/v1/keymanager/publickey/{applicationId} -mosip.kernel.keymanager-service-sign-url=http://localhost:8088/v1/keymanager/sign - - -#--- - -mosip.kernel.tokenid.uin.salt=zHuDEAbmbxiUbUShgy6pwUhKh9DE0EZn9kQDKPPKbWscGajMwf -mosip.kernel.tokenid.partnercode.salt=yS8w5Wb6vhIKdf1msi4LYTJks7mqkbmITk2O63Iq8h0bkRlD0d -mosip.kernel.tokenid.length=36 - -#--- -#Length of license key to be generated. -mosip.kernel.licensekey.length=16 -#List of permissions -# NOTE: ',' in the below list is used as splitter in the implementation. -# Use of ',' in the values for below key should be avoided. -# Use of spaces before and after ',' also should be avoided. -mosip.kernel.licensekey.permissions=OTP Trigger,OTP Authentication,Demo Authentication - Identity Data Match,Demo Authentication - Address Data Match,Demo Authentication - Full Address Data Match,Demo Authentication - Secondary Language Match,Biometric Authentication - FMR Data Match,Biometric Authentication - IIR Data Match,Biometric Authentication - FID Data Match,Static Pin Authentication,eKYC - limited,eKYC - Full,eKYC - No -``` - -**Usage Sample** - - - **Get Public Key** - - *Request* - - ``` -OkHttpClient client = new OkHttpClient(); - -Request request = new Request.Builder() -.url("http://localhost:8088/keymanager/v1.0/publickey/REGISTRATION?referenceId=ref1&timeStamp=2018-12-11T06%3A12%3A52.994Z") - .get() - .build(); - -Response response = client.newCall(request).execute(); - ``` - - *Response* - - Status:200 - - ``` - { - "publicKey": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzaFwykABfN683Mp5SNpBQU2_tIRKILIDBReeuTWQuS-6B8Z7kQmQ0cv2fG8fr8XTx7avyY3su25YFfNuIliBmdC3ZKqWVvsL9EpTCCQolcKo9a0351ieKxe_wCg5DIRLS1CciyK_cr2IqcUwh_Y3zkkZs0cF2R945vA_7RMTUth1_9zdobrxYMrMsIf2L1431vLP0-mUuAonQ9GU34L-SyAP1uscWcbk6Xj_EdZRvqrj2aOXrHy0FbQltrwNuTyX0-ZLBwMH7U50Nrh4BeQBA1ioeFKmdzSEY95Fs2jJGmxDUK77dsHw77jmg125HlEuu-NwIvDlcwCFuGQheUQFvwIDAQAB", - "issuedAt": "2018-12-11T06:12:52.994", - "expiryAt": "2019-12-11T06:12:52.994" -} - ``` - - **Sign pdf** - - *Request* - - ``` -final String DEST = DEST; -final String SRC = SRC; -File outFile = new File(DEST); -File inFile = new File(SRC); -RestTemplate restTemplate = new RestTemplate(); -RequestWrapper requestWrapper = new RequestWrapper<>(); -PDFSignatureRequestDto request = new PDFSignatureRequestDto(400, 400, 600, 600, "signing", 1, "password"); - request.setApplicationId("KERNEL"); - request.setReferenceId("SIGN"); - request.setData(Base64.encodeBase64String(FileUtils.readFileToByteArray(inFile))); - request.setTimeStamp("2019-12-10T06:12:52.994Z"); - requestWrapper.setRequest(request); - HttpHeaders headers= new HttpHeaders(); - headers.add("Cookie", Token); -HttpEntity> httpEntity = new HttpEntity>(requestWrapper, headers); -ResponseEntity responseEntity =restTemplate.exchange("http://HOST:PORT/v1/keymanager/pdf/sign", HttpMethod.POST, httpEntity, String.class); -ObjectMapper mapper= new ObjectMapper(); -JsonNode jsonNode= mapper.readTree(responseEntity.getBody()); -SignatureResponseDto signatureResponseDto=mapper.readValue(jsonNode.get("response").toString(), SignatureResponseDto.class); -FileUtils.writeByteArrayToFile(outFile,Base64.decodeBase64(signatureResponseDto.getData())); - ``` - -*Response* - -Status:200 - -``` - { - "data": "sq9oJCdwV-mHEdxEXRh91WkQcGJ6Q83quNaP9OZa_p0" - } -``` - -**Encrypt Request** - - ``` -OkHttpClient client = new OkHttpClient(); - -MediaType mediaType = MediaType.parse("multipart/form-data;boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW"); - -RequestBody body = RequestBody.create(mediaType, "{\r\n \"applicationId\": \"REGISTRATION\",\r\n \"data\": \"VGhpcyBpcyBhIHBsYWluIHRleHQ=\",\r\n \"referenceId\": \"ref123\",\r\n \"timeStamp\": \"2018-12-06T12:07:44.403Z\"\r\n}"); - -Request request = new Request.Builder() - .url("http://localhost:8087/cryptomanager/v1.0/encrypt") - .post(body) - .addHeader("content-type", "application/json") - .build(); - -Response response = client.newCall(request).execute(); - ``` - - *Response* - - Status:200 - - ``` -{ -"data":"EsGmECXJucN7AH6DHoKzzGs3bwspfOftQHwhpOWHUpptyFU1MYOz_iJxi1dBcLDXKQE_OV1xrY8Jyw0XUcSDbNYW9qHr5Hfbe30kTc-hCVNKItYN0OYOSBvgq9pd6TAatzlADvW6PRbRyHuumRqoD2ZL0tddiZqe6pa_Ya3hlTYsZm-L_65IJnkGDJLmxmMVS-pqqKqqtrXnTdYMjvK2wMkuZIFz4SX6F0jxnHz7XhrKSBzY8b8O4z1ZUterB450kKPzbRsZ3fySdjlpqhwtuVXZV6gkAA_n1iACOksvSyUZ7BN5AgWKnnsUHaNyF6f-e564G6nTN4M3Fyd_Z_KzxCNLRVlfU1BMSVRURVIjcvEHI6pM3H-kRWMRBZJDyte4BHKuUj4PBtU3dJ4kb_Vmd4nFBuguSh_tFHiz62GB" -} - ``` - - **Decrypt Request** - - ``` -OkHttpClient client = new OkHttpClient(); - -MediaType mediaType = MediaType.parse("application/json"); - -RequestBody body = RequestBody.create(mediaType, "{\n \"applicationId\": \"REGISTRATION\",\n \"data\": \"EsGmECXJucN7AH6DHoKzzGs3bwspfOftQHwhpOWHUpptyFU1MYOz_iJxi1dBcLDXKQE_OV1xrY8Jyw0XUcSDbNYW9qHr5Hfbe30kTc-hCVNKItYN0OYOSBvgq9pd6TAatzlADvW6PRbRyHuumRqoD2ZL0tddiZqe6pa_Ya3hlTYsZm-L_65IJnkGDJLmxmMVS-pqqKqqtrXnTdYMjvK2wMkuZIFz4SX6F0jxnHz7XhrKSBzY8b8O4z1ZUterB450kKPzbRsZ3fySdjlpqhwtuVXZV6gkAA_n1iACOksvSyUZ7BN5AgWKnnsUHaNyF6f-e564G6nTN4M3Fyd_Z_KzxCNLRVlfU1BMSVRURVIjcvEHI6pM3H-kRWMRBZJDyte4BHKuUj4PBtU3dJ4kb_Vmd4nFBuguSh_tFHiz62GB\",\n \"referenceId\": \"ref123\",\n \"timeStamp\": \"2018-12-06T12:07:44.403Z\"\n}\n"); - -Request request = new Request.Builder() - .url("http://localhost:8087/cryptomanager/v1.0/decrypt") - .post(body) - .addHeader("content-type", "application/json") - .build(); - -Response response = client.newCall(request).execute(); - ``` - - *Response* - - Status:200 - - ``` -{ - "data": "VGhpcyBpcyBhIHBsYWluIHRleHQ" -} - ``` - -**Sign Request** - - ``` -OkHttpClient client = new OkHttpClient(); - -MediaType mediaType = MediaType.parse("application/json"); -RequestBody body = RequestBody.create(mediaType, "{ \"id\": \"string\", \"metadata\": {}, \"request\": { \"data\": \"admin\" }, \"requesttime\": \"2018-12-10T06:12:52.994Z\", \"version\": \"string\" }"); -Request request = new Request.Builder() - .url("http://localhost:8092/v1/signature/sign") - .post(body) - .addHeader("Content-Type", "application/json") - .build(); - -Response response = client.newCall(request).execute(); - ``` - - *Response* - - HTTP Status: 200 OK - - ``` -{ - "id": null, - "version": null, - "responsetime": "2019-05-20T05:59:32.178Z", - "metadata": null, - "response": { - "signature": "ZeNsCOsdgf0UgpXDMry82hrHS6b1ZKvS-tZ_3HBGQHleIu1fZA6LNTtx7XZPFeC8dxsyuYO_iN3mVExM4J2tPlebzsRtuxHigi9o7DI_2xGqFudzlgoH55CP_BBNUDmGm6m-lTMkRx6X61dKfKDNo2NipZdM-a_cHf6Z0aVAU4LdJhV4xWOOm8Pb8sYIc2Nf6kUJRiidEGrxonUCfXX1XlnjMAo75wu99pN8G0mc7JhOehUqbwuXwKo4sQ694ae4F_AYl70sepX24v-0k0ga9esXR4i9rKaoHbzhQFtt2hangQkxHajq9ZTrXWMhd4msTzjHCKdEPXQFsTbKrgKtDQ", - "timestamp": "2019-05-20T05:59:31.934Z" - }, - "errors": null -} - ``` - -**The inputs which have to be provided for validate sign response by passing Response Timestamp along with the data and sign response:** - -1.signature -Mandatory - -2.data - Mandatory - -3.timestamp -Mandatory - - -**The response will be Validation Successful if request is successful, else throw exception Validation Unsuccessful** - - -**Signature Validate** - -*Request* - - ``` -OkHttpClient client = new OkHttpClient(); - -MediaType mediaType = MediaType.parse("application/json"); - -RequestBody body = RequestBody.create(mediaType, "{ \"id\": \"string\", \"metadata\": {}, \"request\": { \"signature\": \"DrgkF2vm4WvBe04UNe-RePRcrg77uQpsH3GENRcglBsid-K0UDReeeZVKwimOdwV7Ht1j-_D1BFf2sCrM8ni7ztE5Xc_3TEaniOAnOgZDRSI0GG-uSqjH51AwTSl1PYdStfXtOn6HEfEU68JG7TdAliDI5C7thJ1YNmPnHusIsZzX6sW_VfvSpLeA_RzCqnUDH_VaEzZt_5zRYiQv9van4wt0P7HTfIBlQ5zaeO3wXOc3Pogct3ssKwqdaMmZdc7QTDOFqDZZVceMTIXKyiH-ZVs_u3QXRysiLVdXoz7d7yXHdWxQtzsfMjY7alMJNgbmu4X26LYNRemn65Mmn6ixA\", \"data\": \"test\", \"timestamp\": \"2019-05-20T07:28:04.269Z\" }, \"requesttime\": \"2018-12-10T06:12:52.994Z\", \"version\": \"string\" }"); - - - -Request request = new Request.Builder() - .url("http://localhost:8092/v1/signature/validate") - .post(body) - .addHeader("Content-Type", "application/json") - .build(); - -Response response = client.newCall(request).execute(); - ``` - - *Response* - - HTTP Status: 200 OK - - ``` -{ - "id": null, - "version": null, - "responsetime": "2019-05-20T07:16:40.794Z", - "metadata": null, - "response": { - "status": "success", - "message": "Validation Successful" - }, - "errors": null -} - ``` - - **Token ID Generation** - - -``` -OkHttpClient client = new OkHttpClient(); - -Request request = new Request.Builder() - .url("http://localhost:8097/v1/tokenidgenerator/7394829283/PC001") - .get() - .build(); - -Response response = client.newCall(request).execute(); -``` - - - *Response:* - - HttpStatus: 200 OK - -``` -{ - "id": "mosip.kernel.tokenid.generate", - "version": "1.0", - "metadata": {}, - "responsetime": "2019-04-04T05:03:18.287Z", - "response": { - "tokenID": "268177021248100621690339355202974361" - }, - "errors": [] -} -``` - - - **License Key Generation :** - - ``` -{ -OkHttpClient client = new OkHttpClient(); - -MediaType mediaType = MediaType.parse("application/json"); -RequestBody body = RequestBody.create(mediaType, "{\"tspId\":\"TSPID1\",\"licenseExpiryTime\":\"2019-02-07T05:35:53.476Z\"}"); -Request request = new Request.Builder() - .url("http://localhost:8080/v1.0/license/generate") - .post(body) - .addHeader("content-type", "application/json") - .addHeader("cache-control", "no-cache") - .addHeader("postman-token", "7d3b19f4-5a6c-d926-4975-1f228f8caa3e") - .build(); - -Response response = client.newCall(request).execute(); -} - ``` - -*License Generation Responses :* -Successful Generation : - -HttpStatus : 200 OK - -``` -{ - "licenseKey": "rAx2TRvemovtZ0to" -} -``` - -**License Key Mapping:** - -``` -OkHttpClient client = new OkHttpClient(); - -MediaType mediaType = MediaType.parse("application/json"); -RequestBody body = RequestBody.create(mediaType, "{ \"lkey\": \"rAx2TRvemovtZ0to\",\"permissions\": [\"OTP Trigger\",\"OTP Authentication\"],\"tspId\": \"TSPID1\"}"); -Request request = new Request.Builder() - .url("http://localhost:8080/v1.0/license/map") - .post(body) - .addHeader("content-type", "application/json") - .addHeader("cache-control", "no-cache") - .addHeader("postman-token", "86230d1c-f33d-0ab1-6726-8f7f6ade6072") - .build(); - -Response response = client.newCall(request).execute(); - -``` -*License Mapping Responses:* - - HttpStatus : 200 OK - - - ``` -{ - "status": "Mapped License with the permissions" -} - ``` - -**License Key Fetch:** - -``` - OkHttpClient client = new OkHttpClient(); - -Request request = new Request.Builder() - .url("http://localhost:8080/v1.0/license/fetch?licenseKey=rAx2TRvemovtZ0to&tspId=TSPID1") - .get() - .addHeader("cache-control", "no-cache") - .addHeader("postman-token", "ac4daf24-2cef-f5f5-50f4-32b0d1938177") - .build(); - -``` - -*License Fetch Responses:* - - HttpStatus : 200 OK - - ``` -{ - "mappedPermissions": [ - "OTP Trigger", - "OTP Authentication" - ] -} - ``` - - - - -## Setup steps: - -### Linux (Docker) -- OLD Style - -1. (First time only) Rename the kernel-keymanager-softhsm Dockerfile in softhsm directory to `Dockerfile`. Build kernel-keymanager-softhsm docker image using this Dockerfile with command: - -``` -docker build --build-arg softhsm_pin=1234 --tag kernel-keymanager-softhsm:0.1 . -``` - -The pin passed to the variable `softhsm_pin` in docker build command should be same as the value of property -`mosip.kernel.keymanager.softhsm.keystore-pass` in properties file. - -2. (First time only) Modify the `FROM` in kernel-keymanager-service Dockerfile with kernel-keymanager-softhsm docker image name: -``` -FROM kernel-keymanager-softhsm:0.1 -``` - -OR - -2. (First time only) Push kernel-keymanager-softhsm docker image to private repository and modify the `FROM` in kernel-keymanager-service Dockerfile with kernel-keymanager-softhsm docker image URI: -``` -FROM /kernel-keymanager-softhsm:0.1 -``` - -3. Build kernel-keymanager-service docker image with command: - -``` -docker build --tag kernel-keymanager-service:1.0 . -``` - -4. Run docker container using command: - -``` -docker run -tid --ulimit memlock=-1 -p 8088:8088 -e spring_config_url_env= -e spring_config_label_env= -e active_profile_env= -v softhsm:/softhsm --name kernel-keymanager-service kernel-keymanager-service:1.0 -``` -#### Note: -- Remember to use docker volume using `-v softhsm:/softhsm` and do not add bind mount `(-v /softhsm:/softhsm)`. -- Keys will be stored in a docker volume named softhsm. To view information of this volume, run: - -``` -docker volume inspect softhsm -``` - -Know more about docker volume: https://docs.docker.com/storage/volumes/ -- It is recommended to set ulimit for memlock (the maximum size that may be locked into memory) to unlimited using -`--ulimit memlock=-1`. If not, the softhsm will warn with this message: - -``` -SoftHSM has been configured to store sensitive data in non-page RAM -(i.e. memory that is not swapped out to disk). This is the default and -most secure configuration. Your system, however, is not configured to -support this model in non-privileged accounts (i.e. user accounts). - -You can check the setting on your system by running the following -command in a shell: - - ulimit -l - -If this does not return "unlimited" and you plan to run SoftHSM from -non-privileged accounts then you should edit the configuration file -/etc/security/limits.conf (on most systems). - -You will need to add the following lines to this file: - -# -* - memlock unlimited - -Alternatively, you can elect to disable this feature of SoftHSM by -re-running configure with the option "--disable-non-paged-memory". -Please be advised that this may seriously degrade the security of -SoftHSM. -``` - -### Linux (Docker) -- New Style -With the new docker file the key manager is an independent of the type of HSM. The HSM is abstracted out of this layer using PKCS11 library and dynamic installation of client libraries for the HSM. - -However the key manager needs the hsm client (vendor specific) to interact with the various models of HSM. The Docker file is structured to download and install this client from the artifactory url $artifactory_url_env/artifactory/libs-release-local/hsm/client.zip. - -In our environment we will use a network based HSM from The HSM is run in network mode baed on the https://hub.docker.com/repository/docker/mosipdev/softhsm. The source code of this project is part of the mosip-mock-services projects. - -So in order to connect the key manager with the softhsm the following has to be done. - -1. Load the client.zip file from https://github.com/mosip/mosip-mock-services/softhsm to the artifactory in the path /artifactory/libs-release-local/hsm/client.zip -1. Run the keymanager docker using the following command or its equivalent yml - docker run -e artifactory_url_env="url pointing to the artifactory" -e PKCS11_PROXY_SOCKET="tcp://servicenameofsofthsm:5666" kernel-keymanager-service: - - -### Windows - -1. Download softhsm portable zip archive from https://github.com/disig/SoftHSM2-for-Windows#download -2. Extract it to any location, e.g `D:\SoftHSM2`. SoftHSM2 searches for its configuration file in the following locations: -``` - 1. Path specified by SOFTHSM2_CONF environment variable - 2. User specific path %HOMEDRIVE%%HOMEPATH%\softhsm2.conf - 3. File softhsm2.conf in the current working directory -``` -3. Modify following in environment variables: -``` -> set SOFTHSM2_CONF=D:\SoftHSM2\etc\softhsm2.conf -> set PATH=%PATH%;D:\SoftHSM2\lib\ -``` -4. Create another conf file at `D:\SoftHSM2\etc\softhsm-application.conf` with below content -``` -# Sun PKCS#11 provider configuration file for SoftHSMv2 -name = SoftHSM2 -library = D:\SoftHSM2\lib\softhsm2-x64.dll -slotListIndex = 0 -``` -5. Install JCE With an Unlimited Strength Jurisdiction Policy as shown here: -https://dzone.com/articles/install-java-cryptography-extension-jce-unlimited -6. Go to `D:\SoftHSM2\bin` and run below command: -``` -> softhsm2-util.exe --init-token --slot 0 --label "My token 1" -``` -Check token is initialized in slot with below command: -``` -> softhsm2-util.exe --show-slots -``` -The output should be like below: -``` -Slot 569035518 - Slot info: - Description: SoftHSM slot ID 0x21eacafe - Manufacturer ID: SoftHSM project - Hardware version: 2.4 - Firmware version: 2.4 - Token present: yes - Token info: - Manufacturer ID: SoftHSM project - Model: SoftHSM v2 - Hardware version: 2.4 - Firmware version: 2.4 - Serial number: b1ee933e21eacafe - Initialized: yes - User PIN init.: yes - Label: My token 1 -Slot 1 - Slot info: - Description: SoftHSM slot ID 0x1 - Manufacturer ID: SoftHSM project - Hardware version: 2.4 - Firmware version: 2.4 - Token present: yes - Token info: - Manufacturer ID: SoftHSM project - Model: SoftHSM v2 - Hardware version: 2.4 - Firmware version: 2.4 - Serial number: - Initialized: no - User PIN init.: no - Label: -``` -5. Put the newly created conf filepath `D:\SoftHSM2\etc\softhsm-application.conf` in `mosip.kernel.keymanager.softhsm.config-path` property. Softhsm is ready to be used. - -For more information, check https://github.com/opendnssec/SoftHSMv2 - - - - - - - - diff --git a/kernel/kernel-keymanager-service/configure_start.sh b/kernel/kernel-keymanager-service/configure_start.sh deleted file mode 100644 index 772d8841055..00000000000 --- a/kernel/kernel-keymanager-service/configure_start.sh +++ /dev/null @@ -1,40 +0,0 @@ -#!/bin/bash - -#installs the pkcs11 libraries. -set -e - -DEFAULT_ZIP_PATH=artifactory/libs-release-local/hsm/client.zip -[ -z "$hsm_zip_file_path" ] && zip_path="$DEFAULT_ZIP_PATH" || zip_path="$hsm_zip_file_path" - -echo "Download the client from $artifactory_url_env" -echo "Zip File Path: $zip_path" - -wget -q --show-progress "$artifactory_url_env/$zip_path" -echo "Downloaded $artifactory_url_env/$zip_path" - -FILE_NAME=${zip_path##*/} - -DIR_NAME=$hsm_local_dir_name - -has_parent=$(zipinfo -1 "$FILE_NAME" | awk '{split($NF,a,"/");print a[1]}' | sort -u | wc -l) -if test "$has_parent" -eq 1; then - echo "Zip has a parent directory inside" - dirname=$(zipinfo -1 "$FILE_NAME" | awk '{split($NF,a,"/");print a[1]}' | sort -u | head -n 1) - echo "Unzip directory" - unzip $FILE_NAME - echo "Renaming directory" - mv -v $dirname $DIR_NAME -else - echo "Zip has no parent directory inside" - echo "Creating destination directory" - mkdir "$DIR_NAME" - echo "Unzip to destination directory" - unzip -d "$DIR_NAME" $FILE_NAME -fi - -echo "Attempting to install" -cd ./$DIR_NAME && chmod +x install.sh && sudo ./install.sh -echo "Installation complete" -cd $work_dir - -exec "$@" \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/pom.xml b/kernel/kernel-keymanager-service/pom.xml deleted file mode 100644 index e813c3f9a20..00000000000 --- a/kernel/kernel-keymanager-service/pom.xml +++ /dev/null @@ -1,394 +0,0 @@ - - - 4.0.0 - - io.mosip.kernel - - kernel-keymanager-service - 1.2.0-rc2-SNAPSHOT - kernel-keymanager-service - Mosip commons project - https://github.com/mosip/commons - - - UTF-8 - - - 11 - 11 - 3.8.0 - - - 3.0.2 - 3.1.0 - - - 3.2.0 - 2.3 - - - 2.0.2.RELEASE - 2.0.7.RELEASE - 5.0.5.RELEASE - 2.0.4.RELEASE - - - 2.0.7 - 1.5.21 - 2.9.2 - - - 3.6.2 - 3.7.0 - - - - 1.2 - 3.0.0 - 1.3 - 2.2 - 2.0.1.Final - 2.2.6 - - - 1.4.197 - 5.1.46 - 42.2.2 - 2.5.0 - 5.2.17.Final - 6.0.12.Final - - - 4.12 - 2.23.4 - 1.7.4 - 2.0.7 - - - 1.2.3 - 1.7.19 - 1.7.7 - 1.7.25 - - - 2.9.5 - 2.9.8 - 2.9.6 - 20180130 - 2.2.10 - 20180813 - 1.1.1 - - - 3.6.1 - 3.7 - 2.6 - 1.11 - 4.3 - 1.9.2 - 2.2 - 4.5.6 - 19.0 - 1.18.8 - 0.1.54 - 1.4.0 - 7.1.0 - 2.0.0 - 5.5.13 - 2.3.23 - 1.7 - 2.0 - 1.5.2 - 2.1.1 - 1.66 - 63.1 - 1.0.0 - 3.3.3 - 3.1.0 - 4.1.0-incubating - 1.11.368 - 0.2.4 - 2.3.0 - 3.0.1 - 1.9.12 - 0.6.0 - 2.0.0.AM2 - 1.8.12 - 1.4.2 - 1.4.2 - UTF-8 - - 63.1 - 1.0.0 - 3.3.3 - 3.1.0 - 4.1.0-incubating - 1.11.368 - 0.2.4 - 2.3.0 - 3.0.1 - 1.9.12 - 0.6.0 - 2.0.0.AM2 - 1.8.12 - 1.4.2 - 1.4.2 - 1.2.0-rc2-SNAPSHOT - 1.2.0-rc2-SNAPSHOT - 1.2.0-rc2-SNAPSHOT - 1.2.0-rc2-SNAPSHOT - 1.2.0-rc2-SNAPSHOT - 0.6.5 - - 0.3.0 - true - - - - - io.mosip.kernel - kernel-core - ${kernel.core.version} - - - org.springframework.boot - spring-boot-starter-web - ${spring.boot.version} - - - io.springfox - springfox-swagger-ui - ${springfox.version} - - - io.springfox - springfox-swagger2 - ${springfox.version} - - - org.springframework.boot - spring-boot-starter-security - ${spring.boot.version} - - - org.springframework.security - spring-security-test - ${spring.security.test.version} - - - org.postgresql - postgresql - ${postgresql.version} - - - io.mosip.kernel - kernel-logger-logback - ${kernel.logger.logback.version} - - - io.mosip.kernel - kernel-pdfgenerator-itext - ${kernel.pdfgenerator.itext.version} - - - org.springframework.boot - spring-boot-starter-data-jpa - ${spring.boot.version} - - - com.h2database - h2 - ${h2.version} - runtime - - - org.bitbucket.b_c - jose4j - ${jose4j.version} - - - com.github.microsoft - TSS.Java - ${tss.version} - - - - - - ossrh - https://oss.sonatype.org/content/repositories/snapshots - - - ossrh - https://oss.sonatype.org/service/local/staging/deploy/maven2/ - - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring.boot.version} - - true - ZIP - - - - - build-info - repackage - - - - - - maven-jar-plugin - - - package - - jar - - - lib - - - - - - maven-deploy-plugin - 2.8.1 - - - default-deploy - deploy - - deploy - - - - - - org.sonatype.plugins - nexus-staging-maven-plugin - 1.6.7 - true - - - default-deploy - deploy - - deploy - - - - - ossrh - https://oss.sonatype.org/ - false - - - - - org.apache.maven.plugins - maven-source-plugin - true - 2.2.1 - - - attach-sources - - jar-no-fork - - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 3.2.0 - - - attach-javadocs - - jar - - - - - none - - - - org.apache.maven.plugins - maven-gpg-plugin - 1.5 - - - sign-artifacts - verify - - sign - - - - --pinentry-mode - loopback - - - - - - - pl.project13.maven - git-commit-id-plugin - 3.0.1 - - - get-the-git-infos - - revision - - validate - - - - true - ${project.build.outputDirectory}/git.properties - - ^git.build.(time|version)$ - ^git.commit.id.(abbrev|full)$ - - full - ${project.basedir}/.git - - - - - - - scm:git:git://github.com/mosip/commons.git - scm:git:ssh://github.com:mosip/commons.git - https://github.com/mosip/commons - HEAD - - - - MPL 2.0 - https://www.mozilla.org/en-US/MPL/2.0/ - - - - - Mosip - mosip.emailnotifier@gmail.com - io.mosip - https://github.com/mosip/commons - - - - diff --git a/kernel/kernel-keymanager-service/softhsm-application.conf b/kernel/kernel-keymanager-service/softhsm-application.conf deleted file mode 100644 index e8828e7b53e..00000000000 --- a/kernel/kernel-keymanager-service/softhsm-application.conf +++ /dev/null @@ -1,4 +0,0 @@ -#Sun PKCS#11 provider configuration file for SoftHSMv2 -name = SoftHSM2 -library = /softhsm/lib/softhsm/libsofthsm2.so -slotListIndex = 0 diff --git a/kernel/kernel-keymanager-service/softhsm/Dockerfile-softhsm b/kernel/kernel-keymanager-service/softhsm/Dockerfile-softhsm deleted file mode 100644 index af1d383ca5e..00000000000 --- a/kernel/kernel-keymanager-service/softhsm/Dockerfile-softhsm +++ /dev/null @@ -1,33 +0,0 @@ -FROM anapsix/alpine-java:8_jdk_unlimited - -# Required to be passed at docker build time like: docker build --build-arg softhsm_pin=1234 --tag kernel-keymanager-service:1.0 . -ARG softhsm_pin - -ENV softhsm_pin_env=${softhsm_pin} - -RUN apk --update add \ - alpine-sdk \ - autoconf \ - automake \ - expect \ - git \ - libtool \ - openssl-dev - -RUN git clone https://github.com/opendnssec/SoftHSMv2.git /tmp/softhsm2 - -WORKDIR /tmp/softhsm2 - -RUN git checkout 2.5.0 -b 2.5.0 \ - && sh autogen.sh \ - && ./configure --prefix=/softhsm \ - && make \ - && make install - -WORKDIR /root - -RUN rm -rf /tmp/softhsm2 - -RUN chmod -R 777 /softhsm - -RUN /softhsm/bin/softhsm2-util --init-token --slot 0 --pin ${softhsm_pin_env} --so-pin ${softhsm_pin_env} --label 'Keymanager_token' \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/META-INF/MANIFEST.MF b/kernel/kernel-keymanager-service/src/main/java/META-INF/MANIFEST.MF deleted file mode 100644 index 254272e1c07..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/META-INF/MANIFEST.MF +++ /dev/null @@ -1,3 +0,0 @@ -Manifest-Version: 1.0 -Class-Path: - diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/constant/ClientCryptoErrorConstants.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/constant/ClientCryptoErrorConstants.java deleted file mode 100644 index 99fccbe11de..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/constant/ClientCryptoErrorConstants.java +++ /dev/null @@ -1,43 +0,0 @@ -package io.mosip.kernel.clientcrypto.constant; - -public enum ClientCryptoErrorConstants { - - TPM_REQUIRED("KER-CC-001", "TPM INSTANCE IS REQUIRED"), - INITIALIZATION_ERROR("KER-CC-002", "FAILED TO INITIALIZE CC INSTANCE"), - CONTEXT_RELOAD_REQUIRED("KER-CC-003", "Restart / reload context"), - CRYPTO_FAILED("KER-CC-004", "Failed crypto operation"), - TPM_REQUIRED_FLAG_NOT_SET("KER-CC-005", "TPM required flag not set"); - - /** - * The error code. - */ - private final String errorCode; - - /** - * The error message. - */ - private final String errorMessage; - - /** - * @param errorCode The error code to be set. - * @param errorMessage The error message to be set. - */ - private ClientCryptoErrorConstants(String errorCode, String errorMessage) { - this.errorCode = errorCode; - this.errorMessage = errorMessage; - } - - /** - * @return The error code. - */ - public String getErrorCode() { - return errorCode; - } - - /** - * @return The error message. - */ - public String getErrorMessage() { - return errorMessage; - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/constant/ClientCryptoManagerConstant.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/constant/ClientCryptoManagerConstant.java deleted file mode 100644 index 9ff8f4cfd66..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/constant/ClientCryptoManagerConstant.java +++ /dev/null @@ -1,24 +0,0 @@ -package io.mosip.kernel.clientcrypto.constant; - -/** - * @author Anusha Sunkada - * @since 1.1.2 - */ -public interface ClientCryptoManagerConstant { - - String SESSIONID = "ccSessionID"; - String INITIALIZATION = "INITIALIZATION"; - String EMPTY = ""; - - String TPM = "TPM"; - String NON_TPM = "NON-TPM"; - - String SERVER_PROD_PROFILE = "PROD"; - - String KEY_PATH = System.getProperty("user.dir"); - String KEYS_DIR = ".mosipkeys"; - String DB_PWD_FILE = "db.conf"; - - String ENABLED = "Y"; - String DISABLED = "N"; -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/controller/ClientCryptoController.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/controller/ClientCryptoController.java deleted file mode 100644 index 80bc49107c7..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/controller/ClientCryptoController.java +++ /dev/null @@ -1,129 +0,0 @@ -package io.mosip.kernel.clientcrypto.controller; - - -import javax.validation.Valid; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.CrossOrigin; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RestController; - -import io.mosip.kernel.clientcrypto.dto.PublicKeyRequestDto; -import io.mosip.kernel.clientcrypto.dto.PublicKeyResponseDto; -import io.mosip.kernel.clientcrypto.dto.TpmCryptoRequestDto; -import io.mosip.kernel.clientcrypto.dto.TpmCryptoResponseDto; -import io.mosip.kernel.clientcrypto.dto.TpmSignRequestDto; -import io.mosip.kernel.clientcrypto.dto.TpmSignResponseDto; -import io.mosip.kernel.clientcrypto.dto.TpmSignVerifyRequestDto; -import io.mosip.kernel.clientcrypto.dto.TpmSignVerifyResponseDto; -import io.mosip.kernel.clientcrypto.service.spi.ClientCryptoManagerService; -import io.mosip.kernel.core.http.RequestWrapper; -import io.mosip.kernel.core.http.ResponseFilter; -import io.mosip.kernel.core.http.ResponseWrapper; -import io.swagger.annotations.Api; - -/** - * @author Anusha Sunkada - * @since 1.1.2 - */ - -@CrossOrigin -@RestController -@Api(value = "Operation related to offline Encryption and Decryption", tags = { "clientcrypto" }) -public class ClientCryptoController { - - @Autowired - private ClientCryptoManagerService clientCryptoManagerService; - - /** - * - * @param tpmSignRequestDtoRequestWrapper - * @return - */ - @PreAuthorize("hasAnyRole('ZONAL_ADMIN','GLOBAL_ADMIN','INDIVIDUAL','ID_AUTHENTICATION','TEST', 'REGISTRATION_ADMIN', 'REGISTRATION_SUPERVISOR', 'REGISTRATION_OFFICER', 'REGISTRATION_PROCESSOR','PRE_REGISTRATION_ADMIN','RESIDENT')") - @ResponseFilter - @PostMapping(value = "/cssign", produces = "application/json") - public ResponseWrapper signData(@RequestBody @Valid RequestWrapper - tpmSignRequestDtoRequestWrapper) { - ResponseWrapper responseDtoResponseWrapper = new ResponseWrapper<>(); - responseDtoResponseWrapper.setResponse(clientCryptoManagerService.csSign(tpmSignRequestDtoRequestWrapper.getRequest())); - return responseDtoResponseWrapper; - } - - /** - * - * @param tpmSignVerifyRequestDtoRequestWrapper - * @return - */ - @PreAuthorize("hasAnyRole('ZONAL_ADMIN','GLOBAL_ADMIN','INDIVIDUAL','ID_AUTHENTICATION','TEST', 'REGISTRATION_ADMIN', 'REGISTRATION_SUPERVISOR', 'REGISTRATION_OFFICER', 'REGISTRATION_PROCESSOR','PRE_REGISTRATION_ADMIN','RESIDENT')") - @ResponseFilter - @PostMapping(value = "/csverifysign", produces = "application/json") - public ResponseWrapper verifySignature(@RequestBody @Valid RequestWrapper - tpmSignVerifyRequestDtoRequestWrapper) { - ResponseWrapper responseDtoResponseWrapper = new ResponseWrapper<>(); - responseDtoResponseWrapper.setResponse(clientCryptoManagerService.csVerify(tpmSignVerifyRequestDtoRequestWrapper.getRequest())); - return responseDtoResponseWrapper; - } - - /** - * - * @param tpmCryptoRequestDtoRequestWrapper - * @return - */ - @PreAuthorize("hasAnyRole('ZONAL_ADMIN','GLOBAL_ADMIN','INDIVIDUAL','ID_AUTHENTICATION','TEST', 'REGISTRATION_ADMIN', 'REGISTRATION_SUPERVISOR', 'REGISTRATION_OFFICER', 'REGISTRATION_PROCESSOR','PRE_REGISTRATION_ADMIN','RESIDENT')") - @ResponseFilter - @PostMapping(value = "/tpmencrypt", produces = "application/json") - public ResponseWrapper tpmEncrypt(@RequestBody @Valid RequestWrapper - tpmCryptoRequestDtoRequestWrapper) { - ResponseWrapper responseDtoResponseWrapper = new ResponseWrapper<>(); - responseDtoResponseWrapper.setResponse(clientCryptoManagerService.csEncrypt(tpmCryptoRequestDtoRequestWrapper.getRequest())); - return responseDtoResponseWrapper; - } - - /** - * - * @param tpmCryptoRequestDtoRequestWrapper - * @return - */ - @PreAuthorize("hasAnyRole('ZONAL_ADMIN','GLOBAL_ADMIN','INDIVIDUAL','ID_AUTHENTICATION','TEST', 'REGISTRATION_ADMIN', 'REGISTRATION_SUPERVISOR', 'REGISTRATION_OFFICER', 'REGISTRATION_PROCESSOR','PRE_REGISTRATION_ADMIN','RESIDENT')") - @ResponseFilter - @PostMapping(value = "/tpmdecrypt", produces = "application/json") - public ResponseWrapper tpmDecrypt(@RequestBody @Valid RequestWrapper - tpmCryptoRequestDtoRequestWrapper) { - ResponseWrapper responseDtoResponseWrapper = new ResponseWrapper<>(); - responseDtoResponseWrapper.setResponse(clientCryptoManagerService.csDecrypt(tpmCryptoRequestDtoRequestWrapper.getRequest())); - return responseDtoResponseWrapper; - } - - /** - * - * @param publicKeyRequestDtoRequestWrapper - * @return - */ - @PreAuthorize("hasAnyRole('ZONAL_ADMIN','GLOBAL_ADMIN','INDIVIDUAL','ID_AUTHENTICATION','TEST', 'REGISTRATION_ADMIN', 'REGISTRATION_SUPERVISOR', 'REGISTRATION_OFFICER', 'REGISTRATION_PROCESSOR','PRE_REGISTRATION_ADMIN','RESIDENT')") - @ResponseFilter - @PostMapping(value = "/tpmsigning/publickey", produces = "application/json") - public ResponseWrapper getSigningPublicKey(@RequestBody @Valid RequestWrapper - publicKeyRequestDtoRequestWrapper) { - ResponseWrapper responseDtoResponseWrapper = new ResponseWrapper<>(); - responseDtoResponseWrapper.setResponse(clientCryptoManagerService.getSigningPublicKey(publicKeyRequestDtoRequestWrapper.getRequest())); - return responseDtoResponseWrapper; - } - - /** - * - * @param publicKeyRequestDtoRequestWrapper - * @return - */ - @PreAuthorize("hasAnyRole('ZONAL_ADMIN','GLOBAL_ADMIN','INDIVIDUAL','ID_AUTHENTICATION','TEST', 'REGISTRATION_ADMIN', 'REGISTRATION_SUPERVISOR', 'REGISTRATION_OFFICER', 'REGISTRATION_PROCESSOR','PRE_REGISTRATION_ADMIN','RESIDENT')") - @ResponseFilter - @PostMapping(value = "/tpmencryption/publickey", produces = "application/json") - public ResponseWrapper getEncPublicKey(@RequestBody @Valid RequestWrapper - publicKeyRequestDtoRequestWrapper) { - ResponseWrapper responseDtoResponseWrapper = new ResponseWrapper<>(); - responseDtoResponseWrapper.setResponse(clientCryptoManagerService.getEncPublicKey(publicKeyRequestDtoRequestWrapper.getRequest())); - return responseDtoResponseWrapper; - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/dto/PublicKeyRequestDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/dto/PublicKeyRequestDto.java deleted file mode 100644 index 192dbfdec2e..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/dto/PublicKeyRequestDto.java +++ /dev/null @@ -1,26 +0,0 @@ -package io.mosip.kernel.clientcrypto.dto; - -import io.mosip.kernel.keymanagerservice.constant.KeymanagerConstant; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -import javax.validation.constraints.NotBlank; - -@Data -@AllArgsConstructor -@NoArgsConstructor -@ApiModel(description = "Model representing to fetch signing public key from TPM request") -public class PublicKeyRequestDto { - - /** - * server profile name - */ - @ApiModelProperty(notes = "Server Profile (Prod / QA / Dev)", required = true) - @NotBlank(message = KeymanagerConstant.INVALID_REQUEST) - String serverProfile; - - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/dto/PublicKeyResponseDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/dto/PublicKeyResponseDto.java deleted file mode 100644 index f1f351f43e8..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/dto/PublicKeyResponseDto.java +++ /dev/null @@ -1,21 +0,0 @@ -package io.mosip.kernel.clientcrypto.dto; - - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -@Data -@AllArgsConstructor -@NoArgsConstructor -@ApiModel(description = "Class representing a Public Key Response") -public class PublicKeyResponseDto { - - /** - * Field for public key - */ - @ApiModelProperty(notes = "Public key in BASE64 encoding format", required = true) - private String publicKey; -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/dto/TpmCryptoRequestDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/dto/TpmCryptoRequestDto.java deleted file mode 100644 index ce6dc29c27c..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/dto/TpmCryptoRequestDto.java +++ /dev/null @@ -1,37 +0,0 @@ -package io.mosip.kernel.clientcrypto.dto; - -import io.mosip.kernel.keymanagerservice.constant.KeymanagerConstant; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -import javax.validation.constraints.NotBlank; - -@Data -@AllArgsConstructor -@NoArgsConstructor -@ApiModel(description = "Model representing a data for encrypt/decrypt") -public class TpmCryptoRequestDto { - - /** - * Base64 encoded data to encrypt/decrypt. - */ - @ApiModelProperty(notes = "Data to Encrypt/Decrypt", example = "Any String", required = true) - @NotBlank(message = KeymanagerConstant.INVALID_REQUEST) - private String value; - - /** - * public key in BASE64 encoding - */ - @ApiModelProperty(notes = "encrypting public key", required = true) - @NotBlank(message = KeymanagerConstant.INVALID_REQUEST) - private String publicKey; - - /** - * Flag to identify TPM or Non-TPM validations - */ - @ApiModelProperty(notes = "Defaults to TPM, set to false for non-tpm based verification", required = false) - private boolean isTpm; -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/dto/TpmCryptoResponseDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/dto/TpmCryptoResponseDto.java deleted file mode 100644 index ea6ea8dd32f..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/dto/TpmCryptoResponseDto.java +++ /dev/null @@ -1,20 +0,0 @@ -package io.mosip.kernel.clientcrypto.dto; - -import io.swagger.annotations.ApiModel; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - - -@Data -@AllArgsConstructor -@NoArgsConstructor -@ApiModel(description = "Model representing response for encrypt/decrypt request") -public class TpmCryptoResponseDto { - - /** - * Encrypted / decrypted data - */ - private String value; - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/dto/TpmSignRequestDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/dto/TpmSignRequestDto.java deleted file mode 100644 index 15f32b9d50e..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/dto/TpmSignRequestDto.java +++ /dev/null @@ -1,24 +0,0 @@ -package io.mosip.kernel.clientcrypto.dto; - -import io.mosip.kernel.keymanagerservice.constant.KeymanagerConstant; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -import javax.validation.constraints.NotBlank; - -@Data -@AllArgsConstructor -@NoArgsConstructor -@ApiModel(description = "Model representing response for sign request") -public class TpmSignRequestDto { - - /** - * Data in BASE64 encoding to sign - */ - @ApiModelProperty(notes = "Data to sign", required = true) - @NotBlank(message = KeymanagerConstant.INVALID_REQUEST) - private String data; -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/dto/TpmSignResponseDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/dto/TpmSignResponseDto.java deleted file mode 100644 index 71a534bc171..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/dto/TpmSignResponseDto.java +++ /dev/null @@ -1,13 +0,0 @@ -package io.mosip.kernel.clientcrypto.dto; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -@Data -@AllArgsConstructor -@NoArgsConstructor -public class TpmSignResponseDto { - - private String data; -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/dto/TpmSignVerifyRequestDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/dto/TpmSignVerifyRequestDto.java deleted file mode 100644 index c679a7b1814..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/dto/TpmSignVerifyRequestDto.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.mosip.kernel.clientcrypto.dto; - - -import io.mosip.kernel.keymanagerservice.constant.KeymanagerConstant; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -import javax.validation.constraints.NotBlank; - -@Data -@AllArgsConstructor -@NoArgsConstructor -@ApiModel(description = "Model representing request for signature verification") -public class TpmSignVerifyRequestDto { - - /** - * Data in BASE64 encoding - */ - @ApiModelProperty(notes = "Data corresponding to signature", required = true) - @NotBlank(message = KeymanagerConstant.INVALID_REQUEST) - private String data; - - /** - * Signature in BASE64 encoding - */ - @ApiModelProperty(notes = "Signature", required = true) - @NotBlank(message = KeymanagerConstant.INVALID_REQUEST) - private String signature; - - /** - * public key in BASE64 encoding - */ - @ApiModelProperty(notes = "Signing public key", required = true) - @NotBlank(message = KeymanagerConstant.INVALID_REQUEST) - private String publicKey; - - /** - * Flag to identify TPM or Non-TPM validations - */ - @ApiModelProperty(notes = "Defaults to TPM, set to false for non-tpm based verification", required = false) - private boolean isTpm; -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/dto/TpmSignVerifyResponseDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/dto/TpmSignVerifyResponseDto.java deleted file mode 100644 index 09b117589a2..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/dto/TpmSignVerifyResponseDto.java +++ /dev/null @@ -1,13 +0,0 @@ -package io.mosip.kernel.clientcrypto.dto; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -@Data -@AllArgsConstructor -@NoArgsConstructor -public class TpmSignVerifyResponseDto { - - private boolean verified; -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/exception/ClientCryptoException.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/exception/ClientCryptoException.java deleted file mode 100644 index 7f6673703b7..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/exception/ClientCryptoException.java +++ /dev/null @@ -1,35 +0,0 @@ -package io.mosip.kernel.clientcrypto.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; - -/** - * @author Anusha Sunkada - * @since 1.1.2 - * - */ -public class ClientCryptoException extends BaseUncheckedException { - - /** - * Generated serial version id - */ - private static final long serialVersionUID = 8621530697947108810L; - - /** - * Constructor the initialize Handler exception - * - * @param errorCode The errorcode for this exception - * @param errorMessage The error message for this exception - */ - public ClientCryptoException(String errorCode, String errorMessage) { - super(errorCode, errorMessage); - } - - /** - * @param errorCode The errorcode for this exception - * @param errorMessage The error message for this exception - * @param rootCause cause of the error occoured - */ - public ClientCryptoException(String errorCode, String errorMessage, Throwable rootCause) { - super(errorCode, errorMessage, rootCause); - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/service/impl/ClientCryptoFacade.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/service/impl/ClientCryptoFacade.java deleted file mode 100644 index 54c4229ff35..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/service/impl/ClientCryptoFacade.java +++ /dev/null @@ -1,177 +0,0 @@ -package io.mosip.kernel.clientcrypto.service.impl; - -import io.mosip.kernel.clientcrypto.constant.ClientCryptoErrorConstants; -import io.mosip.kernel.clientcrypto.constant.ClientCryptoManagerConstant; -import io.mosip.kernel.clientcrypto.exception.ClientCryptoException; -import io.mosip.kernel.clientcrypto.service.spi.ClientCryptoService; -import io.mosip.kernel.core.crypto.spi.CryptoCoreSpec; -import io.mosip.kernel.core.exception.ExceptionUtils; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.keymanagerservice.logger.KeymanagerLogger; - -import org.junit.Assert; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.env.Environment; -import org.springframework.stereotype.Component; -import tss.tpm.TPMT_PUBLIC; - -import javax.crypto.KeyGenerator; -import javax.crypto.SecretKey; -import javax.crypto.spec.SecretKeySpec; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.util.Arrays; -import java.util.Objects; - -@Component -public class ClientCryptoFacade { - - private static final Logger LOGGER = KeymanagerLogger.getLogger(ClientCryptoFacade.class); - private static SecureRandom secureRandom = null; - private static ClientCryptoService clientCryptoService = null; - - @Autowired - private CryptoCoreSpec cryptoCore; - - @Autowired - private Environment environment; - - @Value("${mosip.kernel.client.crypto.iv-length:12}") - private int ivLength; - - @Value("${mosip.kernel.client.crypto.aad-length:32}") - private int aadLength; - - //we are using 2048 bit RSA key - @Value("${mosip.kernel.client.crypto.sym-key-length:256}") - private int symmetricKeyLength; - - @Deprecated - public static void setIsTPMRequired(boolean flag) { - //nothing to do @since 1.1.4 - } - - private void initializeClientSecurity() { - LOGGER.debug(ClientCryptoManagerConstant.SESSIONID, ClientCryptoManagerConstant.INITIALIZATION, - ClientCryptoManagerConstant.EMPTY, "initializeClientSecurity >>> started"); - - try { - clientCryptoService = new TPMClientCryptoServiceImpl(); - } catch(Throwable e) { - LOGGER.debug(ClientCryptoManagerConstant.SESSIONID, ClientCryptoManagerConstant.INITIALIZATION, - ClientCryptoManagerConstant.EMPTY, ExceptionUtils.getStackTrace(e)); - } - - if(clientCryptoService == null) { - try { - LOGGER.warn(ClientCryptoManagerConstant.SESSIONID, ClientCryptoManagerConstant.INITIALIZATION, ClientCryptoManagerConstant.EMPTY, - "USING LOCAL CLIENT SECURITY INITIALIZED, IGNORE IF THIS IS NON-PROD ENV"); - clientCryptoService = new LocalClientCryptoServiceImpl(cryptoCore); - } catch (Throwable ex) { - LOGGER.error(ClientCryptoManagerConstant.SESSIONID, ClientCryptoManagerConstant.INITIALIZATION, - ClientCryptoManagerConstant.EMPTY, ExceptionUtils.getStackTrace(ex)); - } - } - - if(clientCryptoService == null) { - LOGGER.error(ClientCryptoManagerConstant.SESSIONID, ClientCryptoManagerConstant.INITIALIZATION, - ClientCryptoManagerConstant.EMPTY, "Failed to get client security instance."); - throw new ClientCryptoException(ClientCryptoErrorConstants.INITIALIZATION_ERROR.getErrorCode(), - ClientCryptoErrorConstants.INITIALIZATION_ERROR.getErrorMessage()); - } - - LOGGER.debug(ClientCryptoManagerConstant.SESSIONID, ClientCryptoManagerConstant.INITIALIZATION, - ClientCryptoManagerConstant.EMPTY, "initializeClientSecurity >>> Completed"); - } - - public ClientCryptoService getClientSecurity() { - if(clientCryptoService == null) { - initializeClientSecurity(); - } - return clientCryptoService; - } - - public boolean validateSignature(byte[] publicKey, byte[] signature, byte[] actualData) { - if(!isTPMKey(publicKey)) { - LOGGER.warn(ClientCryptoManagerConstant.SESSIONID, ClientCryptoManagerConstant.INITIALIZATION, ClientCryptoManagerConstant.EMPTY, - "USING LOCAL CLIENT SECURITY USED TO SIGN DATA, IGNORE IF THIS IS NON-PROD ENV"); - return LocalClientCryptoServiceImpl.validateSignature(publicKey, signature, actualData); - } - return TPMClientCryptoServiceImpl.validateSignature(publicKey, signature, actualData); - } - - public byte[] encrypt(byte[] publicKey, byte[] dataToEncrypt) { - SecretKey secretKey = getSecretKey(); - byte[] iv = generateRandomBytes(ivLength); - byte[] aad = generateRandomBytes(aadLength); - byte[] cipher = cryptoCore.symmetricEncrypt(secretKey, dataToEncrypt, iv, aad); - - byte[] encryptedSecretKey = null; - if(!isTPMKey(publicKey)) { - LOGGER.warn(ClientCryptoManagerConstant.SESSIONID, ClientCryptoManagerConstant.INITIALIZATION, ClientCryptoManagerConstant.EMPTY, - "USING LOCAL CLIENT SECURITY USED TO ENCRYPT DATA, IGNORE IF THIS IS NON-PROD ENV"); - LocalClientCryptoServiceImpl.cryptoCore = this.cryptoCore; - encryptedSecretKey = LocalClientCryptoServiceImpl.asymmetricEncrypt(publicKey, secretKey.getEncoded()); - } - else { - encryptedSecretKey = TPMClientCryptoServiceImpl.asymmetricEncrypt(publicKey, secretKey.getEncoded()); - } - Objects.requireNonNull(encryptedSecretKey); - byte[] processedData = new byte[cipher.length+encryptedSecretKey.length+iv.length+aad.length]; - System.arraycopy(encryptedSecretKey,0,processedData, 0, encryptedSecretKey.length); - System.arraycopy(iv, 0, processedData, encryptedSecretKey.length, iv.length); - System.arraycopy(aad, 0, processedData, encryptedSecretKey.length + iv.length, aad.length); - System.arraycopy(cipher, 0, processedData, encryptedSecretKey.length + iv.length + aad.length, cipher.length); - return processedData; - } - - public byte[] decrypt(byte[] dataToDecrypt) { - Assert.assertNotNull(getClientSecurity()); - byte[] encryptedSecretKey = Arrays.copyOfRange(dataToDecrypt, 0, symmetricKeyLength); - byte[] secretKeyBytes = getClientSecurity().asymmetricDecrypt(encryptedSecretKey); - byte[] iv = Arrays.copyOfRange(dataToDecrypt, symmetricKeyLength, symmetricKeyLength+ivLength); - byte[] aad = Arrays.copyOfRange(dataToDecrypt, symmetricKeyLength + ivLength, symmetricKeyLength+ivLength+aadLength); - byte[] cipher = Arrays.copyOfRange(dataToDecrypt, symmetricKeyLength + ivLength + aadLength, - dataToDecrypt.length); - - SecretKey secretKey = new SecretKeySpec(secretKeyBytes, "AES"); - return cryptoCore.symmetricDecrypt(secretKey, cipher, iv, aad); - } - - public static byte[] generateRandomBytes(int length) { - if(secureRandom == null) - secureRandom = new SecureRandom(); - - byte[] bytes = new byte[length]; - secureRandom.nextBytes(bytes); - return bytes; - } - - private static SecretKey getSecretKey() { - try { - KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); - keyGenerator.init(256); - return keyGenerator.generateKey(); - } catch (NoSuchAlgorithmException e) { - LOGGER.info(ClientCryptoManagerConstant.SESSIONID, "Client Security FACADE", - ClientCryptoManagerConstant.EMPTY, "Failed to generate secret key " + ExceptionUtils.getStackTrace(e)); - } - return null; - } - - private boolean isTPMKey(byte[] publicKey) { - try { - TPMT_PUBLIC tpmPublic = TPMT_PUBLIC.fromTpm(publicKey); - Objects.requireNonNull(tpmPublic); - return true; - } catch (Throwable t) { - //*** INVALID TPM KEY **** As its noisy, its logged at debug level - LOGGER.debug("*** INVALID TPM KEY **** " + ExceptionUtils.getStackTrace(t)); - } - return false; - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/service/impl/ClientCryptoManagerServiceImpl.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/service/impl/ClientCryptoManagerServiceImpl.java deleted file mode 100644 index 7e4ac62e815..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/service/impl/ClientCryptoManagerServiceImpl.java +++ /dev/null @@ -1,77 +0,0 @@ -package io.mosip.kernel.clientcrypto.service.impl; - -import io.mosip.kernel.clientcrypto.dto.*; -import io.mosip.kernel.clientcrypto.service.spi.ClientCryptoManagerService; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.CryptoUtil; -import io.mosip.kernel.keymanagerservice.logger.KeymanagerLogger; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -/** - * @author Anusha Sunkada - * @since 1.1.2 - */ -@Service -public class ClientCryptoManagerServiceImpl implements ClientCryptoManagerService { - - private static final Logger LOGGER = KeymanagerLogger.getLogger(ClientCryptoManagerServiceImpl.class); - - @Autowired - private ClientCryptoFacade clientCryptoFacade; - - @Override - public TpmSignResponseDto csSign(TpmSignRequestDto tpmSignRequestDto) { - byte[] signedData = clientCryptoFacade.getClientSecurity().signData( - CryptoUtil.decodeBase64(tpmSignRequestDto.getData())); - TpmSignResponseDto tpmSignResponseDto = new TpmSignResponseDto(); - tpmSignResponseDto.setData(CryptoUtil.encodeBase64(signedData)); - return tpmSignResponseDto; - } - - @Override - public TpmSignVerifyResponseDto csVerify(TpmSignVerifyRequestDto tpmSignVerifyRequestDto) { - boolean result = clientCryptoFacade.validateSignature( - CryptoUtil.decodeBase64(tpmSignVerifyRequestDto.getPublicKey()), - CryptoUtil.decodeBase64(tpmSignVerifyRequestDto.getSignature()), - CryptoUtil.decodeBase64(tpmSignVerifyRequestDto.getData())); - TpmSignVerifyResponseDto tpmSignVerifyResponseDto = new TpmSignVerifyResponseDto(); - tpmSignVerifyResponseDto.setVerified(result); - return tpmSignVerifyResponseDto; - } - - @Override - public TpmCryptoResponseDto csEncrypt(TpmCryptoRequestDto tpmCryptoRequestDto) { - byte[] cipher = clientCryptoFacade.encrypt( - CryptoUtil.decodeBase64(tpmCryptoRequestDto.getPublicKey()), - CryptoUtil.decodeBase64(tpmCryptoRequestDto.getValue())); - TpmCryptoResponseDto tpmCryptoResponseDto = new TpmCryptoResponseDto(); - tpmCryptoResponseDto.setValue(CryptoUtil.encodeBase64(cipher)); - return tpmCryptoResponseDto; - } - - @Override - public TpmCryptoResponseDto csDecrypt(TpmCryptoRequestDto tpmCryptoRequestDto) { - byte[] plainData = clientCryptoFacade.decrypt(CryptoUtil.decodeBase64(tpmCryptoRequestDto.getValue())); - TpmCryptoResponseDto tpmCryptoResponseDto = new TpmCryptoResponseDto(); - tpmCryptoResponseDto.setValue(CryptoUtil.encodeBase64(plainData)); - return tpmCryptoResponseDto; - } - - @Override - public PublicKeyResponseDto getSigningPublicKey(PublicKeyRequestDto publicKeyRequestDto) { - PublicKeyResponseDto publicKeyResponseDto = new PublicKeyResponseDto(); - publicKeyResponseDto.setPublicKey(CryptoUtil.encodeBase64(clientCryptoFacade.getClientSecurity(). - getSigningPublicPart())); - return publicKeyResponseDto; - } - - @Override - public PublicKeyResponseDto getEncPublicKey(PublicKeyRequestDto publicKeyRequestDto) { - PublicKeyResponseDto publicKeyResponseDto = new PublicKeyResponseDto(); - publicKeyResponseDto.setPublicKey(CryptoUtil.encodeBase64(clientCryptoFacade.getClientSecurity(). - getEncryptionPublicPart())); - return publicKeyResponseDto; - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/service/impl/LocalClientCryptoServiceImpl.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/service/impl/LocalClientCryptoServiceImpl.java deleted file mode 100644 index a01e1714b7c..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/service/impl/LocalClientCryptoServiceImpl.java +++ /dev/null @@ -1,302 +0,0 @@ -package io.mosip.kernel.clientcrypto.service.impl; - -import io.mosip.kernel.clientcrypto.constant.ClientCryptoErrorConstants; -import io.mosip.kernel.clientcrypto.constant.ClientCryptoManagerConstant; -import io.mosip.kernel.clientcrypto.exception.ClientCryptoException; -import io.mosip.kernel.clientcrypto.service.spi.ClientCryptoService; -import io.mosip.kernel.core.crypto.spi.CryptoCoreSpec; -import io.mosip.kernel.core.exception.ExceptionUtils; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.CryptoUtil; -import io.mosip.kernel.keymanagerservice.logger.KeymanagerLogger; -import io.mosip.kernel.zkcryptoservice.constant.ZKCryptoManagerConstants; -import org.apache.commons.io.FileUtils; - -import javax.crypto.KeyGenerator; -import javax.crypto.SecretKey; -import javax.crypto.spec.SecretKeySpec; -import javax.validation.constraints.NotNull; -import java.io.*; -import java.net.InetAddress; -import java.nio.charset.StandardCharsets; -import java.nio.file.*; -import java.security.*; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.PKCS8EncodedKeySpec; -import java.security.spec.X509EncodedKeySpec; -import java.util.Arrays; -import java.util.Objects; - -/** - * This is TPM Fallback implementation, - * Note: This implementation must not be supported in PROD environments. - * - * @author Anusha Sunkada - * @since 1.1.2 - * - */ -class LocalClientCryptoServiceImpl implements ClientCryptoService { - - private static final Logger LOGGER = KeymanagerLogger.getLogger(LocalClientCryptoServiceImpl.class); - private static final String ALGORITHM = "RSA"; - private static final int KEY_LENGTH = 2048; - private static final String SIGN_ALGORITHM = "SHA256withRSA"; - private static final String PRIVATE_KEY = "reg.key"; - private static final String PUBLIC_KEY = "reg.pub"; - private static final String README = "readme.txt"; - - private static SecureRandom secureRandom = null; - protected static CryptoCoreSpec cryptoCore; - - - /** - * Creates RSA Key pair under user's home directory and the same is used for further - * crypto operations. - * @throws Throwable - */ - LocalClientCryptoServiceImpl(@NotNull CryptoCoreSpec cryptoCoreImpl) - throws Throwable { - LOGGER.info(ClientCryptoManagerConstant.SESSIONID, ClientCryptoManagerConstant.NON_TPM, - ClientCryptoManagerConstant.EMPTY, "Getting the instance of NON_TPM Security"); - - backwardCompatibilityFix(); - if(!doesKeysExists()) { - setupKeysDir(); - KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(ALGORITHM); - keyGenerator.initialize(KEY_LENGTH, new SecureRandom()); - KeyPair keypair = keyGenerator.generateKeyPair(); - createKeyFile(PRIVATE_KEY, keypair.getPrivate().getEncoded()); - createKeyFile(PUBLIC_KEY, keypair.getPublic().getEncoded()); - createReadMe(keypair.getPublic()); - - LOGGER.info(ClientCryptoManagerConstant.SESSIONID, ClientCryptoManagerConstant.NON_TPM, - ClientCryptoManagerConstant.EMPTY, "TPM NOT AVAILABLE - GENERATED NEW KEY PAIR SUCCESSFULLY."); - - } - LOGGER.info(ClientCryptoManagerConstant.SESSIONID, ClientCryptoManagerConstant.NON_TPM, - ClientCryptoManagerConstant.EMPTY, "Completed initializing Local Security Impl"); - - LOGGER.info(ClientCryptoManagerConstant.SESSIONID, ClientCryptoManagerConstant.NON_TPM, - ClientCryptoManagerConstant.EMPTY, "Check this file for publicKey and KeyIndex : " - + getKeysDirPath() + File.separator + README); - - //set cryptoCore - cryptoCore = cryptoCoreImpl; - } - - @Override - public byte[] signData(@NotNull byte[] dataToSign) throws ClientCryptoException { - try { - Signature sign = Signature.getInstance(SIGN_ALGORITHM); - sign.initSign(getPrivateKey()); - - try(ByteArrayInputStream in = new ByteArrayInputStream(dataToSign)) { - byte[] buffer = new byte[2048]; - int len = 0; - while((len = in.read(buffer)) != -1) { - sign.update(buffer, 0, len); - } - return sign.sign(); - } - } catch (Exception ex) { - throw new ClientCryptoException(ClientCryptoErrorConstants.CRYPTO_FAILED.getErrorCode(), - ClientCryptoErrorConstants.CRYPTO_FAILED.getErrorMessage(), ex); - } - } - - @Override - public boolean validateSignature(@NotNull byte[] signature, @NotNull byte[] actualData) - throws ClientCryptoException{ - try { - return validateSignature(getPublicKey(),signature, actualData); - } catch (Exception ex) { - throw new ClientCryptoException(ClientCryptoErrorConstants.CRYPTO_FAILED.getErrorCode(), - ClientCryptoErrorConstants.CRYPTO_FAILED.getErrorMessage(), ex); - } - } - - @Override - public byte[] asymmetricEncrypt(@NotNull byte[] dataToEncrypt) throws ClientCryptoException{ - try { - return cryptoCore.asymmetricEncrypt(getPublicKey(), dataToEncrypt); - } catch (Exception ex) { - throw new ClientCryptoException(ClientCryptoErrorConstants.CRYPTO_FAILED.getErrorCode(), - ClientCryptoErrorConstants.CRYPTO_FAILED.getErrorMessage(), ex); - } - } - - @Override - public byte[] asymmetricDecrypt(@NotNull byte[] dataToDecrypt) throws ClientCryptoException{ - try { - return cryptoCore.asymmetricDecrypt(getPrivateKey(), dataToDecrypt); - } catch (Exception ex) { - throw new ClientCryptoException(ClientCryptoErrorConstants.CRYPTO_FAILED.getErrorCode(), - ClientCryptoErrorConstants.CRYPTO_FAILED.getErrorMessage(), ex); - } - } - - @Override - public byte[] getSigningPublicPart() throws ClientCryptoException { - try { - return getPublicKey().getEncoded(); - } catch (Exception ex) { - throw new ClientCryptoException(ClientCryptoErrorConstants.CRYPTO_FAILED.getErrorCode(), - ClientCryptoErrorConstants.CRYPTO_FAILED.getErrorMessage(), ex); - } - } - - @Override - public void closeSecurityInstance() throws ClientCryptoException { - LOGGER.info(ClientCryptoManagerConstant.SESSIONID, ClientCryptoManagerConstant.NON_TPM, - ClientCryptoManagerConstant.EMPTY, "Nothing to do, as Local NON-TPM Security Impl is in use"); - } - - @Override - public boolean isTPMInstance() { - return false; - } - - public static byte[] generateRandomBytes(int length) { - if(secureRandom == null) - secureRandom = new SecureRandom(); - - byte[] bytes = new byte[length]; - secureRandom.nextBytes(bytes); - return bytes; - } - - @Override - public byte[] getEncryptionPublicPart() { - try { - return getPublicKey().getEncoded(); - } catch (Exception ex) { - throw new ClientCryptoException(ClientCryptoErrorConstants.CRYPTO_FAILED.getErrorCode(), - ClientCryptoErrorConstants.CRYPTO_FAILED.getErrorMessage(), ex); - } - } - - public static boolean validateSignature(@NotNull byte[] publicKey, @NotNull byte[] signature, @NotNull byte[] actualData) throws ClientCryptoException { - try { - X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey); - KeyFactory kf = KeyFactory.getInstance(ALGORITHM); - return validateSignature(kf.generatePublic(keySpec), signature, actualData); - } catch (Exception ex) { - throw new ClientCryptoException(ClientCryptoErrorConstants.CRYPTO_FAILED.getErrorCode(), - ClientCryptoErrorConstants.CRYPTO_FAILED.getErrorMessage(), ex); - } - } - - public static byte[] asymmetricEncrypt(byte[] publicKey, byte[] dataToEncrypt) throws ClientCryptoException { - LOGGER.info(ClientCryptoManagerConstant.SESSIONID, ClientCryptoManagerConstant.NON_TPM, - ClientCryptoManagerConstant.EMPTY, "LocalClientSecurity Asymmetric encrypt"); - try { - X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey); - KeyFactory kf = KeyFactory.getInstance(ALGORITHM); - return cryptoCore.asymmetricEncrypt(kf.generatePublic(keySpec), dataToEncrypt); - } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) { - throw new ClientCryptoException(ClientCryptoErrorConstants.CRYPTO_FAILED.getErrorCode(), - ClientCryptoErrorConstants.CRYPTO_FAILED.getErrorMessage(), ex); - } - } - - private static boolean validateSignature(PublicKey publicKey, byte[] signature, byte[] actualData) - throws ClientCryptoException { - try { - Signature sign = Signature.getInstance(SIGN_ALGORITHM); - sign.initVerify(publicKey); - - try(ByteArrayInputStream in = new ByteArrayInputStream(actualData)) { - byte[] buffer = new byte[2048]; - int len = 0; - - while((len = in.read(buffer)) != -1) { - sign.update(buffer, 0, len); - } - return sign.verify(signature); - } - } catch (Exception ex) { - throw new ClientCryptoException(ClientCryptoErrorConstants.CRYPTO_FAILED.getErrorCode(), - ClientCryptoErrorConstants.CRYPTO_FAILED.getErrorMessage(), ex); - } - } - - private void setupKeysDir() { - File keysDir = new File(getKeysDirPath()); - keysDir.mkdirs(); - } - - private boolean doesKeysExists() { - File keysDir = new File(getKeysDirPath()); - return (keysDir.exists() && Objects.requireNonNull(keysDir.list()).length >= 2); - } - - //Copy ${user.home}/.mosipkeys/db.conf to ${user.dir}/.mosipkeys/db.conf - private void backwardCompatibilityFix() { - Path targetPrivateKey = Paths.get(ClientCryptoManagerConstant.KEY_PATH, ClientCryptoManagerConstant.KEYS_DIR, PRIVATE_KEY); - if(targetPrivateKey.toFile().exists()) { - LOGGER.info("Backward compatibility fix not applicable"); - return; - } - - Path target = Paths.get(ClientCryptoManagerConstant.KEY_PATH, ClientCryptoManagerConstant.KEYS_DIR); - File existingKeysDir = new File(System.getProperty("user.home") + File.separator + ClientCryptoManagerConstant.KEYS_DIR); - if(existingKeysDir.exists() && Objects.requireNonNull(existingKeysDir.list()).length >= 2) { - try { - FileUtils.copyDirectory(existingKeysDir, target.toFile()); - LOGGER.info("Successfully performed backward compatible fix. Copied {} to {}", - existingKeysDir, target); - } catch (IOException e) { - LOGGER.error("Failed to perform backward compatible fix. Failed to copy {} to {} due to {}", - existingKeysDir, target, e); - } - } - } - - private String getKeysDirPath() { - return ClientCryptoManagerConstant.KEY_PATH + File.separator + ClientCryptoManagerConstant.KEYS_DIR; - } - - private void createKeyFile(String fileName, byte[] key) throws IOException { - try(FileOutputStream os = - new FileOutputStream(getKeysDirPath() + File.separator + fileName)) { - os.write(key); - } - } - - private PrivateKey getPrivateKey() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { - byte[] key = Files.readAllBytes(Paths.get(getKeysDirPath() + File.separator + PRIVATE_KEY)); - PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(key); - KeyFactory kf = KeyFactory.getInstance(ALGORITHM); - return kf.generatePrivate(keySpec); - } - - private PublicKey getPublicKey() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { - byte[] key = Files.readAllBytes(Paths.get(getKeysDirPath() + File.separator + PUBLIC_KEY)); - X509EncodedKeySpec keySpec = new X509EncodedKeySpec(key); - KeyFactory kf = KeyFactory.getInstance(ALGORITHM); - return kf.generatePublic(keySpec); - } - - - - private void createReadMe(PublicKey publicKey) throws IOException { - StringBuilder builder = new StringBuilder(); - builder.append("MachineName: "); - builder.append(InetAddress.getLocalHost().getHostName().toLowerCase()); - builder.append("\r\n"); - builder.append("PublicKey: "); - builder.append(CryptoUtil.encodeBase64String(publicKey.getEncoded())); - builder.append("\r\n"); - builder.append("KeyIndex: "); - builder.append(CryptoUtil.computeFingerPrint(publicKey.getEncoded(), null).toLowerCase()); - builder.append("\r\n"); - builder.append("Note : Use the above public key and client/machine name to create client machine using admin API"); - builder.append("\r\n"); - builder.append("Note : If the keys are lost/deleted, keys are regenerated on next instantiation of this instance. Corresponding client mappings need to be recreated once again."); - builder.append("\r\n"); - - Files.write(Paths.get(getKeysDirPath() + File.separator + README), - builder.toString().getBytes(StandardCharsets.UTF_8), - StandardOpenOption.CREATE); - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/service/impl/TPMClientCryptoServiceImpl.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/service/impl/TPMClientCryptoServiceImpl.java deleted file mode 100644 index ef31b5b1308..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/service/impl/TPMClientCryptoServiceImpl.java +++ /dev/null @@ -1,311 +0,0 @@ -package io.mosip.kernel.clientcrypto.service.impl; - -import io.mosip.kernel.clientcrypto.constant.ClientCryptoErrorConstants; -import io.mosip.kernel.clientcrypto.constant.ClientCryptoManagerConstant; -import io.mosip.kernel.clientcrypto.exception.ClientCryptoException; -import io.mosip.kernel.clientcrypto.service.spi.ClientCryptoService; - -import io.mosip.kernel.core.exception.ExceptionUtils; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.keymanagerservice.logger.KeymanagerLogger; -import org.junit.Assert; -import tss.*; -import tss.tpm.CreatePrimaryResponse; -import tss.tpm.*; - -import javax.crypto.KeyGenerator; -import javax.crypto.SecretKey; -import java.io.IOException; -import java.nio.charset.Charset; -import java.security.NoSuchAlgorithmException; -import java.time.LocalDateTime; -import java.time.temporal.ChronoUnit; - - -/** - * TPM is Strong and secure. - *

- * Strong - key is derived from true random source and large key space. - *

- * Secure - The private key material never leaves the TPM secure boundary in plain form. - * When a key leaves the TPM - in order to be loaded and used later - it is wrapped (encrypted) by its parent key. - * Keys, therefore, form a tree: each key is wrapped by its parent, all the way to the root of the tree, - * where the primary key is derived from a fixed seed. The seed is stored in the TPM's NVDATA, under a reserved index, - * and cannot be read externally. - *

- * The TPM stores keys on one of four hierarchies: * - * 1. Endorsement hierarchy. - * 2. Platform hierarchy. - * 3. Owner hierarchy, also known as storage hierarchy. - * 4. Null hierarchy. - *

- * A hierarchy is a logical collection of entities: keys and nv data blobs. Each hierarchy has a different seed and - * different authorization policy. Hierarchies differ by when their seeds are created and by who certifies their primary keys. - * Generally speaking, the endorsement hierarchy is reserved for objects created and certified by the TPM manufacturer. - * The endorsement seed (eseed) is randomly generated at manufacturing time and never changes during the lifetime of the device. - * The primary endorsement key is certified by the TPM manufacturer, and because its seed never changes, - * it can be used to identify the device. Since there's only one TPM device per machine, the primary endorsement key can - * also be used as the machine's identity - * - * Primary keys are derived from the primary seeds using a deterministic key derivation function (KDF). More accurately, - * the KDF takes as input the fixed seed and the key's template that describes its properties. - * - * - * @author Balaji Sridharan - * @author Anusha Sunkada - * @since 1.1.2 - */ -class TPMClientCryptoServiceImpl implements ClientCryptoService { - - private static final Logger LOGGER = KeymanagerLogger.getLogger(TPMClientCryptoServiceImpl.class); - private static final byte[] NULL_VECTOR = new byte[0]; - - //Zero terminated string - RSA encoding params - private static byte[] label = Helpers.concatenate(Charset.forName("UTF-8").encode(new String(NULL_VECTOR)).array(), - new byte[] { 0 }); - - //Note: TPM is single threaded - private static Tpm tpm; - private static CreatePrimaryResponse signingPrimaryResponse; - private static CreatePrimaryResponse encPrimaryResponse; - - TPMClientCryptoServiceImpl() throws Throwable { - LOGGER.debug(ClientCryptoManagerConstant.SESSIONID, ClientCryptoManagerConstant.TPM, - ClientCryptoManagerConstant.EMPTY, "TPMClientCryptoServiceImpl constructor invoked"); - - if (tpm == null) { - LOGGER.info(ClientCryptoManagerConstant.SESSIONID, ClientCryptoManagerConstant.TPM, - ClientCryptoManagerConstant.EMPTY, "Instantiating Platform TPM"); - - tpm = TpmFactory.platformTpm(); - if( !isKernelModeTRM() ) { //checks if its not connected to software TPM - LOGGER.warn(ClientCryptoManagerConstant.SESSIONID, ClientCryptoManagerConstant.TPM, - ClientCryptoManagerConstant.EMPTY, "UNABLE TO CONNECT TO KERNEL/SYSTEM TPM RESOURCE MANAGER"); - tpm = null; - } - - LOGGER.info(ClientCryptoManagerConstant.SESSIONID, ClientCryptoManagerConstant.TPM, - ClientCryptoManagerConstant.EMPTY, "Completed getting the instance of Platform TPM"); - } - } - - @Override - public byte[] signData(byte[] dataToSign) throws ClientCryptoException { - try { - Assert.assertNotNull(tpm); - CreatePrimaryResponse signingKey = createSigningKey(); - TPMU_SIGNATURE signedData = null; - synchronized(tpm) { - signedData = tpm.Sign(signingKey.handle, - TPMT_HA.fromHashOf(TPM_ALG_ID.SHA256, dataToSign).digest, new TPMS_NULL_SIG_SCHEME(), - TPMT_TK_HASHCHECK.nullTicket()); - } - Assert.assertNotNull(signedData); - LOGGER.info(ClientCryptoManagerConstant.SESSIONID, ClientCryptoManagerConstant.TPM, - ClientCryptoManagerConstant.EMPTY, "Completed Signing data using TPM"); - return ((TPMS_SIGNATURE_RSASSA) signedData).sig; - } catch (Exception ex) { - throw new ClientCryptoException(ClientCryptoErrorConstants.CRYPTO_FAILED.getErrorCode(), - ClientCryptoErrorConstants.CRYPTO_FAILED.getErrorMessage(), ex); - } - } - - @Override - public boolean validateSignature(byte[] signature, byte[] actualData) throws ClientCryptoException { - return validateSignature(getSigningPublicPart(), signature, actualData); - } - - @Override - public byte[] asymmetricEncrypt(byte[] plainData) throws ClientCryptoException{ - try { - CreatePrimaryResponse primaryResponse = createRSAKey(); - return asymmetricEncrypt(primaryResponse.outPublic.toTpm(), plainData); - } catch (Exception ex) { - throw new ClientCryptoException(ClientCryptoErrorConstants.CRYPTO_FAILED.getErrorCode(), - ClientCryptoErrorConstants.CRYPTO_FAILED.getErrorMessage(), ex); - } - } - - @Override - public byte[] asymmetricDecrypt(byte[] dataToDecrypt) throws ClientCryptoException{ - try { - Assert.assertNotNull(tpm); - CreatePrimaryResponse primaryResponse = createRSAKey(); - - synchronized (tpm) { - return tpm.RSA_Decrypt(primaryResponse.handle, dataToDecrypt, new TPMS_NULL_ASYM_SCHEME(), - label); - } - } catch (Exception ex) { - throw new ClientCryptoException(ClientCryptoErrorConstants.CRYPTO_FAILED.getErrorCode(), - ClientCryptoErrorConstants.CRYPTO_FAILED.getErrorMessage(), ex); - } - } - - @Override - public byte[] getSigningPublicPart() throws ClientCryptoException{ - try { - return createSigningKey().outPublic.toTpm(); - } catch (Exception ex) { - throw new ClientCryptoException(ClientCryptoErrorConstants.CRYPTO_FAILED.getErrorCode(), - ClientCryptoErrorConstants.CRYPTO_FAILED.getErrorMessage(), ex); - } - } - - @Override - public synchronized void closeSecurityInstance() { - try { - if (tpm != null) - tpm.close(); - } catch (IOException e) { - LOGGER.error(ClientCryptoManagerConstant.SESSIONID, ClientCryptoManagerConstant.TPM, - ClientCryptoManagerConstant.EMPTY, ExceptionUtils.getStackTrace(e)); - } - } - - /** - * single call can generate at most 48 bytes, - * the size of the largest hash digest implemented by the TPM (TPM2_ALG_SHA384 in this case) - * - * @param length - * @return - */ - public synchronized static byte[] generateRandomBytes(int length) { - return tpm.GetRandom(length); - } - - @Override - public byte[] getEncryptionPublicPart() { - try { - return createRSAKey().outPublic.toTpm(); - } catch (Exception ex) { - throw new ClientCryptoException(ClientCryptoErrorConstants.CRYPTO_FAILED.getErrorCode(), - ClientCryptoErrorConstants.CRYPTO_FAILED.getErrorMessage(), ex); - } - } - - - public static boolean validateSignature(byte[] publicKey, byte[] signature, byte[] actualData) - throws ClientCryptoException { - TPMT_PUBLIC tpmPublic = TPMT_PUBLIC.fromTpm(publicKey); - // Create Signature from signed data and algorithm - TPMU_SIGNATURE rsaSignature = new TPMS_SIGNATURE_RSASSA(TPM_ALG_ID.SHA256, signature); - // Validate the Signature using Public Template - return tpmPublic.validateSignature(actualData, rsaSignature); - } - - - public static byte[] asymmetricEncrypt(byte[] publicKey, byte[] dataToEncrypt) throws ClientCryptoException { - LOGGER.info(ClientCryptoManagerConstant.SESSIONID, ClientCryptoManagerConstant.TPM, - ClientCryptoManagerConstant.EMPTY, "TpmClientSecurity Asymmetric encrypt"); - TPMT_PUBLIC tpmPublic = TPMT_PUBLIC.fromTpm(publicKey); - return tpmPublic.encrypt(dataToEncrypt, new String(NULL_VECTOR)); - } - - @Override - public boolean isTPMInstance() { - return true; - } - - - /** - * Note: If either the seed or the template changes, a completely different primary key is created - * - * @return - */ - private CreatePrimaryResponse createSigningKey() { - LOGGER.info(ClientCryptoManagerConstant.SESSIONID, ClientCryptoManagerConstant.TPM, - ClientCryptoManagerConstant.EMPTY, "Creating the Key from Platform TPM"); - - if(signingPrimaryResponse != null) - return signingPrimaryResponse; - - TPMT_PUBLIC template = new TPMT_PUBLIC(TPM_ALG_ID.SHA1, - new TPMA_OBJECT(TPMA_OBJECT.fixedTPM, TPMA_OBJECT.fixedParent, TPMA_OBJECT.sign, - TPMA_OBJECT.sensitiveDataOrigin, TPMA_OBJECT.userWithAuth), - new byte[0], - new TPMS_RSA_PARMS(new TPMT_SYM_DEF_OBJECT(TPM_ALG_ID.NULL, 0, TPM_ALG_ID.NULL), - new TPMS_SIG_SCHEME_RSASSA(TPM_ALG_ID.SHA256), 2048, 65537), - new TPM2B_PUBLIC_KEY_RSA()); - TPM_HANDLE primaryHandle = TPM_HANDLE.from(TPM_RH.ENDORSEMENT); - TPMS_SENSITIVE_CREATE dataToBeSealedWithAuth = new TPMS_SENSITIVE_CREATE(NULL_VECTOR, NULL_VECTOR); - - synchronized (tpm) { - //everytime this is called key never changes until unless either seed / template change. - signingPrimaryResponse = tpm.CreatePrimary(primaryHandle, dataToBeSealedWithAuth, template, - NULL_VECTOR, new TPMS_PCR_SELECTION[0]); - } - - LOGGER.info(ClientCryptoManagerConstant.SESSIONID, ClientCryptoManagerConstant.TPM, - ClientCryptoManagerConstant.EMPTY, "Completed creating the Signing Key from Platform TPM"); - return signingPrimaryResponse; - } - - /** - * Note: If either the seed or the template changes, a completely different primary key is created - * @return - */ - private CreatePrimaryResponse createRSAKey() { - LOGGER.info(ClientCryptoManagerConstant.SESSIONID, ClientCryptoManagerConstant.TPM, - ClientCryptoManagerConstant.EMPTY, "Getting Asymmetric Key Creation from tpm"); - - if(encPrimaryResponse != null) - return encPrimaryResponse; - - LocalDateTime localDateTime = LocalDateTime.now(); - // This policy is a "standard" policy that is used with vendor-provided - // EKs - byte[] standardEKPolicy = new byte[] { (byte) 0x83, 0x71, (byte) 0x97, 0x67, 0x44, (byte) 0x84, (byte) 0xb3, - (byte) 0xf8, 0x1a, (byte) 0x90, (byte) 0xcc, (byte) 0x8d, 0x46, (byte) 0xa5, (byte) 0xd7, 0x24, - (byte) 0xfd, 0x52, (byte) 0xd7, 0x6e, 0x06, 0x52, 0x0b, 0x64, (byte) 0xf2, (byte) 0xa1, (byte) 0xda, - 0x1b, 0x33, 0x14, 0x69, (byte) 0xaa }; - - TPMT_PUBLIC template = new TPMT_PUBLIC(TPM_ALG_ID.SHA256, - new TPMA_OBJECT(TPMA_OBJECT.fixedTPM, TPMA_OBJECT.fixedParent, - TPMA_OBJECT.decrypt, TPMA_OBJECT.sensitiveDataOrigin, TPMA_OBJECT.userWithAuth), - standardEKPolicy, - new TPMS_RSA_PARMS(new TPMT_SYM_DEF_OBJECT(TPM_ALG_ID.NULL, 0, TPM_ALG_ID.NULL), - new TPMS_ENC_SCHEME_OAEP(TPM_ALG_ID.SHA256), 2048, 65537), - new TPM2B_PUBLIC_KEY_RSA()); - TPMS_SENSITIVE_CREATE dataToBeSealedWithAuth = new TPMS_SENSITIVE_CREATE(NULL_VECTOR, NULL_VECTOR); - TPM_HANDLE primaryHandle = TPM_HANDLE.from(TPM_RH.ENDORSEMENT); - - synchronized (tpm) { - encPrimaryResponse = tpm.CreatePrimary(primaryHandle, dataToBeSealedWithAuth, template, - null, null); - } - - long secondsTaken = localDateTime.until(LocalDateTime.now(), ChronoUnit.SECONDS); - LOGGER.info(ClientCryptoManagerConstant.SESSIONID, ClientCryptoManagerConstant.TPM, - ClientCryptoManagerConstant.EMPTY, - String.format("Completed Asymmetric Key Creation using tpm. Time taken is %s seconds", - String.valueOf(secondsTaken))); - return encPrimaryResponse; - } - - private static SecretKey getSecretKey() { - try { - KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); - keyGenerator.init(256); - return keyGenerator.generateKey(); - } catch (NoSuchAlgorithmException e) { - LOGGER.info(ClientCryptoManagerConstant.SESSIONID, ClientCryptoManagerConstant.TPM, - ClientCryptoManagerConstant.EMPTY, "Failed to generate secret key " + ExceptionUtils.getStackTrace(e)); - } - return null; - } - - /** - * check if connected to kernel/system mode TPM resource manager - * @return - */ - private boolean isKernelModeTRM() { - synchronized (tpm) { - if(tpm != null && tpm._getDevice() != null && - (tpm._getDevice() instanceof TpmDeviceTbs || tpm._getDevice() instanceof TpmDeviceLinux)) { - return true; - } - } - return false; - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/service/spi/ClientCryptoManagerService.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/service/spi/ClientCryptoManagerService.java deleted file mode 100644 index b5f400bc9a8..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/service/spi/ClientCryptoManagerService.java +++ /dev/null @@ -1,56 +0,0 @@ -package io.mosip.kernel.clientcrypto.service.spi; - -import io.mosip.kernel.clientcrypto.dto.*; - -/** - * - * @author Anusha Sunkada - * @since 1.1.2 - * - */ -public interface ClientCryptoManagerService { - - /** - * Signs with TPM private key - * @param tpmSignRequestDto - * @return TpmSignResponseDto - */ - public TpmSignResponseDto csSign(TpmSignRequestDto tpmSignRequestDto); - - /** - * Verify provided signature and data with TPM public key - * @param tpmSignVerifyRequestDto - * @return TpmSignVerifyResponseDto - */ - public TpmSignVerifyResponseDto csVerify(TpmSignVerifyRequestDto tpmSignVerifyRequestDto); - - - /** - * Encrypt data with TPM public key - * @param tpmCryptoRequestDto - * @return TpmCryptoResponseDto - */ - public TpmCryptoResponseDto csEncrypt(TpmCryptoRequestDto tpmCryptoRequestDto); - - /** - * Decrypts cipher with TPM private key - * @param tpmCryptoRequestDto - * @return TpmCryptoResponseDto - */ - public TpmCryptoResponseDto csDecrypt(TpmCryptoRequestDto tpmCryptoRequestDto); - - /** - * Returns TPM public key - * @param publicKeyRequestDto - * @return - */ - public PublicKeyResponseDto getSigningPublicKey(PublicKeyRequestDto publicKeyRequestDto); - - /** - * Returns TPM encryption public key - * @param publicKeyRequestDto - * @return - */ - public PublicKeyResponseDto getEncPublicKey(PublicKeyRequestDto publicKeyRequestDto); - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/service/spi/ClientCryptoService.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/service/spi/ClientCryptoService.java deleted file mode 100644 index 9f0eab8a740..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/clientcrypto/service/spi/ClientCryptoService.java +++ /dev/null @@ -1,74 +0,0 @@ -package io.mosip.kernel.clientcrypto.service.spi; - - -import io.mosip.kernel.clientcrypto.exception.ClientCryptoException; - -import javax.validation.constraints.NotNull; - -/** - * @author Anusha Sunkada - * @since 1.1.2 - */ -public interface ClientCryptoService { - - - /** - * Signs the input data by private key provided - * - * @param dataToSign plain data to be signed - * @return signature bytes - */ - byte[] signData(@NotNull byte[] dataToSign) throws ClientCryptoException; - - - /** - * Validates the signed data against the actual data using the public part of underlying security module - * - * @param signature - signature to verify against - * @param actualData - plain data - * @return true if successful signature verification - */ - boolean validateSignature(@NotNull byte[] signature, @NotNull byte[] actualData) - throws ClientCryptoException; - - /** - * Encrypts the input data - * - * @param plainData - plain data to encrypt - * @return encrypted data - */ - byte[] asymmetricEncrypt(@NotNull byte[] plainData) throws ClientCryptoException; - - /** - * Decrypts provided cipher text - * - * @param cipher - encrypted data - * @return plain data - */ - byte[] asymmetricDecrypt(@NotNull byte[] cipher) throws ClientCryptoException; - - /** - * - * - * @return public key as byte array - */ - byte[] getSigningPublicPart(); - - /** - * Closes underlying security implementation - */ - void closeSecurityInstance() throws ClientCryptoException; - - /** - * - * @return true if the implementation was specific to TPM - */ - boolean isTPMInstance(); - - /** - * - * @return public key as byte array - */ - byte[] getEncryptionPublicPart(); - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/crypto/jce/constant/SecurityExceptionCodeConstant.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/crypto/jce/constant/SecurityExceptionCodeConstant.java deleted file mode 100644 index fe09492bffa..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/crypto/jce/constant/SecurityExceptionCodeConstant.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * - * - * - * - * - * - * - * - */ - -package io.mosip.kernel.crypto.jce.constant; - -/** - * {@link Enum} for exception constants - * - * @author Urvil Joshi - * @since 1.0.0 - */ -public enum SecurityExceptionCodeConstant { - MOSIP_INVALID_KEY_EXCEPTION("KER-FSE-001", - "invalid Key (key is null or empty or has invalid encoding, wronglength, and uninitialized, etc)."), - MOSIP_INVALID_DATA_LENGTH_EXCEPTION("KER-FSE-002", "check input data length"), - MOSIP_INVALID_DATA_EXCEPTION("KER-FSE-003", "data not valid (currupted,length is not valid etc.)"), - MOSIP_INVALID_ENCRYPTED_DATA_CORRUPT_EXCEPTION("KER-FSE-004", "encrypted data is corrupted"), - MOSIP_INVALID_DATA_SIZE_EXCEPTION("KER-FSE-005", "ecrypted data size is not valid"), - MOSIP_NULL_DATA_EXCEPTION("KER-FSE-006", "data is null or length is 0"), - MOSIP_NULL_METHOD_EXCEPTION("KER-FSE-007", "mosip security method is null"), - MOSIP_NO_SUCH_ALGORITHM_EXCEPTION("KER-FSE-008", "no such algorithm"), - MOSIP_INVALID_PARAM_SPEC_EXCEPTION("KER-FSE-009", "invalid param spec"), - MOSIP_SIGNATURE_EXCEPTION("KER-FSE-010", "invalid signature, maybe null or empty"), - SALT_PROVIDED_IS_NULL_OR_EMPTY("KER-FSE-011", "salt provided is null or empty"); - - /** - * Constant {@link Enum} errorCode - */ - private final String errorCode; - - /** - * Getter for errorMessage - * - * @return get errorMessage value - */ - public String getErrorMessage() { - return errorMessage; - } - - /** - * Constant {@link Enum} errorMessage - */ - private final String errorMessage; - - /** - * Constructor for this class - * - * @param value set {@link Enum} value - */ - private SecurityExceptionCodeConstant(final String errorCode, final String errorMessage) { - this.errorCode = errorCode; - this.errorMessage = errorMessage; - } - - /** - * Getter for errorCode - * - * @return get errorCode value - */ - public String getErrorCode() { - return errorCode; - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/crypto/jce/core/CryptoCore.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/crypto/jce/core/CryptoCore.java deleted file mode 100644 index 4ebf30b9981..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/crypto/jce/core/CryptoCore.java +++ /dev/null @@ -1,548 +0,0 @@ -package io.mosip.kernel.crypto.jce.core; - -import java.math.BigInteger; -import java.security.InvalidAlgorithmParameterException; -import java.security.NoSuchProviderException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.cert.CertificateExpiredException; -import java.security.cert.CertificateNotYetValidException; -import java.security.cert.X509Certificate; -import java.security.interfaces.RSAPrivateKey; -import java.security.interfaces.RSAPublicKey; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.MGF1ParameterSpec; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Objects; - -import javax.annotation.PostConstruct; -import javax.crypto.BadPaddingException; -import javax.crypto.Cipher; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; -import javax.crypto.SecretKey; -import javax.crypto.SecretKeyFactory; -import javax.crypto.spec.GCMParameterSpec; -import javax.crypto.spec.OAEPParameterSpec; -import javax.crypto.spec.PBEKeySpec; -import javax.crypto.spec.PSource.PSpecified; -import javax.crypto.spec.SecretKeySpec; -import javax.xml.bind.DatatypeConverter; -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.jose4j.jws.JsonWebSignature; -import org.jose4j.jwx.CompactSerializer; -import org.jose4j.lang.JoseException; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; - -import io.mosip.kernel.core.crypto.exception.InvalidDataException; -import io.mosip.kernel.core.crypto.exception.InvalidKeyException; -import io.mosip.kernel.core.crypto.exception.InvalidParamSpecException; -import io.mosip.kernel.core.crypto.exception.SignatureException; -import io.mosip.kernel.core.crypto.spi.CryptoCoreSpec; -import io.mosip.kernel.core.exception.NoSuchAlgorithmException; -import io.mosip.kernel.core.util.CryptoUtil; -import io.mosip.kernel.core.util.EmptyCheckUtils; -import io.mosip.kernel.crypto.jce.constant.SecurityExceptionCodeConstant; -import io.mosip.kernel.crypto.jce.util.CryptoUtils; - -/** - * This class provided Basic and Core Cryptographic functionalities . - * - * This class follows {@link CryptoCoreSpec} and implement all basic - * Cryptographic functions. - * - * @author Urvil Joshi - * @author Rajath - * @since 1.0.0 - * - * @see CryptoCoreSpec - * @see PrivateKey - * @see PublicKey - * @see SecretKey - * @see Cipher - * @see GCMParameterSpec - * @see SecureRandom - */ -//Code optimization remaining (Code Dupe) -@Component -public class CryptoCore implements CryptoCoreSpec { - - private static final String PERIOD_SEPARATOR_REGEX = "\\."; - - // Used as a hack for softhsm oeap padding decryption usecase will be when we - // will use in HSM - private static final String RSA_ECB_NO_PADDING = "RSA/ECB/NoPadding"; - - private static final String PKCS11_STORE_TYPE = "PKCS11"; - - @Value("${mosip.kernel.keygenerator.asymmetric-key-length:2048}") - private int asymmetricKeyLength; - - private static final String MGF1 = "MGF1"; - - private static final String HASH_ALGO = "SHA-256"; - - private static final String AES = "AES"; - - @Value("${mosip.kernel.crypto.gcm-tag-length:128}") - private int tagLength; - - @Value("${mosip.kernel.crypto.symmetric-algorithm-name:AES/GCM/PKCS5Padding}") - private String symmetricAlgorithm; - - @Value("${mosip.kernel.crypto.asymmetric-algorithm-name:RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING}") - private String asymmetricAlgorithm; - - @Value("${mosip.kernel.crypto.hash-algorithm-name:PBKDF2WithHmacSHA512}") - private String passwordAlgorithm; - - @Value("${mosip.kernel.crypto.sign-algorithm-name:RS256}") - private String signAlgorithm; - - @Value("${mosip.kernel.crypto.hash-symmetric-key-length:256}") - private int symmetricKeyLength; - - @Value("${mosip.kernel.crypto.hash-iteration:100000}") - private int iterations; - - @Value("${mosip.kernel.keymanager.hsm.keystore-type:PKCS11}") - private String keystoreType; - - private SecureRandom secureRandom; - - @PostConstruct - public void init() { - secureRandom = new SecureRandom(); - } - - @Override - public byte[] symmetricEncrypt(SecretKey key, byte[] data, byte[] aad) { - Objects.requireNonNull(key, SecurityExceptionCodeConstant.MOSIP_INVALID_KEY_EXCEPTION.getErrorMessage()); - CryptoUtils.verifyData(data); - Cipher cipher; - try { - cipher = Cipher.getInstance(symmetricAlgorithm); - } catch (java.security.NoSuchAlgorithmException | NoSuchPaddingException e) { - throw new NoSuchAlgorithmException( - SecurityExceptionCodeConstant.MOSIP_NO_SUCH_ALGORITHM_EXCEPTION.getErrorCode(), - SecurityExceptionCodeConstant.MOSIP_NO_SUCH_ALGORITHM_EXCEPTION.getErrorMessage(), e); - } - byte[] output = null; - byte[] randomIV = generateIV(cipher.getBlockSize()); - try { - SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), AES); - GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(tagLength, randomIV); - cipher.init(Cipher.ENCRYPT_MODE, keySpec, gcmParameterSpec); - output = new byte[cipher.getOutputSize(data.length) + cipher.getBlockSize()]; - if (aad != null && aad.length != 0) { - cipher.updateAAD(aad); - } - byte[] processData = doFinal(data, cipher); - System.arraycopy(processData, 0, output, 0, processData.length); - System.arraycopy(randomIV, 0, output, processData.length, randomIV.length); - } catch (java.security.InvalidKeyException e) { - throw new InvalidKeyException(SecurityExceptionCodeConstant.MOSIP_INVALID_KEY_EXCEPTION.getErrorCode(), - SecurityExceptionCodeConstant.MOSIP_INVALID_KEY_EXCEPTION.getErrorMessage(), e); - } catch (InvalidAlgorithmParameterException e) { - throw new InvalidKeyException( - SecurityExceptionCodeConstant.MOSIP_INVALID_PARAM_SPEC_EXCEPTION.getErrorCode(), - SecurityExceptionCodeConstant.MOSIP_INVALID_PARAM_SPEC_EXCEPTION.getErrorMessage(), e); - } - return output; - } - - @Override - public byte[] symmetricEncrypt(SecretKey key, byte[] data, byte[] iv, byte[] aad) { - Objects.requireNonNull(key, SecurityExceptionCodeConstant.MOSIP_INVALID_KEY_EXCEPTION.getErrorMessage()); - CryptoUtils.verifyData(data); - if (iv == null) { - return symmetricEncrypt(key, data, aad); - } - Cipher cipher; - try { - cipher = Cipher.getInstance(symmetricAlgorithm); - } catch (java.security.NoSuchAlgorithmException | NoSuchPaddingException e) { - throw new NoSuchAlgorithmException( - SecurityExceptionCodeConstant.MOSIP_NO_SUCH_ALGORITHM_EXCEPTION.getErrorCode(), - SecurityExceptionCodeConstant.MOSIP_NO_SUCH_ALGORITHM_EXCEPTION.getErrorMessage(), e); - } - try { - SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), AES); - GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(tagLength, iv); - cipher.init(Cipher.ENCRYPT_MODE, keySpec, gcmParameterSpec); - if (aad != null && aad.length != 0) { - cipher.updateAAD(aad); - } - return doFinal(data, cipher); - } catch (java.security.InvalidKeyException e) { - throw new InvalidKeyException(SecurityExceptionCodeConstant.MOSIP_INVALID_KEY_EXCEPTION.getErrorCode(), - SecurityExceptionCodeConstant.MOSIP_INVALID_KEY_EXCEPTION.getErrorMessage(), e); - } catch (InvalidAlgorithmParameterException e) { - throw new InvalidParamSpecException( - SecurityExceptionCodeConstant.MOSIP_INVALID_PARAM_SPEC_EXCEPTION.getErrorCode(), - SecurityExceptionCodeConstant.MOSIP_INVALID_PARAM_SPEC_EXCEPTION.getErrorMessage(), e); - } - } - - @Override - public byte[] symmetricDecrypt(SecretKey key, byte[] data, byte[] aad) { - Objects.requireNonNull(key, SecurityExceptionCodeConstant.MOSIP_INVALID_KEY_EXCEPTION.getErrorMessage()); - CryptoUtils.verifyData(data); - Cipher cipher; - try { - cipher = Cipher.getInstance(symmetricAlgorithm); - } catch (java.security.NoSuchAlgorithmException | NoSuchPaddingException e) { - throw new NoSuchAlgorithmException( - SecurityExceptionCodeConstant.MOSIP_NO_SUCH_ALGORITHM_EXCEPTION.getErrorCode(), - SecurityExceptionCodeConstant.MOSIP_NO_SUCH_ALGORITHM_EXCEPTION.getErrorMessage(), e); - } - byte[] output = null; - try { - byte[] randomIV = Arrays.copyOfRange(data, data.length - cipher.getBlockSize(), data.length); - SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), AES); - GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(tagLength, randomIV); - cipher.init(Cipher.DECRYPT_MODE, keySpec, gcmParameterSpec); - if (aad != null && aad.length != 0) { - cipher.updateAAD(aad); - } - output = doFinal(Arrays.copyOf(data, data.length - cipher.getBlockSize()), cipher); - } catch (java.security.InvalidKeyException e) { - throw new InvalidKeyException(SecurityExceptionCodeConstant.MOSIP_INVALID_KEY_EXCEPTION.getErrorCode(), - SecurityExceptionCodeConstant.MOSIP_INVALID_KEY_EXCEPTION.getErrorMessage(), e); - } catch (InvalidAlgorithmParameterException e) { - throw new InvalidKeyException( - SecurityExceptionCodeConstant.MOSIP_INVALID_PARAM_SPEC_EXCEPTION.getErrorCode(), - SecurityExceptionCodeConstant.MOSIP_INVALID_PARAM_SPEC_EXCEPTION.getErrorMessage(), e); - } catch (ArrayIndexOutOfBoundsException e) { - throw new InvalidDataException( - SecurityExceptionCodeConstant.MOSIP_INVALID_DATA_LENGTH_EXCEPTION.getErrorCode(), - SecurityExceptionCodeConstant.MOSIP_INVALID_DATA_LENGTH_EXCEPTION.getErrorMessage(), e); - } - return output; - } - - @Override - public byte[] symmetricDecrypt(SecretKey key, byte[] data, byte[] iv, byte[] aad) { - Objects.requireNonNull(key, SecurityExceptionCodeConstant.MOSIP_INVALID_KEY_EXCEPTION.getErrorMessage()); - CryptoUtils.verifyData(data); - if (iv == null) { - return symmetricDecrypt(key, data, aad); - } - Cipher cipher; - try { - cipher = Cipher.getInstance(symmetricAlgorithm); - } catch (java.security.NoSuchAlgorithmException | NoSuchPaddingException e) { - throw new NoSuchAlgorithmException( - SecurityExceptionCodeConstant.MOSIP_NO_SUCH_ALGORITHM_EXCEPTION.getErrorCode(), - SecurityExceptionCodeConstant.MOSIP_NO_SUCH_ALGORITHM_EXCEPTION.getErrorMessage(), e); - } - try { - SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), AES); - GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(tagLength, iv); - cipher.init(Cipher.DECRYPT_MODE, keySpec, gcmParameterSpec); - if (aad != null) { - cipher.updateAAD(aad); - } - return doFinal(data, cipher); - } catch (java.security.InvalidKeyException e) { - throw new InvalidKeyException(SecurityExceptionCodeConstant.MOSIP_INVALID_KEY_EXCEPTION.getErrorCode(), - SecurityExceptionCodeConstant.MOSIP_INVALID_KEY_EXCEPTION.getErrorMessage(), e); - } catch (InvalidAlgorithmParameterException e) { - throw new InvalidParamSpecException( - SecurityExceptionCodeConstant.MOSIP_INVALID_PARAM_SPEC_EXCEPTION.getErrorCode(), - SecurityExceptionCodeConstant.MOSIP_INVALID_PARAM_SPEC_EXCEPTION.getErrorMessage(), e); - } - } - - @Override - public byte[] asymmetricEncrypt(PublicKey key, byte[] data) { - Objects.requireNonNull(key, SecurityExceptionCodeConstant.MOSIP_INVALID_KEY_EXCEPTION.getErrorMessage()); - CryptoUtils.verifyData(data); - Cipher cipher; - try { - cipher = Cipher.getInstance(asymmetricAlgorithm); - } catch (java.security.NoSuchAlgorithmException | NoSuchPaddingException e) { - throw new NoSuchAlgorithmException( - SecurityExceptionCodeConstant.MOSIP_NO_SUCH_ALGORITHM_EXCEPTION.getErrorCode(), - SecurityExceptionCodeConstant.MOSIP_NO_SUCH_ALGORITHM_EXCEPTION.getErrorMessage(), e); - } - final OAEPParameterSpec oaepParams = new OAEPParameterSpec(HASH_ALGO, MGF1, MGF1ParameterSpec.SHA256, - PSpecified.DEFAULT); - try { - cipher.init(Cipher.ENCRYPT_MODE, key, oaepParams); - } catch (java.security.InvalidKeyException e) { - throw new InvalidKeyException(SecurityExceptionCodeConstant.MOSIP_INVALID_KEY_EXCEPTION.getErrorCode(), - e.getMessage(), 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); - } - - @Override - public byte[] asymmetricDecrypt(PrivateKey privateKey, byte[] data) { - if (PKCS11_STORE_TYPE.equalsIgnoreCase(keystoreType)) { - BigInteger keyModulus = ((RSAPrivateKey) privateKey).getModulus(); - return asymmetricDecrypt(privateKey, keyModulus, data, null); - } - return jceAsymmetricDecrypt(privateKey, data, null); - } - - @Override - public byte[] asymmetricDecrypt(PrivateKey privateKey, PublicKey publicKey, byte[] data) { - if (PKCS11_STORE_TYPE.equalsIgnoreCase(keystoreType)) { - BigInteger keyModulus = Objects.nonNull(publicKey) ? ((RSAPublicKey) publicKey).getModulus() : - ((RSAPrivateKey) privateKey).getModulus(); - return asymmetricDecrypt(privateKey, keyModulus, data, null); - } - return jceAsymmetricDecrypt(privateKey, data, null); - } - - @Override - public byte[] asymmetricDecrypt(PrivateKey privateKey, PublicKey publicKey, byte[] data, String storeType) { - if (PKCS11_STORE_TYPE.equalsIgnoreCase(keystoreType)) { - BigInteger keyModulus = Objects.nonNull(publicKey) ? ((RSAPublicKey) publicKey).getModulus() : - ((RSAPrivateKey) privateKey).getModulus(); - return asymmetricDecrypt(privateKey, keyModulus, data, storeType); - } - return jceAsymmetricDecrypt(privateKey, data, storeType); - } - - private byte[] asymmetricDecrypt(PrivateKey privateKey, BigInteger keyModulus, byte[] data, String storeType) { - 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) : - Cipher.getInstance(RSA_ECB_NO_PADDING, storeType); - } catch (java.security.NoSuchAlgorithmException | NoSuchPaddingException | NoSuchProviderException e) { - throw new NoSuchAlgorithmException( - SecurityExceptionCodeConstant.MOSIP_NO_SUCH_ALGORITHM_EXCEPTION.getErrorCode(), - SecurityExceptionCodeConstant.MOSIP_NO_SUCH_ALGORITHM_EXCEPTION.getErrorMessage(), e); - } - - try { - cipher.init(Cipher.DECRYPT_MODE, privateKey); - } catch (java.security.InvalidKeyException e) { - throw new InvalidKeyException(SecurityExceptionCodeConstant.MOSIP_INVALID_KEY_EXCEPTION.getErrorCode(), - e.getMessage(), 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 - */ - private byte[] unpadOAEPPadding(byte[] paddedPlainText, BigInteger keyModulus) { - - 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 new InvalidKeyException(SecurityExceptionCodeConstant.MOSIP_INVALID_KEY_EXCEPTION - .getErrorCode(), e.getMessage(), e); - } - } - - private byte[] jceAsymmetricDecrypt(PrivateKey privateKey, byte[] data, String storeType){ - 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 (java.security.NoSuchAlgorithmException | NoSuchPaddingException | NoSuchProviderException e) { - throw new NoSuchAlgorithmException( - SecurityExceptionCodeConstant.MOSIP_NO_SUCH_ALGORITHM_EXCEPTION.getErrorCode(), - SecurityExceptionCodeConstant.MOSIP_NO_SUCH_ALGORITHM_EXCEPTION.getErrorMessage(), e); - } catch (java.security.InvalidKeyException e) { - throw new InvalidKeyException(SecurityExceptionCodeConstant.MOSIP_INVALID_KEY_EXCEPTION.getErrorCode(), - e.getMessage(), e); - } catch (InvalidAlgorithmParameterException e) { - throw new InvalidParamSpecException( - SecurityExceptionCodeConstant.MOSIP_INVALID_PARAM_SPEC_EXCEPTION.getErrorCode(), - SecurityExceptionCodeConstant.MOSIP_INVALID_PARAM_SPEC_EXCEPTION.getErrorMessage(), e); - } - } - - - @Override - public String hash(byte[] data, byte[] salt) { - CryptoUtils.verifyData(data); - CryptoUtils.verifyData(salt, SecurityExceptionCodeConstant.SALT_PROVIDED_IS_NULL_OR_EMPTY.getErrorCode(), - SecurityExceptionCodeConstant.SALT_PROVIDED_IS_NULL_OR_EMPTY.getErrorMessage()); - SecretKeyFactory secretKeyFactory; - char[] convertedData = new String(data).toCharArray(); - PBEKeySpec pbeKeySpec = new PBEKeySpec(convertedData, salt, iterations, symmetricKeyLength); - SecretKey key; - try { - secretKeyFactory = SecretKeyFactory.getInstance(passwordAlgorithm); - key = secretKeyFactory.generateSecret(pbeKeySpec); - } catch (InvalidKeySpecException e) { - throw new InvalidParamSpecException( - SecurityExceptionCodeConstant.MOSIP_INVALID_PARAM_SPEC_EXCEPTION.getErrorCode(), e.getMessage(), e); - } catch (java.security.NoSuchAlgorithmException e) { - throw new NoSuchAlgorithmException( - SecurityExceptionCodeConstant.MOSIP_NO_SUCH_ALGORITHM_EXCEPTION.getErrorCode(), - SecurityExceptionCodeConstant.MOSIP_NO_SUCH_ALGORITHM_EXCEPTION.getErrorMessage(), e); - } - return DatatypeConverter.printHexBinary(key.getEncoded()); - } - - @Override - public String sign(byte[] data, PrivateKey privateKey) { - Objects.requireNonNull(privateKey, SecurityExceptionCodeConstant.MOSIP_INVALID_KEY_EXCEPTION.getErrorMessage()); - CryptoUtils.verifyData(data); - JsonWebSignature jws = new JsonWebSignature(); - jws.setPayloadBytes(data); - jws.setAlgorithmHeaderValue(signAlgorithm); - jws.setKey(privateKey); - jws.setDoKeyValidation(false); - try { - return jws.getDetachedContentCompactSerialization(); - } catch (JoseException e) { - throw new SignatureException(SecurityExceptionCodeConstant.MOSIP_SIGNATURE_EXCEPTION.getErrorCode(), - e.getMessage(), e); - } - } - - @Override - public boolean verifySignature(byte[] data, String sign, PublicKey publicKey) { - if (EmptyCheckUtils.isNullEmpty(sign)) { - throw new SignatureException(SecurityExceptionCodeConstant.MOSIP_SIGNATURE_EXCEPTION.getErrorCode(), - SecurityExceptionCodeConstant.MOSIP_SIGNATURE_EXCEPTION.getErrorMessage()); - } - Objects.requireNonNull(publicKey, SecurityExceptionCodeConstant.MOSIP_INVALID_KEY_EXCEPTION.getErrorMessage()); - CryptoUtils.verifyData(data); - JsonWebSignature jws = new JsonWebSignature(); - try { - String[] parts = sign.split(PERIOD_SEPARATOR_REGEX); - parts[1] = CryptoUtil.encodeBase64(data); - jws.setCompactSerialization(CompactSerializer.serialize(parts)); - jws.setKey(publicKey); - return jws.verifySignature(); - } catch (ArrayIndexOutOfBoundsException | JoseException e) { - throw new SignatureException(SecurityExceptionCodeConstant.MOSIP_SIGNATURE_EXCEPTION.getErrorCode(), - e.getMessage(), e); - } - - } - - @SuppressWarnings("unchecked") - @Override - public SecureRandom random() { - return secureRandom; - } - - /** - * Generator for IV(Initialisation Vector) - * - * @param blockSize blocksize of current cipher - * @return generated IV - */ - private byte[] generateIV(int blockSize) { - byte[] byteIV = new byte[blockSize]; - secureRandom.nextBytes(byteIV); - return byteIV; - } - - private byte[] doFinal(byte[] data, Cipher cipher) { - try { - return cipher.doFinal(data); - } catch (IllegalBlockSizeException e) { - throw new InvalidDataException( - SecurityExceptionCodeConstant.MOSIP_INVALID_DATA_SIZE_EXCEPTION.getErrorCode(), e.getMessage(), e); - } catch (BadPaddingException e) { - throw new InvalidDataException( - SecurityExceptionCodeConstant.MOSIP_INVALID_ENCRYPTED_DATA_CORRUPT_EXCEPTION.getErrorCode(), - e.getMessage(), e); - } - } - - /* - * This two methods here are for temporary, Unit test for this will be written - * in next versions - */ - @Override - public String sign(byte[] data, PrivateKey privateKey, X509Certificate x509Certificate) { - Objects.requireNonNull(privateKey, SecurityExceptionCodeConstant.MOSIP_INVALID_KEY_EXCEPTION.getErrorMessage()); - CryptoUtils.verifyData(data); - JsonWebSignature jws = new JsonWebSignature(); - List certList = new ArrayList<>(); - certList.add(x509Certificate); - X509Certificate[] certArray = certList.toArray(new X509Certificate[] {}); - jws.setCertificateChainHeaderValue(certArray); - jws.setPayloadBytes(data); - jws.setAlgorithmHeaderValue(signAlgorithm); - jws.setKey(privateKey); - jws.setDoKeyValidation(false); - try { - return jws.getCompactSerialization(); - } catch (JoseException e) { - throw new SignatureException(SecurityExceptionCodeConstant.MOSIP_SIGNATURE_EXCEPTION.getErrorCode(), - e.getMessage(), e); - } - } - - /* - * This two methods here are for temporary, Unit test for this will be written - * in next versions - */ - @Override - public boolean verifySignature(String sign) { - if (EmptyCheckUtils.isNullEmpty(sign)) { - throw new SignatureException(SecurityExceptionCodeConstant.MOSIP_SIGNATURE_EXCEPTION.getErrorCode(), - SecurityExceptionCodeConstant.MOSIP_SIGNATURE_EXCEPTION.getErrorMessage()); - } - JsonWebSignature jws = new JsonWebSignature(); - try { - jws.setCompactSerialization(sign); - List certificateChainHeaderValue = jws.getCertificateChainHeaderValue(); - X509Certificate certificate = certificateChainHeaderValue.get(0); - certificate.checkValidity(); - PublicKey publicKey = certificate.getPublicKey(); - jws.setKey(publicKey); - return jws.verifySignature(); - } catch (JoseException | CertificateExpiredException | CertificateNotYetValidException e) { - throw new SignatureException(SecurityExceptionCodeConstant.MOSIP_SIGNATURE_EXCEPTION.getErrorCode(), - e.getMessage(), e); - } - - } - - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/crypto/jce/core/JwsFactory.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/crypto/jce/core/JwsFactory.java deleted file mode 100644 index 2e183815c47..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/crypto/jce/core/JwsFactory.java +++ /dev/null @@ -1,15 +0,0 @@ -package io.mosip.kernel.crypto.jce.core; - -import java.security.PrivateKey; -import java.security.cert.X509Certificate; - -import io.mosip.kernel.core.crypto.spi.JwsSpec; -import io.mosip.kernel.crypto.jce.util.JWSValidation; - -public class JwsFactory { - - public JwsSpec getJWS() { - return new JWSValidation(); - } - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/crypto/jce/util/CryptoUtils.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/crypto/jce/util/CryptoUtils.java deleted file mode 100644 index 274df5ad1e3..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/crypto/jce/util/CryptoUtils.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * - * - * - * - * - */ -package io.mosip.kernel.crypto.jce.util; - -import io.mosip.kernel.core.crypto.exception.InvalidDataException; -import io.mosip.kernel.core.crypto.exception.NullDataException; -import io.mosip.kernel.crypto.jce.constant.SecurityExceptionCodeConstant; - -/** - * Utility class for crypto - * - * @author Urvil Joshi - * @since 1.0.0 - */ -public class CryptoUtils { - - /** - * Constructor for this class - */ - private CryptoUtils() { - - } - - /** - * Verify if data is null or empty - * - * @param - * - * @param data data provided by user - */ - public static void verifyData(byte[] data) { - if (data == null) { - throw new NullDataException(SecurityExceptionCodeConstant.MOSIP_NULL_DATA_EXCEPTION.getErrorCode(), - SecurityExceptionCodeConstant.MOSIP_NULL_DATA_EXCEPTION.getErrorMessage()); - } else if (data.length == 0) { - throw new InvalidDataException(SecurityExceptionCodeConstant.MOSIP_NULL_DATA_EXCEPTION.getErrorCode(), - SecurityExceptionCodeConstant.MOSIP_NULL_DATA_EXCEPTION.getErrorMessage()); - } - } - - /** - * Verify if data is null or empty - * - * @param data data provided by user - */ - public static void verifyData(byte[] data, String errorCode, String message) { - if (data == null) { - throw new NullDataException(errorCode, message); - } else if (data.length == 0) { - throw new InvalidDataException(errorCode, message); - } - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/crypto/jce/util/JWSValidation.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/crypto/jce/util/JWSValidation.java deleted file mode 100644 index e651f6d3197..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/crypto/jce/util/JWSValidation.java +++ /dev/null @@ -1,86 +0,0 @@ -package io.mosip.kernel.crypto.jce.util; - -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.List; - -import org.jose4j.jws.AlgorithmIdentifiers; -import org.jose4j.jws.JsonWebSignature; -import org.jose4j.lang.JoseException; -import org.springframework.stereotype.Component; - -import io.mosip.kernel.core.crypto.spi.CryptoCoreSpec; -import io.mosip.kernel.core.crypto.spi.JwsSpec; - -/** - * - * @author M1037717 This class will verify and sign the JWT - * - * @deprecated(This class is deprecated from version 1.0.5, Please use - * {@link CryptoCoreSpec#sign(Object, Object)} and - * {@link CryptoCoreSpec#verifySignature(Object, Object, Object)} - * instead of these methods) - * - */ -@Deprecated -@Component -public class JWSValidation implements JwsSpec { - - /** The public key. */ - protected PublicKey publicKey; - - /** - * - * @param pKey - * @param certificate - * @param payload - * @return signature - * @throws JoseException - */ - @Override - public String jwsSign(String payload, PrivateKey pKey, X509Certificate certificate) { - try { - JsonWebSignature jws = new JsonWebSignature(); - List certList = new ArrayList<>(); - certList.add(certificate); - X509Certificate[] certArray = certList.toArray(new X509Certificate[] {}); - jws.setCertificateChainHeaderValue(certArray); - jws.setPayload(payload); - jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256); - jws.setKey(pKey); - jws.setDoKeyValidation(false); - return jws.getCompactSerialization(); - } catch (JoseException e) { - e.printStackTrace(); - } - return null; - } - - /** - * - * @param sign - * @return boolean - */ - @Override - public boolean verifySignature(String sign) { - try { - JsonWebSignature jws = new JsonWebSignature(); - jws.setCompactSerialization(sign); - List certificateChainHeaderValue = jws.getCertificateChainHeaderValue(); - X509Certificate certificate = certificateChainHeaderValue.get(0); - certificate.checkValidity(); - publicKey = certificate.getPublicKey(); - // certificate.verify(publicKey); - jws.setKey(publicKey); - return jws.verifySignature(); - } catch (CertificateException | JoseException e) { - e.printStackTrace(); - } - return false; - - } - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/constant/CryptomanagerConstant.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/constant/CryptomanagerConstant.java deleted file mode 100644 index fc81a3a6fd4..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/constant/CryptomanagerConstant.java +++ /dev/null @@ -1,43 +0,0 @@ -package io.mosip.kernel.cryptomanager.constant; - -/** - * Constant class for Crypto-Manager-Service - * - * @author Urvil Joshi - * - * @since 1.0.0 - */ -public class CryptomanagerConstant { - /** - * Private Constructor for this class - */ - private CryptomanagerConstant() { - - } - - public static final String WHITESPACE = " "; - public static final String INVALID_REQUEST = "should not be null or empty"; - public static final String EMPTY_ATTRIBUTE = "should not be empty"; - public static final String EMPTY_REGEX = ".+\\S.*"; - - public static final String SESSIONID = "CryptoManagerSession"; - - public static final String ENCRYPT = "CryptoManagerEncrypt"; - - public static final String DECRYPT = "CryptoManagerDecrypt"; - - public static final int THUMBPRINT_LENGTH = 32; - - public static final int ENCRYPTED_SESSION_KEY_LENGTH = 256; - - public static final byte[] VERSION_RSA_2048 = "VER_R2".getBytes(); - - public static final int GCM_AAD_LENGTH = 32; - - public static final int GCM_NONCE_LENGTH = 12; - - public static final String ENCRYPT_PIN = "CryptoManagerEncryptWithPin"; - - public static final String DECRYPT_PIN = "CryptoManagerDecryptWithPin"; -} - diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/constant/CryptomanagerErrorCode.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/constant/CryptomanagerErrorCode.java deleted file mode 100644 index 101d98fefd8..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/constant/CryptomanagerErrorCode.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * - * - * - * - */ -package io.mosip.kernel.cryptomanager.constant; - -/** - * Error Constants for Crypto-Manager-Service - * - * @author Urvil Joshi - * @since 1.0.0 - * - */ -public enum CryptomanagerErrorCode { - /** - * - */ - NO_SUCH_ALGORITHM_EXCEPTION("KER-CRY-001", "No Such algorithm is supported"), - /** - * - */ - INVALID_SPEC_PUBLIC_KEY("KER-CRY-002", "public key is invalid"), - /** - * - */ - INVALID_DATA_WITHOUT_KEY_BREAKER("KER-CRY-003", "data sent to decrypt is without key splitter or invalid"), - /** - * - */ - INVALID_DATA("KER-CRY-003", " or not base64 encoded"), - /** - * - */ - INVALID_REQUEST("KER-CRY-004", "should not be null or empty"), - /** - * - */ - CANNOT_CONNECT_TO_KEYMANAGER_SERVICE("KER-CRY-005", "cannot connect to keymanager service or response is null"), - /** - * - */ - KEYMANAGER_SERVICE_ERROR("KER-CRY-006", "Keymanager Service has replied with following error"), - /** - * - */ - RESPONSE_PARSE_ERROR("KER-CRY-008", "Error occur while parsing response "), - /** - * - */ - DATE_TIME_PARSE_EXCEPTION("KER-CRY-007", "timestamp should be in ISO 8601 format yyyy-MM-ddTHH::mm:ss.SZ"), - /** - * - */ - HEX_DATA_PARSE_EXCEPTION("KER-CRY-009", "Invalid Hex Data"), - - CERTIFICATE_THUMBPRINT_ERROR("KER-CRY-010", "Error in generating Certificate Thumbprint."), - - ENCRYPT_NOT_ALLOWED_ERROR("KER-CRY-011", "Not Allowed to preform encryption with Master Key. Use Base to encrypt data."), - - INTERNAL_SERVER_ERROR("KER-CRY-500", "Internal server error"); - - - - /** - * The errorCode - */ - private final String errorCode; - /** - * The errorMessage - */ - private final String errorMessage; - - /** - * {@link CryptomanagerErrorCode} constructor - * - * @param errorCode error code - * @param errorMessage error message - */ - private CryptomanagerErrorCode(final String errorCode, final String errorMessage) { - this.errorCode = errorCode; - this.errorMessage = errorMessage; - } - - /** - * Getter for errorCode - * - * @return errorCode - */ - public String getErrorCode() { - return errorCode; - } - - /** - * Getter for errorMessage - * - * @return errorMessage - */ - public String getErrorMessage() { - return errorMessage; - } - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/controller/CryptomanagerController.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/controller/CryptomanagerController.java deleted file mode 100644 index 607bb18f89e..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/controller/CryptomanagerController.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * - * - * - * - */ -package io.mosip.kernel.cryptomanager.controller; - -import javax.validation.Valid; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.CrossOrigin; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RestController; - -import io.mosip.kernel.core.http.RequestWrapper; -import io.mosip.kernel.core.http.ResponseFilter; -import io.mosip.kernel.core.http.ResponseWrapper; -import io.mosip.kernel.cryptomanager.dto.CryptoWithPinRequestDto; -import io.mosip.kernel.cryptomanager.dto.CryptoWithPinResponseDto; -import io.mosip.kernel.cryptomanager.dto.CryptomanagerRequestDto; -import io.mosip.kernel.cryptomanager.dto.CryptomanagerResponseDto; -import io.mosip.kernel.cryptomanager.service.CryptomanagerService; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiParam; - -/** - * Rest Controller for Crypto-Manager-Service - * - * @author Urvil Joshi - * @author Srinivasan - * - * @since 1.0.0 - */ -@CrossOrigin -@RestController -@Api(value = "Operation related to Encryption and Decryption", tags = { "cryptomanager" }) -public class CryptomanagerController { - - /** - * {@link CryptomanagerService} instance - */ - @Autowired - private CryptomanagerService cryptomanagerService; - - /** - * Controller for Encrypt the data - * - * @param cryptomanagerRequestDto {@link CryptomanagerRequestDto} request - * @return {@link CryptomanagerResponseDto} encrypted Data - */ - @PreAuthorize("hasAnyRole('ZONAL_ADMIN','GLOBAL_ADMIN','INDIVIDUAL','ID_AUTHENTICATION','TEST', 'REGISTRATION_ADMIN', 'REGISTRATION_SUPERVISOR', 'REGISTRATION_OFFICER', 'REGISTRATION_PROCESSOR','PRE_REGISTRATION_ADMIN','RESIDENT')") - @ResponseFilter - @PostMapping(value = "/encrypt", produces = "application/json") - public ResponseWrapper encrypt( - @ApiParam("Salt and Data to encrypt in BASE64 encoding with meta-data") @RequestBody @Valid RequestWrapper cryptomanagerRequestDto) { - ResponseWrapper response = new ResponseWrapper<>(); - response.setResponse(cryptomanagerService.encrypt(cryptomanagerRequestDto.getRequest())); - return response; - } - - /** - * Controller for Decrypt the data - * - * @param cryptomanagerRequestDto {@link CryptomanagerRequestDto} request - * @return {@link CryptomanagerResponseDto} decrypted Data - */ - @PreAuthorize("hasAnyRole('ZONAL_ADMIN','GLOBAL_ADMIN','INDIVIDUAL','ID_AUTHENTICATION', 'TEST', 'REGISTRATION_ADMIN', 'REGISTRATION_SUPERVISOR', 'REGISTRATION_OFFICER', 'REGISTRATION_PROCESSOR','PRE_REGISTRATION_ADMIN','RESIDENT')") - @ResponseFilter - @PostMapping(value = "/decrypt", produces = "application/json") - public ResponseWrapper decrypt( - @ApiParam("Salt and Data to decrypt in BASE64 encoding with meta-data") @RequestBody @Valid RequestWrapper cryptomanagerRequestDto) { - ResponseWrapper response = new ResponseWrapper<>(); - response.setResponse(cryptomanagerService.decrypt(cryptomanagerRequestDto.getRequest())); - return response; - } - - /** - * Controller for Encrypt the data Using Pin - * - * @param requestDto {@link CryptoWithPinRequestDto} request - * @return {@link CryptoWithPinResponseDto} encrypted Data - */ - @PreAuthorize("hasAnyRole('ZONAL_ADMIN','GLOBAL_ADMIN','INDIVIDUAL','ID_AUTHENTICATION','TEST', 'REGISTRATION_ADMIN', 'REGISTRATION_SUPERVISOR', 'REGISTRATION_OFFICER', 'REGISTRATION_PROCESSOR','PRE_REGISTRATION_ADMIN','RESIDENT')") - @ResponseFilter - @PostMapping(value = "/encryptWithPin", produces = "application/json") - public ResponseWrapper encryptWithPin( - @ApiParam("Pin and Data to encrypt") @RequestBody @Valid RequestWrapper requestDto) { - ResponseWrapper responseDto = new ResponseWrapper<>(); - responseDto.setResponse(cryptomanagerService.encryptWithPin(requestDto.getRequest())); - return responseDto; - } - - /** - * Controller for Decrypt the data Using Pin - * - * @param requestDto {@link CryptoWithPinRequestDto} request - * @return {@link CryptoWithPinResponseDto} decrypted Data - */ - @PreAuthorize("hasAnyRole('ZONAL_ADMIN','GLOBAL_ADMIN','INDIVIDUAL','ID_AUTHENTICATION', 'TEST', 'REGISTRATION_ADMIN', 'REGISTRATION_SUPERVISOR', 'REGISTRATION_OFFICER', 'REGISTRATION_PROCESSOR','PRE_REGISTRATION_ADMIN','RESIDENT')") - @ResponseFilter - @PostMapping(value = "/decryptWithPin", produces = "application/json") - public ResponseWrapper decryptWithPin( - @ApiParam("Pin and Data to decrypt") @RequestBody @Valid RequestWrapper requestDto) { - ResponseWrapper responseDto = new ResponseWrapper<>(); - responseDto.setResponse(cryptomanagerService.decryptWithPin(requestDto.getRequest())); - return responseDto; - } - - /** - * Controller for Encrypt the data & encrypt hash of the data with same session key. - * - * @param cryptomanagerRequestDto {@link CryptomanagerRequestDto} request - * @return {@link CryptomanagerResponseDto} encrypted Data - */ - @PreAuthorize("hasAnyRole('ZONAL_ADMIN','GLOBAL_ADMIN','INDIVIDUAL','ID_AUTHENTICATION','TEST', 'REGISTRATION_ADMIN', 'REGISTRATION_SUPERVISOR', 'REGISTRATION_OFFICER', 'REGISTRATION_PROCESSOR','PRE_REGISTRATION_ADMIN','RESIDENT')") - @ResponseFilter - @PostMapping(value = "/encryptDt", produces = "application/json") - public ResponseWrapper encryptDt( - @ApiParam("Salt and Data to encrypt in BASE64 encoding with meta-data") @RequestBody @Valid RequestWrapper cryptomanagerRequestDto) { - ResponseWrapper response = new ResponseWrapper<>(); - response.setResponse(cryptomanagerService.encrypt(cryptomanagerRequestDto.getRequest())); - return response; - } - - /** - * Controller for Decrypt the data and data hash. Compares the decrypted hash and hash of decrypted data if hash matches data will be returned otherwise throws exception. - * - * @param cryptomanagerRequestDto {@link CryptomanagerRequestDto} request - * @return {@link CryptomanagerResponseDto} decrypted Data - */ - @PreAuthorize("hasAnyRole('ZONAL_ADMIN','GLOBAL_ADMIN','INDIVIDUAL','ID_AUTHENTICATION', 'TEST', 'REGISTRATION_ADMIN', 'REGISTRATION_SUPERVISOR', 'REGISTRATION_OFFICER', 'REGISTRATION_PROCESSOR','PRE_REGISTRATION_ADMIN','RESIDENT')") - @ResponseFilter - @PostMapping(value = "/decryptDt", produces = "application/json") - public ResponseWrapper decryptDt( - @ApiParam("Salt and Data to decrypt in BASE64 encoding with meta-data") @RequestBody @Valid RequestWrapper cryptomanagerRequestDto) { - ResponseWrapper response = new ResponseWrapper<>(); - response.setResponse(cryptomanagerService.decrypt(cryptomanagerRequestDto.getRequest())); - return response; - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/dto/CryptoWithPinRequestDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/dto/CryptoWithPinRequestDto.java deleted file mode 100644 index ed0a72a1cfd..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/dto/CryptoWithPinRequestDto.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * - * - * - * - */ -package io.mosip.kernel.cryptomanager.dto; - -import javax.validation.constraints.NotBlank; - -import io.mosip.kernel.cryptomanager.constant.CryptomanagerConstant; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * Crypto-With-Pin-Request model - * - * @author Mahammed Taheer - * - * @since 1.1.2 - */ -@Data -@AllArgsConstructor -@NoArgsConstructor -@ApiModel(description = "Model representing a Crypto-With-Pin-Service Request") -public class CryptoWithPinRequestDto { - - /** - * Data in String to encrypt/decrypt - */ - - @ApiModelProperty(notes = "Data in String to encrypt/decrypt", required = true) - @NotBlank(message = CryptomanagerConstant.INVALID_REQUEST) - private String data; - - /** - * Pin to be used for encrypt/decrypt - */ - @ApiModelProperty(notes = " Pin to be used for encrypt/decrypt", required = true, example = "A1234") - @NotBlank(message = CryptomanagerConstant.INVALID_REQUEST) - private String userPin; -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/dto/CryptoWithPinResponseDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/dto/CryptoWithPinResponseDto.java deleted file mode 100644 index 360c79796b7..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/dto/CryptoWithPinResponseDto.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * - * - * - * - */ -package io.mosip.kernel.cryptomanager.dto; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * Crypto-With-Pin-Response model - * - * @author Mahammed Taheer - * - * @since 1.1.2 - */ -@Data -@AllArgsConstructor -@NoArgsConstructor -@ApiModel(description = "Model representing a Crypto-With-Pin-Response Response") -public class CryptoWithPinResponseDto { - /** - * Data Encrypted/Decrypted in String - */ - @ApiModelProperty(notes = "Data encrypted/decrypted in String") - private String data; -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/dto/CryptomanagerRequestDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/dto/CryptomanagerRequestDto.java deleted file mode 100644 index bc93870dde4..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/dto/CryptomanagerRequestDto.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * - * - * - * - */ -package io.mosip.kernel.cryptomanager.dto; - -import java.time.LocalDateTime; - -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Pattern; - -import com.fasterxml.jackson.annotation.JsonFormat; - -import io.mosip.kernel.cryptomanager.constant.CryptomanagerConstant; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * Crypto-Manager-Request model - * - * @author Urvil Joshi - * - * @since 1.0.0 - */ -@Data -@AllArgsConstructor -@NoArgsConstructor -@ApiModel(description = "Model representing a Crypto-Manager-Service Request") -public class CryptomanagerRequestDto { - /** - * Application id of decrypting module - */ - @ApiModelProperty(notes = "Application id of decrypting module", example = "REGISTRATION", required = true) - @NotBlank(message = CryptomanagerConstant.INVALID_REQUEST) - private String applicationId; - /** - * Refrence Id - */ - @ApiModelProperty(notes = "Refrence Id", example = "REF01") - private String referenceId; - /** - * Timestamp - */ - @ApiModelProperty(notes = "Timestamp as metadata", example = "2018-12-10T06:12:52.994Z", required = true) - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") - @NotNull - private LocalDateTime timeStamp; - /** - * Data in BASE64 encoding to encrypt/decrypt - */ - @ApiModelProperty(notes = "Data in BASE64 encoding to encrypt/decrypt", required = true) - @NotBlank(message = CryptomanagerConstant.INVALID_REQUEST) - private String data; - /** - * Salt to be passed as IV - */ - @Pattern(regexp = CryptomanagerConstant.EMPTY_REGEX, message = CryptomanagerConstant.EMPTY_ATTRIBUTE) - @ApiModelProperty(notes = " Base64 Encoded Salt to be send as IV", example = "YiGFRjiV7WMFIscV") - private String salt; - - /** - * AAD to be passed - */ - @Pattern(regexp = CryptomanagerConstant.EMPTY_REGEX, message = CryptomanagerConstant.EMPTY_ATTRIBUTE) - @ApiModelProperty(notes = " Base64 Encoded AAD(Advance Authentication Data)", example = "pfxeERQk57XJBJ9JF0oBAtrTzofhAPw54HnJtwW36l4=") - private String aad; - - /** - * flag to prepend certificate thumbprint, default to true. - */ - @ApiModelProperty(notes = "flag to prepend certificate thumbprint to encrypted data.", example = "false", required = false) - @Deprecated - private Boolean prependThumbprint; - - @Override - public String toString() { - return "CryptomanagerRequestDto [applicationId=" + applicationId + ", referenceId=" + referenceId - + ", timeStamp=" + timeStamp + ", salt=" + salt + "]"; - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/dto/CryptomanagerResponseDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/dto/CryptomanagerResponseDto.java deleted file mode 100644 index 21b3a315821..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/dto/CryptomanagerResponseDto.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * - * - * - * - */ -package io.mosip.kernel.cryptomanager.dto; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * Crypto-Manager-Response model - * - * @author Urvil Joshi - * - * @since 1.0.0 - */ -@Data -@AllArgsConstructor -@NoArgsConstructor -@ApiModel(description = "Model representing a Crypto-Manager-Service Response") -public class CryptomanagerResponseDto { - /** - * Data Encrypted/Decrypted in BASE64 encoding - */ - @ApiModelProperty(notes = "Data encrypted/decrypted in BASE64 encoding") - private String data; -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/dto/KeymanagerPublicKeyResponseDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/dto/KeymanagerPublicKeyResponseDto.java deleted file mode 100644 index 87d556bec73..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/dto/KeymanagerPublicKeyResponseDto.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * - * - * - * - */ -package io.mosip.kernel.cryptomanager.dto; - -import java.time.LocalDateTime; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * Key-Manager-Service get-public-key response model - * - * @author Urvil Joshi - * - * @since 1.0.0 - */ -@Data -@AllArgsConstructor -@NoArgsConstructor -public class KeymanagerPublicKeyResponseDto { - - /** - * Public key in BASE64 encodeding - */ - private String publicKey; - - /** - * Timestamp of issuance - */ - private LocalDateTime issuedAt; - - /** - * Timestamp of expiry - */ - private LocalDateTime expiryAt; - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/dto/KeymanagerSymmetricKeyRequestDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/dto/KeymanagerSymmetricKeyRequestDto.java deleted file mode 100644 index 3cee6f7f0dc..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/dto/KeymanagerSymmetricKeyRequestDto.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * - * - * - * - */ -package io.mosip.kernel.cryptomanager.dto; - -import java.time.LocalDateTime; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * Key-Manager-Service decrypt-symmetric-key request model - * - * @author Urvil Joshi - * - * @since 1.0.0 - */ -@Data -@AllArgsConstructor -@NoArgsConstructor -public class KeymanagerSymmetricKeyRequestDto { - - /** - * Application Id - */ - private String applicationId; - - /** - * Timestamp as metadata - */ - private LocalDateTime timeStamp; - - /** - * Refrence Id - */ - private String referenceId; - - /** - * Encrypted Symmetric key - */ - private String encryptedSymmetricKey; -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/dto/KeymanagerSymmetricKeyResponseDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/dto/KeymanagerSymmetricKeyResponseDto.java deleted file mode 100644 index 0c70070f56f..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/dto/KeymanagerSymmetricKeyResponseDto.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * - * - * - * - */ -package io.mosip.kernel.cryptomanager.dto; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * Key-Manager-Service decrypt-symmetric-key response model - * - * @author Urvil Joshi - * - * @since 1.0.0 - */ -@Data -@AllArgsConstructor -@NoArgsConstructor -public class KeymanagerSymmetricKeyResponseDto { - - /** - * Decrypted Symmetric key - */ - private String symmetricKey; -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/dto/PublicKeyResponse.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/dto/PublicKeyResponse.java deleted file mode 100644 index de589c6ba9c..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/dto/PublicKeyResponse.java +++ /dev/null @@ -1,53 +0,0 @@ -package io.mosip.kernel.cryptomanager.dto; - -import java.time.LocalDateTime; - -import com.fasterxml.jackson.annotation.JsonFormat; -import com.fasterxml.jackson.annotation.JsonIgnore; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * Response class for Public Key - * - * @author Dharmesh Khandelwal - * @since 1.0.0 - * - */ -@Data -@AllArgsConstructor -@NoArgsConstructor -@ApiModel(description = "Class representing a Public Key Response") -public class PublicKeyResponse { - - /** - * The string alias - */ - @JsonIgnore - private String alias; - - /** - * Field for public key - */ - @ApiModelProperty(notes = "Public key in BASE64 encoding format", required = true) - private String publicKey; - - /** - * Key creation time - */ - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") - @ApiModelProperty(notes = "Timestamp of issuance of public key", required = true) - private LocalDateTime issuedAt; - - /** - * Key expiry time - */ - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") - @ApiModelProperty(notes = "Timestamp of expiry of public key", required = true) - private LocalDateTime expiryAt; - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/exception/CryptoManagerSerivceException.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/exception/CryptoManagerSerivceException.java deleted file mode 100644 index 219ded58701..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/exception/CryptoManagerSerivceException.java +++ /dev/null @@ -1,39 +0,0 @@ -package io.mosip.kernel.cryptomanager.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; - -/** - * The Class CryptoManagerSerivceException. - * - * @author Srinivasan - * @since 1.0.0 - */ -public class CryptoManagerSerivceException extends BaseUncheckedException { - - /** The Constant serialVersionUID. */ - private static final long serialVersionUID = -5916223368862935708L; - - /** - * Instantiates a new crypto manager serivce exception. - * - * @param errorCode the error code - * @param errorMessage the error message - * @param rootCause the root cause - */ - public CryptoManagerSerivceException(String errorCode, String errorMessage, Throwable rootCause) { - super(errorCode, errorMessage, rootCause); - - } - - /** - * Instantiates a new crypto manager serivce exception. - * - * @param errorCode the error code - * @param errorMessage the error message - */ - public CryptoManagerSerivceException(String errorCode, String errorMessage) { - super(errorCode, errorMessage); - - } - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/exception/KeymanagerServiceException.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/exception/KeymanagerServiceException.java deleted file mode 100644 index 9f0c0029bf8..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/exception/KeymanagerServiceException.java +++ /dev/null @@ -1,34 +0,0 @@ -package io.mosip.kernel.cryptomanager.exception; - -import java.util.List; - -import io.mosip.kernel.core.exception.BaseUncheckedException; -import io.mosip.kernel.core.exception.ServiceError; - -public class KeymanagerServiceException extends BaseUncheckedException { - /** - * Serializable version ID. - */ - private static final long serialVersionUID = 8152409863253682472L; - - /** - * This variable holds the MosipErrors list. - */ - private final List list; - - /** - * @param list The error list. - */ - public KeymanagerServiceException(List list) { - this.list = list; - } - - /** - * Getter for error list. - * - * @return The error list. - */ - public List getList() { - return list; - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/exception/ParseResponseException.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/exception/ParseResponseException.java deleted file mode 100644 index bb3ca20110b..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/exception/ParseResponseException.java +++ /dev/null @@ -1,22 +0,0 @@ -package io.mosip.kernel.cryptomanager.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; - -public class ParseResponseException extends BaseUncheckedException { - - /** - * - */ - private static final long serialVersionUID = 3383837827871687253L; - - public ParseResponseException(String errorCode, String errorMessage, Throwable rootCause) { - super(errorCode, errorMessage, rootCause); - - } - - public ParseResponseException(String errorCode, String errorMessage) { - super(errorCode, errorMessage); - - } - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/service/CryptomanagerService.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/service/CryptomanagerService.java deleted file mode 100644 index 7c89006b62c..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/service/CryptomanagerService.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * - * - * - * - */ -package io.mosip.kernel.cryptomanager.service; - -import org.springframework.stereotype.Service; - -import io.mosip.kernel.cryptomanager.dto.CryptoWithPinRequestDto; -import io.mosip.kernel.cryptomanager.dto.CryptoWithPinResponseDto; -import io.mosip.kernel.cryptomanager.dto.CryptomanagerRequestDto; -import io.mosip.kernel.cryptomanager.dto.CryptomanagerResponseDto; - -/** - * This interface provides the methods which can be used for Encryption and - * Decryption. - * - * @author Urvil Joshi - * @author Srinivasan - * @since 1.0.0 - */ -@Service -public interface CryptomanagerService { - - /** - * Encrypt the data requested with metadata. - * - * @param cryptoRequestDto {@link CryptomanagerRequestDto} instance - * @return encrypted data - */ - public CryptomanagerResponseDto encrypt(CryptomanagerRequestDto cryptoRequestDto); - - /** - * Decrypt data requested with metadata. - * - * @param cryptoRequestDto {@link CryptomanagerRequestDto} instance - * @return decrypted data - */ - public CryptomanagerResponseDto decrypt(CryptomanagerRequestDto cryptoRequestDto); - - /** - * Encrypt the data requested with metadata. - * - * @param requestDto {@link CryptoWithPinRequestDto} instance - * @return encrypted data - */ - public CryptoWithPinResponseDto encryptWithPin(CryptoWithPinRequestDto requestDto); - - /** - * Decrypt data requested with metadata. - * - * @param requestDto {@link CryptoWithPinRequestDto} instance - * @return decrypted data - */ - public CryptoWithPinResponseDto decryptWithPin(CryptoWithPinRequestDto requestDto); -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/service/impl/CryptomanagerServiceImpl.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/service/impl/CryptomanagerServiceImpl.java deleted file mode 100644 index 62fe7beadc8..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/service/impl/CryptomanagerServiceImpl.java +++ /dev/null @@ -1,298 +0,0 @@ -/* - * - * - * - * - */ -package io.mosip.kernel.cryptomanager.service.impl; - -import static java.util.Arrays.copyOfRange; - -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.cert.Certificate; -import java.util.Arrays; - -import javax.crypto.SecretKey; -import javax.crypto.spec.SecretKeySpec; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Service; - -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.crypto.spi.CryptoCoreSpec; -import io.mosip.kernel.core.util.CryptoUtil; -import io.mosip.kernel.cryptomanager.constant.CryptomanagerConstant; -import io.mosip.kernel.cryptomanager.constant.CryptomanagerErrorCode; -import io.mosip.kernel.cryptomanager.dto.CryptoWithPinRequestDto; -import io.mosip.kernel.cryptomanager.dto.CryptoWithPinResponseDto; -import io.mosip.kernel.cryptomanager.dto.CryptomanagerRequestDto; -import io.mosip.kernel.cryptomanager.dto.CryptomanagerResponseDto; -import io.mosip.kernel.cryptomanager.exception.CryptoManagerSerivceException; -import io.mosip.kernel.cryptomanager.service.CryptomanagerService; -import io.mosip.kernel.cryptomanager.util.CryptomanagerUtils; -import io.mosip.kernel.keygenerator.bouncycastle.KeyGenerator; -import io.mosip.kernel.keymanagerservice.logger.KeymanagerLogger; - -/** - * Service Implementation for {@link CryptomanagerService} interface - * - * @author Urvil Joshi - * @author Srinivasan - * - * @since 1.0.0 - */ -@Service -public class CryptomanagerServiceImpl implements CryptomanagerService { - - private static final int GCM_NONCE_LENGTH = 12; - - private static final int PBE_SALT_LENGTH = 32; - - private static final String AES_KEY_TYPE = "AES"; - - private static final Logger LOGGER = KeymanagerLogger.getLogger(CryptomanagerServiceImpl.class); - - /** - * KeySplitter for splitting key and data - */ - @Value("${mosip.kernel.data-key-splitter}") - private String keySplitter; - - /** The 1.1.3 no thumbprint support flag. */ - @Value("${mosip.kernel.keymanager.113nothumbprint.support:false}") - private boolean noThumbprint; - - @Value("${mosip.sign-certificate-refid:SIGN}") - private String signRefId; - - /** The sign applicationid. */ - @Value("${mosip.sign.applicationid:KERNEL}") - private String signApplicationId; - - /** - * {@link KeyGenerator} instance - */ - @Autowired - KeyGenerator keyGenerator; - - /** - * {@link CryptomanagerUtils} instance - */ - @Autowired - CryptomanagerUtils cryptomanagerUtil; - - /** - * {@link CryptoCoreSpec} instance for cryptographic functionalities. - */ - @Autowired - private CryptoCoreSpec cryptoCore; - - /* - * (non-Javadoc) - * - * @see - * io.mosip.kernel.cryptography.service.CryptographyService#encrypt(io.mosip. - * kernel.cryptography.dto.CryptographyRequestDto) - */ - @Override - public CryptomanagerResponseDto encrypt(CryptomanagerRequestDto cryptoRequestDto) { - LOGGER.info(CryptomanagerConstant.SESSIONID, CryptomanagerConstant.ENCRYPT, CryptomanagerConstant.ENCRYPT, - "Request for data encryption."); - - if(!cryptomanagerUtil.isDataValid(cryptoRequestDto.getReferenceId()) || - (cryptoRequestDto.getApplicationId().equalsIgnoreCase(signApplicationId) && - cryptoRequestDto.getReferenceId().equalsIgnoreCase(signRefId))) { - LOGGER.error(CryptomanagerConstant.SESSIONID, CryptomanagerConstant.ENCRYPT, CryptomanagerConstant.ENCRYPT, - "Not Allowed to preform encryption with Master Key."); - throw new CryptoManagerSerivceException(CryptomanagerErrorCode.ENCRYPT_NOT_ALLOWED_ERROR.getErrorCode(), - CryptomanagerErrorCode.ENCRYPT_NOT_ALLOWED_ERROR.getErrorMessage()); - } - - SecretKey secretKey = keyGenerator.getSymmetricKey(); - final byte[] encryptedData; - byte[] headerBytes = new byte[0]; - if (cryptomanagerUtil.isValidSalt(CryptomanagerUtils.nullOrTrim(cryptoRequestDto.getSalt()))) { - encryptedData = cryptoCore.symmetricEncrypt(secretKey, CryptoUtil.decodeBase64(cryptoRequestDto.getData()), - CryptoUtil.decodeBase64(CryptomanagerUtils.nullOrTrim(cryptoRequestDto.getSalt())), - CryptoUtil.decodeBase64(CryptomanagerUtils.nullOrTrim(cryptoRequestDto.getAad()))); - } else { - byte[] aad = CryptoUtil.decodeBase64(CryptomanagerUtils.nullOrTrim(cryptoRequestDto.getAad())); - if (aad == null || aad.length == 0){ - encryptedData = generateAadAndEncryptData(secretKey, cryptoRequestDto.getData()); - headerBytes = CryptomanagerConstant.VERSION_RSA_2048; - } else { - encryptedData = cryptoCore.symmetricEncrypt(secretKey, CryptoUtil.decodeBase64(cryptoRequestDto.getData()), - aad); - } - } - - Certificate certificate = cryptomanagerUtil.getCertificate(cryptoRequestDto); - LOGGER.info(CryptomanagerConstant.SESSIONID, CryptomanagerConstant.ENCRYPT, CryptomanagerConstant.ENCRYPT, - "Found the cerificate, proceeding with session key encryption."); - PublicKey publicKey = certificate.getPublicKey(); - final byte[] encryptedSymmetricKey = cryptoCore.asymmetricEncrypt(publicKey, secretKey.getEncoded()); - LOGGER.info(CryptomanagerConstant.SESSIONID, CryptomanagerConstant.ENCRYPT, CryptomanagerConstant.ENCRYPT, - "Session key encryption completed."); - boolean prependThumbprint = cryptoRequestDto.getPrependThumbprint() == null ? false : cryptoRequestDto.getPrependThumbprint(); - CryptomanagerResponseDto cryptoResponseDto = new CryptomanagerResponseDto(); - // support of 1.1.3 no thumbprint is configured as true & encryption request with no thumbprint - // request thumbprint flag will not be considered if support no thumbprint is set to false. - if (noThumbprint && !prependThumbprint) { - byte[] finalEncKeyBytes = cryptomanagerUtil.concatByteArrays(headerBytes, encryptedSymmetricKey); - cryptoResponseDto.setData(CryptoUtil.encodeBase64(CryptoUtil.combineByteArray(encryptedData, finalEncKeyBytes, keySplitter))); - return cryptoResponseDto; - } - byte[] certThumbprint = cryptomanagerUtil.getCertificateThumbprint(certificate); - byte[] concatedData = cryptomanagerUtil.concatCertThumbprint(certThumbprint, encryptedSymmetricKey); - byte[] finalEncKeyBytes = cryptomanagerUtil.concatByteArrays(headerBytes, concatedData); - cryptoResponseDto.setData(CryptoUtil.encodeBase64(CryptoUtil.combineByteArray(encryptedData, - finalEncKeyBytes, keySplitter))); - return cryptoResponseDto; - } - - private byte[] generateAadAndEncryptData(SecretKey secretKey, String data){ - LOGGER.info(CryptomanagerConstant.SESSIONID, CryptomanagerConstant.ENCRYPT, CryptomanagerConstant.ENCRYPT, - "Provided AAD value is null or empty byte array. So generating random 32 bytes for AAD."); - byte[] aad = cryptomanagerUtil.generateRandomBytes(CryptomanagerConstant.GCM_AAD_LENGTH); - byte[] nonce = copyOfRange(aad, 0, CryptomanagerConstant.GCM_NONCE_LENGTH); - byte[] encData = cryptoCore.symmetricEncrypt(secretKey, CryptoUtil.decodeBase64(data), - nonce, aad); - return cryptomanagerUtil.concatByteArrays(aad, encData); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.kernel.cryptography.service.CryptographyService#decrypt(io.mosip. - * kernel.cryptography.dto.CryptographyRequestDto) - */ - @Override - public CryptomanagerResponseDto decrypt(CryptomanagerRequestDto cryptoRequestDto) { - LOGGER.info(CryptomanagerConstant.SESSIONID, CryptomanagerConstant.DECRYPT, CryptomanagerConstant.DECRYPT, - "Request for data decryption."); - - int keyDemiliterIndex = 0; - byte[] encryptedHybridData = CryptoUtil.decodeBase64(cryptoRequestDto.getData()); - keyDemiliterIndex = CryptoUtil.getSplitterIndex(encryptedHybridData, keyDemiliterIndex, keySplitter); - byte[] encryptedKey = copyOfRange(encryptedHybridData, 0, keyDemiliterIndex); - byte[] encryptedData = copyOfRange(encryptedHybridData, keyDemiliterIndex + keySplitter.length(), - encryptedHybridData.length); - - byte[] headerBytes = cryptomanagerUtil.parseEncryptKeyHeader(encryptedKey); - cryptoRequestDto.setData(CryptoUtil.encodeBase64(copyOfRange(encryptedKey, headerBytes.length, encryptedKey.length))); - SecretKey decryptedSymmetricKey = cryptomanagerUtil.getDecryptedSymmetricKey(cryptoRequestDto); - LOGGER.info(CryptomanagerConstant.SESSIONID, CryptomanagerConstant.DECRYPT, CryptomanagerConstant.DECRYPT, - "Session Decryption completed."); - final byte[] decryptedData; - if (cryptomanagerUtil.isValidSalt(CryptomanagerUtils.nullOrTrim(cryptoRequestDto.getSalt()))) { - decryptedData = cryptoCore.symmetricDecrypt(decryptedSymmetricKey, encryptedData, - CryptoUtil.decodeBase64(CryptomanagerUtils.nullOrTrim(cryptoRequestDto.getSalt())), - CryptoUtil.decodeBase64(CryptomanagerUtils.nullOrTrim(cryptoRequestDto.getAad()))); - } else { - if (Arrays.equals(headerBytes, CryptomanagerConstant.VERSION_RSA_2048)) { - decryptedData = splitAadAndDecryptData(decryptedSymmetricKey, encryptedData); - } else { - decryptedData = cryptoCore.symmetricDecrypt(decryptedSymmetricKey, encryptedData, - CryptoUtil.decodeBase64(CryptomanagerUtils.nullOrTrim(cryptoRequestDto.getAad()))); - } - } - LOGGER.info(CryptomanagerConstant.SESSIONID, CryptomanagerConstant.DECRYPT, CryptomanagerConstant.DECRYPT, - "Data decryption completed."); - CryptomanagerResponseDto cryptoResponseDto = new CryptomanagerResponseDto(); - cryptoResponseDto.setData(CryptoUtil.encodeBase64(decryptedData)); - return cryptoResponseDto; - } - - private byte[] splitAadAndDecryptData(SecretKey symmetricKey, byte[] encryptedData) { - - byte[] aad = copyOfRange(encryptedData, 0, CryptomanagerConstant.GCM_AAD_LENGTH); - byte[] nonce = copyOfRange(aad, 0, CryptomanagerConstant.GCM_NONCE_LENGTH); - byte[] finalEncData = copyOfRange(encryptedData, CryptomanagerConstant.GCM_AAD_LENGTH, encryptedData.length); - return cryptoCore.symmetricDecrypt(symmetricKey, finalEncData, nonce, aad); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.kernel.cryptomanager.service.CryptomanagerService#encryptWithPin(io.mosip. - * kernel.cryptomanager.dto.CryptoWithPinRequestDto) - */ - @Override - public CryptoWithPinResponseDto encryptWithPin(CryptoWithPinRequestDto requestDto) { - LOGGER.info(CryptomanagerConstant.SESSIONID, CryptomanagerConstant.ENCRYPT_PIN, CryptomanagerConstant.ENCRYPT_PIN, - "Request for data encryption with Pin."); - - String dataToEnc = requestDto.getData(); - String userPin = requestDto.getUserPin(); - - if(!cryptomanagerUtil.isDataValid(dataToEnc) || !cryptomanagerUtil.isDataValid(userPin)) { - LOGGER.error(CryptomanagerConstant.SESSIONID, CryptomanagerConstant.ENCRYPT_PIN, CryptomanagerConstant.ENCRYPT_PIN, - "Either Data to encrypt or user pin is blank."); - throw new CryptoManagerSerivceException(CryptomanagerErrorCode.INVALID_REQUEST.getErrorCode(), - CryptomanagerErrorCode.INVALID_REQUEST.getErrorMessage()); - } - - SecureRandom sRandom = new SecureRandom(); - byte[] pbeSalt = new byte[PBE_SALT_LENGTH]; - sRandom.nextBytes(pbeSalt); - - SecretKey derivedKey = getDerivedKey(userPin, pbeSalt); - byte[] gcmNonce = new byte[GCM_NONCE_LENGTH]; - sRandom.nextBytes(gcmNonce); - byte[] encryptedData = cryptoCore.symmetricEncrypt(derivedKey, dataToEnc.getBytes(), gcmNonce, pbeSalt); - - byte[] finalEncryptedData = new byte[encryptedData.length + PBE_SALT_LENGTH + GCM_NONCE_LENGTH]; - System.arraycopy(pbeSalt, 0, finalEncryptedData, 0, pbeSalt.length); - System.arraycopy(gcmNonce, 0, finalEncryptedData, pbeSalt.length, gcmNonce.length); - System.arraycopy(encryptedData, 0, finalEncryptedData, pbeSalt.length + gcmNonce.length, encryptedData.length); - CryptoWithPinResponseDto responseDto = new CryptoWithPinResponseDto(); - responseDto.setData(CryptoUtil.encodeBase64(finalEncryptedData)); - return responseDto; - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.kernel.cryptomanager.service.CryptomanagerService#decryptWithPin(io.mosip. - * kernel.cryptomanager.dto.CryptoWithPinRequestDto) - */ - @Override - public CryptoWithPinResponseDto decryptWithPin(CryptoWithPinRequestDto requestDto) { - LOGGER.info(CryptomanagerConstant.SESSIONID, CryptomanagerConstant.ENCRYPT_PIN, CryptomanagerConstant.ENCRYPT_PIN, - "Request for data decryption with Pin."); - - String dataToDec = requestDto.getData(); - String userPin = requestDto.getUserPin(); - - if(!cryptomanagerUtil.isDataValid(dataToDec) || !cryptomanagerUtil.isDataValid(userPin)) { - LOGGER.error(CryptomanagerConstant.SESSIONID, CryptomanagerConstant.ENCRYPT_PIN, CryptomanagerConstant.ENCRYPT_PIN, - "Either Data to decrypt or user pin is blank."); - throw new CryptoManagerSerivceException(CryptomanagerErrorCode.INVALID_REQUEST.getErrorCode(), - CryptomanagerErrorCode.INVALID_REQUEST.getErrorMessage()); - } - - byte[] decodedEncryptedData = CryptoUtil.decodeBase64(dataToDec); - byte[] pbeSalt = Arrays.copyOfRange(decodedEncryptedData, 0, PBE_SALT_LENGTH); - byte[] gcmNonce = Arrays.copyOfRange(decodedEncryptedData, PBE_SALT_LENGTH, PBE_SALT_LENGTH + GCM_NONCE_LENGTH); - byte[] encryptedData = Arrays.copyOfRange(decodedEncryptedData, PBE_SALT_LENGTH + GCM_NONCE_LENGTH, decodedEncryptedData.length); - - SecretKey derivedKey = getDerivedKey(userPin, pbeSalt); - byte[] decryptedData = cryptoCore.symmetricDecrypt(derivedKey, encryptedData, gcmNonce, pbeSalt); - CryptoWithPinResponseDto responseDto = new CryptoWithPinResponseDto(); - responseDto.setData(new String(decryptedData)); - return responseDto; - } - - private SecretKey getDerivedKey(String userPin, byte[] salt) { - String derivedKeyHex = cryptoCore.hash(userPin.getBytes(), salt); - byte[] derivedKey = cryptomanagerUtil.hexDecode(derivedKeyHex); - return new SecretKeySpec(derivedKey, AES_KEY_TYPE); - } - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/util/CryptomanagerUtils.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/util/CryptomanagerUtils.java deleted file mode 100644 index f2d26497ecd..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/util/CryptomanagerUtils.java +++ /dev/null @@ -1,226 +0,0 @@ -/* - * - * - * - * - */ -package io.mosip.kernel.cryptomanager.util; - -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.cert.Certificate; -import java.security.cert.CertificateEncodingException; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.Optional; - -import javax.crypto.SecretKey; -import javax.crypto.spec.SecretKeySpec; - -import org.apache.commons.codec.digest.DigestUtils; -import java.util.Arrays; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.cloud.context.config.annotation.RefreshScope; -import org.springframework.stereotype.Component; - -import io.mosip.kernel.core.exception.ParseException; -import io.mosip.kernel.core.util.CryptoUtil; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.cryptomanager.constant.CryptomanagerConstant; -import io.mosip.kernel.cryptomanager.constant.CryptomanagerErrorCode; -import io.mosip.kernel.cryptomanager.dto.CryptomanagerRequestDto; -import io.mosip.kernel.cryptomanager.exception.CryptoManagerSerivceException; -import io.mosip.kernel.keymanagerservice.dto.SymmetricKeyRequestDto; -import io.mosip.kernel.keymanagerservice.service.KeymanagerService; -import io.mosip.kernel.keymanagerservice.util.KeymanagerUtil; -import io.mosip.kernel.keymanagerservice.logger.KeymanagerLogger; - -/** - * Util class for this project. - * - * @author Urvil Joshi - * @author Manoj SP - * @since 1.0.0 - */ -@RefreshScope -@Component -public class CryptomanagerUtils { - - private static final Logger LOGGER = KeymanagerLogger.getLogger(CryptomanagerUtils.class); - - /** The Constant UTC_DATETIME_PATTERN. */ - private static final String UTC_DATETIME_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; - - /** Asymmetric Algorithm Name. */ - @Value("${mosip.kernel.keygenerator.asymmetric-algorithm-name}") - private String asymmetricAlgorithmName; - - /** Symmetric Algorithm Name. */ - @Value("${mosip.kernel.keygenerator.symmetric-algorithm-name}") - private String symmetricAlgorithmName; - - - /** Key Splitter. */ - @Value("${mosip.kernel.data-key-splitter}") - private String keySplitter; - - /** The key manager. */ - @Autowired - private KeymanagerService keyManager; - - @Autowired - private KeymanagerUtil keymanagerUtil; - - /** - * Calls Key-Manager-Service to get public key of an application. - * - * @param cryptomanagerRequestDto {@link CryptomanagerRequestDto} instance - * @return {@link Certificate} returned by Key Manager Service - */ - public Certificate getCertificate(CryptomanagerRequestDto cryptomanagerRequestDto) { - String certData = getCertificateFromKeyManager(cryptomanagerRequestDto.getApplicationId(), - cryptomanagerRequestDto.getReferenceId()); - - return keymanagerUtil.convertToCertificate(certData); - } - - /** - * Gets the certificate from key manager. - * - * @param appId the app id - * @param refId the ref id - * @return the certificate data from key manager - */ - private String getCertificateFromKeyManager(String appId, String refId) { - return keyManager.getCertificate(appId, Optional.ofNullable(refId)).getCertificate(); - } - - - /** - * Calls Key-Manager-Service to decrypt symmetric key. - * - * @param cryptomanagerRequestDto {@link CryptomanagerRequestDto} instance - * @return Decrypted {@link SecretKey} from Key Manager Service - */ - public SecretKey getDecryptedSymmetricKey(CryptomanagerRequestDto cryptomanagerRequestDto) { - byte[] symmetricKey = CryptoUtil.decodeBase64(decryptSymmetricKeyUsingKeyManager(cryptomanagerRequestDto)); - return new SecretKeySpec(symmetricKey, 0, symmetricKey.length, symmetricAlgorithmName); - } - - /** - * Decrypt symmetric key using key manager. - * - * @param cryptomanagerRequestDto the cryptomanager request dto - * @return the string - */ - private String decryptSymmetricKeyUsingKeyManager(CryptomanagerRequestDto cryptomanagerRequestDto) { - SymmetricKeyRequestDto symmetricKeyRequestDto = new SymmetricKeyRequestDto( - cryptomanagerRequestDto.getApplicationId(), cryptomanagerRequestDto.getTimeStamp(), - cryptomanagerRequestDto.getReferenceId(), cryptomanagerRequestDto.getData(), cryptomanagerRequestDto.getPrependThumbprint()); - return keyManager.decryptSymmetricKey(symmetricKeyRequestDto).getSymmetricKey(); - } - - /** - * Change Parameter form to trim if not null. - * - * @param parameter parameter - * @return null if null;else trimmed string - */ - public static String nullOrTrim(String parameter) { - return parameter == null ? null : parameter.trim(); - } - - /** - * Function to check is salt is valid. - * - * @param salt salt - * @return true if salt is valid, else false - */ - public boolean isValidSalt(String salt) { - return salt != null && !salt.trim().isEmpty(); - } - - /** - * Parse a date string of pattern UTC_DATETIME_PATTERN into - * {@link LocalDateTime}. - * - * @param dateTimeof type {@link String} of pattern UTC_DATETIME_PATTERN - * @return a {@link LocalDateTime} of given pattern - */ - public LocalDateTime parseToLocalDateTime(String dateTime) { - return LocalDateTime.parse(dateTime, DateTimeFormatter.ofPattern(UTC_DATETIME_PATTERN)); - } - - /** - * hex decode string to byte array - * - * @param hexData type {@link String} - * @return a {@link byte[]} of given data - */ - public byte[] hexDecode(String hexData) { - - char[] hexDataCharArr = hexData.toCharArray(); - int dataLength = hexDataCharArr.length; - - if ((dataLength & 0x01) != 0) { - throw new ParseException(CryptomanagerErrorCode.HEX_DATA_PARSE_EXCEPTION.getErrorCode(), - CryptomanagerErrorCode.HEX_DATA_PARSE_EXCEPTION.getErrorMessage()); - } - - byte[] decodedBytes = new byte[dataLength >> 1]; - - for (int i = 0, j = 0; j < dataLength; i++) { - int f = Character.digit(hexDataCharArr[j], 16) << 4; - j++; - f = f | Character.digit(hexDataCharArr[j], 16); - j++; - decodedBytes[i] = (byte) (f & 0xFF); - } - return decodedBytes; - } - - public byte[] getCertificateThumbprint(Certificate cert) { - try { - return DigestUtils.sha256(cert.getEncoded()); - } catch (CertificateEncodingException e) { - LOGGER.error(CryptomanagerConstant.SESSIONID, CryptomanagerConstant.ENCRYPT, "", - "Error generating certificate thumbprint."); - throw new CryptoManagerSerivceException(CryptomanagerErrorCode.CERTIFICATE_THUMBPRINT_ERROR.getErrorCode(), - CryptomanagerErrorCode.CERTIFICATE_THUMBPRINT_ERROR.getErrorMessage()); - } - } - - public byte[] concatCertThumbprint(byte[] certThumbprint, byte[] encryptedKey){ - byte[] finalData = new byte[CryptomanagerConstant.THUMBPRINT_LENGTH + encryptedKey.length]; - System.arraycopy(certThumbprint, 0, finalData, 0, certThumbprint.length); - System.arraycopy(encryptedKey, 0, finalData, certThumbprint.length, encryptedKey.length); - return finalData; - } - - public byte[] generateRandomBytes(int size) { - byte[] randomBytes = new byte[size]; - SecureRandom secureRandom = new SecureRandom(); - secureRandom.nextBytes(randomBytes); - return randomBytes; - } - - public byte[] concatByteArrays(byte[] array1, byte[] array2){ - byte[] finalData = new byte[array1.length + array2.length]; - System.arraycopy(array1, 0, finalData, 0, array1.length); - System.arraycopy(array2, 0, finalData, array1.length, array2.length); - return finalData; - } - - public byte[] parseEncryptKeyHeader(byte[] encryptedKey){ - byte[] versionHeaderBytes = Arrays.copyOfRange(encryptedKey, 0, CryptomanagerConstant.VERSION_RSA_2048.length); - if (!Arrays.equals(versionHeaderBytes, CryptomanagerConstant.VERSION_RSA_2048)) { - return new byte[0]; - } - return versionHeaderBytes; - } - - public boolean isDataValid(String anyData) { - return anyData != null && !anyData.trim().isEmpty(); - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/util/KeymanagerSymmetricKeyConverter.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/util/KeymanagerSymmetricKeyConverter.java deleted file mode 100644 index 4bfd85cae7b..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/util/KeymanagerSymmetricKeyConverter.java +++ /dev/null @@ -1,31 +0,0 @@ -package io.mosip.kernel.cryptomanager.util; - -import io.mosip.kernel.core.datamapper.spi.DataConverter; -import io.mosip.kernel.cryptomanager.dto.CryptomanagerRequestDto; -import io.mosip.kernel.cryptomanager.dto.KeymanagerSymmetricKeyRequestDto; - -/** - * Custom converter for {@link KeymanagerSymmetricKeyRequestDto} and - * {@link CryptomanagerRequestDto} - * - * @author Urvil Joshi - * - * @since 1.0.0 - */ -public class KeymanagerSymmetricKeyConverter - implements DataConverter { - - /* - * (non-Javadoc) - * - * @see io.mosip.kernel.core.datamapper.spi.DataConverter#convert(java.lang. - * Object, java.lang.Object) - */ - @Override - public void convert(CryptomanagerRequestDto source, KeymanagerSymmetricKeyRequestDto destination) { - destination.setApplicationId(source.getApplicationId()); - destination.setReferenceId(source.getReferenceId()); - destination.setTimeStamp(source.getTimeStamp()); - destination.setEncryptedSymmetricKey(source.getData()); - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keygenerator/bouncycastle/KeyGenerator.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keygenerator/bouncycastle/KeyGenerator.java deleted file mode 100644 index 9d4d497bb7e..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keygenerator/bouncycastle/KeyGenerator.java +++ /dev/null @@ -1,69 +0,0 @@ -package io.mosip.kernel.keygenerator.bouncycastle; - -import java.security.KeyPair; -import java.security.KeyPairGenerator; - -import javax.crypto.SecretKey; - -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; - -import io.mosip.kernel.keygenerator.bouncycastle.util.KeyGeneratorUtils; - -/** - * This class generates asymmetric and symmetric key pairs - * - * @author Urvil Joshi - * - * @since 1.0.0 - */ -@Component -public class KeyGenerator { - - /** - * Symmetric key algorithm Name - */ - @Value("${mosip.kernel.keygenerator.symmetric-algorithm-name}") - private String symmetricKeyAlgorithm; - - /** - * Symmetric key length - */ - @Value("${mosip.kernel.keygenerator.symmetric-key-length}") - private int symmetricKeyLength; - - /** - * Asymmetric key algorithm Name - */ - @Value("${mosip.kernel.keygenerator.asymmetric-algorithm-name}") - private String asymmetricKeyAlgorithm; - - /** - * Asymmetric key length - */ - @Value("${mosip.kernel.keygenerator.asymmetric-key-length}") - private int asymmetricKeyLength; - - /** - * This method generates symmetric key - * - * @return generated {@link SecretKey} - */ - public SecretKey getSymmetricKey() { - javax.crypto.KeyGenerator generator = KeyGeneratorUtils.getKeyGenerator(symmetricKeyAlgorithm, - symmetricKeyLength); - return generator.generateKey(); - } - - /** - * This method generated Asymmetric key pairs - * - * @return {@link KeyPair} which contain public nad private key - */ - public KeyPair getAsymmetricKey() { - KeyPairGenerator generator = KeyGeneratorUtils.getKeyPairGenerator(asymmetricKeyAlgorithm, asymmetricKeyLength); - return generator.generateKeyPair(); - - } - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keygenerator/bouncycastle/constant/KeyGeneratorExceptionConstant.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keygenerator/bouncycastle/constant/KeyGeneratorExceptionConstant.java deleted file mode 100644 index 8fb4f8ed61b..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keygenerator/bouncycastle/constant/KeyGeneratorExceptionConstant.java +++ /dev/null @@ -1,77 +0,0 @@ -package io.mosip.kernel.keygenerator.bouncycastle.constant; - -/** - * Exception constants for this Application - * - * @author Urvil Joshi - * @since 1.0.0 - */ -public enum KeyGeneratorExceptionConstant { - - /** - * {@link #MOSIP_NO_SUCH_ALGORITHM_EXCEPTION} exception constant - */ - MOSIP_NO_SUCH_ALGORITHM_EXCEPTION("KER-KEG-010", "no such algorithm is present"); - - /** - * Constructor for this {@link Enum} - */ - private KeyGeneratorExceptionConstant() { - } - - /** - * Constructor for this {@link Enum} - * - * @param errorCode errorCode for exception - * @param errorMessage errorMessage for exception - */ - KeyGeneratorExceptionConstant(String errorCode, String errorMessage) { - this.setErrorCode(errorCode); - this.setErrorMessage(errorMessage); - } - - /** - * Getter for {@link #errorCode} - * - * @return {@link #errorCode} - */ - public String getErrorCode() { - return errorCode; - } - - /** - * Setter for {@link #errorCode} - * - * @param errorCode {@link #errorCode} - */ - private void setErrorCode(String errorCode) { - this.errorCode = errorCode; - } - - /** - * Getter for {@link #errorMessage} - * - * @return {@link #errorMessage} - */ - public String getErrorMessage() { - return errorMessage; - } - - /** - * Setter for {@link #errorMessage} - * - * @param errorMessage - */ - private void setErrorMessage(String errorMessage) { - this.errorMessage = errorMessage; - } - - /** - * Error Code for Exception - */ - private String errorCode; - /** - * Error Message for Exception - */ - private String errorMessage; -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keygenerator/bouncycastle/util/KeyGeneratorUtils.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keygenerator/bouncycastle/util/KeyGeneratorUtils.java deleted file mode 100644 index 376286994cf..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keygenerator/bouncycastle/util/KeyGeneratorUtils.java +++ /dev/null @@ -1,92 +0,0 @@ -package io.mosip.kernel.keygenerator.bouncycastle.util; - -import java.security.KeyPairGenerator; -import java.security.SecureRandom; -import java.security.Security; - -import javax.crypto.KeyGenerator; - -import org.bouncycastle.jce.provider.BouncyCastleProvider; - -import io.mosip.kernel.core.exception.NoSuchAlgorithmException; -import io.mosip.kernel.keygenerator.bouncycastle.constant.KeyGeneratorExceptionConstant; - -/** - * This is a utils class for keygenerator - * - * @author Urvil Joshi - * - * @since 1.0.0 - */ -public class KeyGeneratorUtils { - - /** - * Bouncy-Castle provider instance - */ - private static BouncyCastleProvider provider; - - static { - provider = init(); - } - - /** - * No Args Constructor for this class - */ - private KeyGeneratorUtils() { - } - - /** - * This class configures {@link KeyGenerator} - * - * @param algorithmName algorithm name as configured - * @param keylength key-length as configured - * @return configured {@link KeyGenerator} instance - */ - public static javax.crypto.KeyGenerator getKeyGenerator(String algorithmName, int keylength) { - - javax.crypto.KeyGenerator generator = null; - try { - generator = javax.crypto.KeyGenerator.getInstance(algorithmName, provider); - } catch (java.security.NoSuchAlgorithmException e) { - throw new NoSuchAlgorithmException( - KeyGeneratorExceptionConstant.MOSIP_NO_SUCH_ALGORITHM_EXCEPTION.getErrorCode(), - KeyGeneratorExceptionConstant.MOSIP_NO_SUCH_ALGORITHM_EXCEPTION.getErrorMessage(), e); - } - SecureRandom random = new SecureRandom(); - generator.init(keylength, random); - return generator; - } - - /** - * This class configures {@link KeyPairGenerator} - * - * @param algorithmName algorithm name as configured - * @param keylength key-length as configured - * @return configured {@link KeyPairGenerator} instance - */ - public static KeyPairGenerator getKeyPairGenerator(String algorithmName, int keylength) { - - KeyPairGenerator generator = null; - try { - generator = KeyPairGenerator.getInstance(algorithmName, provider); - } catch (java.security.NoSuchAlgorithmException e) { - throw new NoSuchAlgorithmException( - KeyGeneratorExceptionConstant.MOSIP_NO_SUCH_ALGORITHM_EXCEPTION.getErrorCode(), - KeyGeneratorExceptionConstant.MOSIP_NO_SUCH_ALGORITHM_EXCEPTION.getErrorMessage(), e); - } - SecureRandom random = new SecureRandom(); - generator.initialize(keylength, random); - return generator; - } - - /** - * Initialize by adding bouncy castle provider in JVM. - * - * @return {@link BouncyCastleProvider} - */ - private static BouncyCastleProvider init() { - BouncyCastleProvider provider = new BouncyCastleProvider(); - Security.addProvider(provider); - return provider; - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanager/hsm/constant/KeymanagerConstant.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanager/hsm/constant/KeymanagerConstant.java deleted file mode 100644 index 724492c4aa5..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanager/hsm/constant/KeymanagerConstant.java +++ /dev/null @@ -1,59 +0,0 @@ -package io.mosip.kernel.keymanager.hsm.constant; - -/** - * Constants for Softhsm Keystore - * - * @author Dharmesh Khandelwal - * @since 1.0.0 - * - */ -public final class KeymanagerConstant { - - /** - * Private constructor for SofthsmKeystoreConstant - */ - private KeymanagerConstant() { - } - - /** - * String constant for dot - */ - public static final String DOT = "."; - /** - * String constant for signature algorithm - */ - public static final String SIGNATURE_ALGORITHM = "SHA256withRSA"; - - public static final String SUN_PKCS11_PROVIDER = "SunPKCS11"; - - public static final String KEYSTORE_TYPE_PKCS11 = "PKCS11"; - - public static final String KEYSTORE_TYPE_PKCS12 = "PKCS12"; - - public static final String KEYSTORE_TYPE_OFFLINE = "OFFLINE"; - - public static final String SYM_KEY_ALGORITHM = "SYM_KEY_ALGORITHM"; - - public static final String SYM_KEY_SIZE = "SYM_KEY_SIZE"; - - public static final String ASYM_KEY_ALGORITHM = "ASYM_KEY_ALGORITHM"; - - public static final String ASYM_KEY_SIZE = "ASYM_KEY_SIZE"; - - public static final String CERT_SIGN_ALGORITHM = "CERT_SIGN_ALGORITHM"; - - public static final String CONFIG_FILE_PATH = "CONFIG_FILE_PATH"; - - public static final String PKCS11_KEYSTORE_PASSWORD = "PKCS11_KEYSTORE_PASSWORD"; - - public static final String PKCS11_KS_IMPL_CLAZZ = "io.mosip.kernel.keymanager.hsm.impl.pkcs.PKCS11KeyStoreImpl"; - - public static final String PKCS12_KS_IMPL_CLAZZ = "io.mosip.kernel.keymanager.hsm.impl.pkcs.PKCS12KeyStoreImpl"; - - public static final String OFFLINE_KS_IMPL_CLAZZ = "io.mosip.kernel.keymanager.hsm.impl.offline.OLKeyStoreImpl"; - - public static final String JCE_CLAZZ_NAME = "className"; - - public static final String FLAG_KEY_REF_CACHE = "FLAG_KEY_REF_CACHE"; - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanager/hsm/constant/KeymanagerErrorCode.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanager/hsm/constant/KeymanagerErrorCode.java deleted file mode 100644 index 50bc6fad28f..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanager/hsm/constant/KeymanagerErrorCode.java +++ /dev/null @@ -1,67 +0,0 @@ -package io.mosip.kernel.keymanager.hsm.constant; - -/** - * Error Code for Softhsm Keystore - * - * @author Dharmesh Khandelwal - * @since 1.0.0 - * - */ -public enum KeymanagerErrorCode { - INVALID_CONFIG_FILE("KER-KMA-001", "Config file invalid"), - - NO_SUCH_SECURITY_PROVIDER("KER-KMA-002", "No such security provider"), - - KEYSTORE_PROCESSING_ERROR("KER-KMA-003", "Error occured in processing Keystore: "), - - NO_SUCH_ALIAS("KER-KMA-004", "No such alias: "), - - CERTIFICATE_PROCESSING_ERROR("KER-KMA-005", "Error occured while processing exception: "), - - NOT_VALID_STORE_PASSWORD("KER-KMA-007", "Provided Keystore password is not valid."), - - KEYSTORE_NOT_INSTANTIATED("KER-KMA-006", "Keystore not instantiated error."), - - KEYSTORE_NO_CONSTRUCTOR_FOUND("KER-KMA-008", "Keystore implemenation clazz has no constructor with Map as argument."), - - OFFLINE_KEYSTORE_ACCESS_ERROR("KER-KMA-009", "Keystore instantiated as offline, performing operation not allowed."); - - /** - * The error code - */ - private final String errorCode; - /** - * The error message - */ - private final String errorMessage; - - /** - * Constructor to set error code and message - * - * @param errorCode the error code - * @param errorMessage the error message - */ - private KeymanagerErrorCode(final String errorCode, final String errorMessage) { - this.errorCode = errorCode; - this.errorMessage = errorMessage; - } - - /** - * Function to get error code - * - * @return {@link #errorCode} - */ - public String getErrorCode() { - return errorCode; - } - - /** - * Function to get the error message - * - * @return {@link #errorMessage} - */ - public String getErrorMessage() { - return errorMessage; - } - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanager/hsm/impl/KeyStoreImpl.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanager/hsm/impl/KeyStoreImpl.java deleted file mode 100644 index 428ca2292e1..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanager/hsm/impl/KeyStoreImpl.java +++ /dev/null @@ -1,316 +0,0 @@ -package io.mosip.kernel.keymanager.hsm.impl; - -import java.lang.reflect.Constructor; -import java.security.Key; -import java.security.KeyStore.PrivateKeyEntry; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.cert.Certificate; -import java.security.cert.X509Certificate; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -import javax.crypto.SecretKey; - -import org.springframework.beans.factory.InitializingBean; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.data.util.ReflectionUtils; -import org.springframework.stereotype.Component; - -import io.mosip.kernel.core.keymanager.exception.KeystoreProcessingException; -import io.mosip.kernel.core.keymanager.model.CertificateParameters; -import io.mosip.kernel.core.keymanager.spi.KeyStore; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.keymanager.hsm.constant.KeymanagerConstant; -import io.mosip.kernel.keymanager.hsm.constant.KeymanagerErrorCode; -import io.mosip.kernel.keymanagerservice.logger.KeymanagerLogger; - - -/** - * HSM Keymanager implementation based on OpenDNSSEC that handles and stores - * its cryptographic keys via the PKCS#11 interface. This is a software - * implementation of a generic cryptographic device. SoftHSM can work with other - * cryptographic device because of the PKCS#11 interface. - * - * @author Dharmesh Khandelwal - * @since 1.0.0 - * - */ -@ConfigurationProperties(prefix = "mosip.kernel.keymanager.hsm") -@Component -public class KeyStoreImpl implements KeyStore, InitializingBean { - - private static final Logger LOGGER = KeymanagerLogger.getLogger(KeyStoreImpl.class); - - private static final Map DEFAULT_KS_IMPL_CLASSES = new HashMap<>(); - - static { - DEFAULT_KS_IMPL_CLASSES.put(KeymanagerConstant.KEYSTORE_TYPE_PKCS11, KeymanagerConstant.PKCS11_KS_IMPL_CLAZZ); - DEFAULT_KS_IMPL_CLASSES.put(KeymanagerConstant.KEYSTORE_TYPE_PKCS12, KeymanagerConstant.PKCS12_KS_IMPL_CLAZZ); - DEFAULT_KS_IMPL_CLASSES.put(KeymanagerConstant.KEYSTORE_TYPE_OFFLINE, KeymanagerConstant.OFFLINE_KS_IMPL_CLAZZ); - } - - /** - * The type of keystore, e.g. PKCS11, PKCS12, JCE - */ - @Value("${mosip.kernel.keymanager.hsm.keystore-type:PKCS11}") - private String keystoreType; - - /** - * Path of HSM PKCS11 config file or the Keystore in caes of bouncy castle - * provider - */ - @Value("${mosip.kernel.keymanager.hsm.config-path:\"\"}") - private String configPath; - - /** - * The passkey for Keystore - */ - @Value("${mosip.kernel.keymanager.hsm.keystore-pass:\"\"}") - private String keystorePass; - - /** - * Symmetric key algorithm Name - */ - @Value("${mosip.kernel.keygenerator.symmetric-algorithm-name:AES}") - private String symmetricKeyAlgorithm; - - /** - * Symmetric key length - */ - @Value("${mosip.kernel.keygenerator.symmetric-key-length:256}") - private int symmetricKeyLength; - - /** - * Asymmetric key algorithm Name - */ - @Value("${mosip.kernel.keygenerator.asymmetric-algorithm-name:RSA}") - private String asymmetricKeyAlgorithm; - - /** - * Asymmetric key length - */ - @Value("${mosip.kernel.keygenerator.asymmetric-key-length:2048}") - private int asymmetricKeyLength; - - /** - * Certificate Signing Algorithm - * - */ - @Value("${mosip.kernel.certificate.sign.algorithm:SHA256withRSA}") - private String signAlgorithm; - - /** - * Key Reference Cache Enable flag - * - */ - @Value("${mosip.kernel.keymanager.keystore.keyreference.enable.cache:true}") - private boolean enableKeyReferenceCache; - - /** - * JCE Implementation Clazz Name and other required information. - * - */ - private Map jceParams = new HashMap(); - - /** - * Algorithms names & Key Size Information. - * - */ - private Map keystoreParams = new HashMap(); - - /** - * Delegate Object. - * - */ - private KeyStore keyStore = null; - - @Override - public void afterPropertiesSet() throws Exception { - - // Adding supported algorithms from properties file. - setAlgorithmProperties(); - String clazzName = DEFAULT_KS_IMPL_CLASSES.get(keystoreType); - if (Objects.isNull(clazzName)) { - clazzName = jceParams.get(KeymanagerConstant.JCE_CLAZZ_NAME); - mergeJceParams(); - } else { - addPKCSParams(); - } - // Still clazzName is null, loading the keystore as offline to support only encryption. - if (Objects.isNull(clazzName)) { - LOGGER.info("ksSessionId", "KeyStoreImpl-Main", "KeyStoreImpl", "No Clazz Found to load " + - "for Keystore Impl, So loading default offline clazz."); - clazzName = DEFAULT_KS_IMPL_CLASSES.get(KeymanagerConstant.OFFLINE_KS_IMPL_CLAZZ); - } - LOGGER.info("ksSessionId", "KeyStoreImpl-Main", "KeyStoreImpl", "Found Clazz to load for Keystore Impl: " + clazzName); - Class object = Class.forName(clazzName); - Optional> resConstructor = ReflectionUtils.findConstructor(object, keystoreParams); - if (resConstructor.isPresent()) { - Constructor constructor = resConstructor.get(); - constructor.setAccessible(true); - keyStore = (KeyStore) constructor.newInstance(keystoreParams); - } else { - throw new KeystoreProcessingException(KeymanagerErrorCode.KEYSTORE_NO_CONSTRUCTOR_FOUND.getErrorCode(), - KeymanagerErrorCode.KEYSTORE_NO_CONSTRUCTOR_FOUND.getErrorMessage()); - } - LOGGER.info("ksSessionId", "KeyStoreImpl-Main", "KeyStoreImpl", "Successfully loaded Clazz for Keystore Impl: " + clazzName); - } - - private void setAlgorithmProperties() { - keystoreParams.put(KeymanagerConstant.SYM_KEY_ALGORITHM, symmetricKeyAlgorithm); - keystoreParams.put(KeymanagerConstant.SYM_KEY_SIZE, Integer.toString(symmetricKeyLength)); - keystoreParams.put(KeymanagerConstant.ASYM_KEY_ALGORITHM, asymmetricKeyAlgorithm); - keystoreParams.put(KeymanagerConstant.ASYM_KEY_SIZE, Integer.toString(asymmetricKeyLength)); - keystoreParams.put(KeymanagerConstant.CERT_SIGN_ALGORITHM, signAlgorithm); - keystoreParams.put(KeymanagerConstant.FLAG_KEY_REF_CACHE, Boolean.toString(enableKeyReferenceCache)); - } - - private void addPKCSParams() { - keystoreParams.put(KeymanagerConstant.CONFIG_FILE_PATH, configPath); - keystoreParams.put(KeymanagerConstant.PKCS11_KEYSTORE_PASSWORD, keystorePass); - } - - - private void mergeJceParams(){ - - jceParams.forEach((key, value) -> { - if(!key.equals(KeymanagerConstant.JCE_CLAZZ_NAME)){ - keystoreParams.put(key, value); - } - }); - } - /* - * (non-Javadoc) - * - * @see io.mosip.kernel.core.keymanager.spi.SofthsmKeystore#getAllAlias() - */ - @Override - public List getAllAlias() { - return keyStore.getAllAlias(); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.kernel.core.keymanager.spi.SofthsmKeystore#getKey(java.lang.String) - */ - @Override - public Key getKey(String alias) { - return keyStore.getKey(alias); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.kernel.core.keymanager.spi.SofthsmKeystore#getAsymmetricKey(java. - * lang.String) - */ - @Override - public PrivateKeyEntry getAsymmetricKey(String alias) { - return keyStore.getAsymmetricKey(alias); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.kernel.core.keymanager.spi.SofthsmKeystore#getPrivateKey(java.lang. - * String) - */ - @Override - public PrivateKey getPrivateKey(String alias) { - return keyStore.getPrivateKey(alias); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.kernel.core.keymanager.spi.SofthsmKeystore#getPublicKey(java.lang. - * String) - */ - @Override - public PublicKey getPublicKey(String alias) { - return keyStore.getPublicKey(alias); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.kernel.core.keymanager.spi.SofthsmKeystore#getCertificate(java.lang. - * String) - */ - @Override - public X509Certificate getCertificate(String alias) { - return (X509Certificate) keyStore.getCertificate(alias); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.kernel.core.keymanager.spi.SofthsmKeystore#getSymmetricKey(java.lang - * .String) - */ - @Override - public SecretKey getSymmetricKey(String alias) { - return keyStore.getSymmetricKey(alias); - } - - /* - * (non-Javadoc) - * - * @see io.mosip.kernel.core.keymanager.spi.SofthsmKeystore#deleteKey(java.lang. - * String) - */ - @Override - public void deleteKey(String alias) { - keyStore.deleteKey(alias); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.kernel.core.keymanager.spi.SofthsmKeystore#storeAsymmetricKey(java. - * security.KeyPair, java.lang.String) - */ - @Override - public void generateAndStoreAsymmetricKey(String alias, String signKeyAlias, CertificateParameters certParams) { - keyStore.generateAndStoreAsymmetricKey(alias, signKeyAlias, certParams); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.kernel.core.keymanager.spi.SofthsmKeystore#storeSymmetricKey(javax. - * crypto.SecretKey, java.lang.String) - */ - @Override - public void generateAndStoreSymmetricKey(String alias) { - keyStore.generateAndStoreSymmetricKey(alias); - } - - @Override - public void storeCertificate(String alias, PrivateKey privateKey, Certificate certificate) { - keyStore.storeCertificate(alias, privateKey, certificate); - } - - @Override - public String getKeystoreProviderName() { - return keyStore.getKeystoreProviderName(); - } - - public void setJce(Map jce) { - this.jceParams = jce; - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanager/hsm/impl/offline/OLKeyStoreImpl.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanager/hsm/impl/offline/OLKeyStoreImpl.java deleted file mode 100644 index d834bf5d963..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanager/hsm/impl/offline/OLKeyStoreImpl.java +++ /dev/null @@ -1,169 +0,0 @@ -package io.mosip.kernel.keymanager.hsm.impl.offline; - -import java.security.Key; -import java.security.KeyStore.PrivateKeyEntry; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.cert.Certificate; -import java.security.cert.X509Certificate; -import java.util.List; -import java.util.Map; - -import javax.crypto.SecretKey; - -import io.mosip.kernel.core.keymanager.exception.KeystoreProcessingException; -import io.mosip.kernel.core.keymanager.model.CertificateParameters; -import io.mosip.kernel.keymanager.hsm.constant.KeymanagerConstant; -import io.mosip.kernel.keymanager.hsm.constant.KeymanagerErrorCode; - - -/** - * Offline Keymanager implementation to support only encryption & signature verification API. - * - * @author Mahammed Taheer - * @since 1.1.4 - * - */ -public class OLKeyStoreImpl implements io.mosip.kernel.core.keymanager.spi.KeyStore { - - public OLKeyStoreImpl(Map params) throws Exception { - // Key Generation is not allowed in case of offline keystore. - } - - /* - * (non-Javadoc) - * - * @see io.mosip.kernel.core.keymanager.spi.SofthsmKeystore#getAllAlias() - */ - @Override - public List getAllAlias() { - throw new KeystoreProcessingException(KeymanagerErrorCode.OFFLINE_KEYSTORE_ACCESS_ERROR.getErrorCode(), - KeymanagerErrorCode.OFFLINE_KEYSTORE_ACCESS_ERROR.getErrorMessage()); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.kernel.core.keymanager.spi.SofthsmKeystore#getKey(java.lang.String) - */ - @Override - public Key getKey(String alias) { - throw new KeystoreProcessingException(KeymanagerErrorCode.OFFLINE_KEYSTORE_ACCESS_ERROR.getErrorCode(), - KeymanagerErrorCode.OFFLINE_KEYSTORE_ACCESS_ERROR.getErrorMessage()); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.kernel.core.keymanager.spi.SofthsmKeystore#getAsymmetricKey(java. - * lang.String) - */ - @Override - public PrivateKeyEntry getAsymmetricKey(String alias) { - throw new KeystoreProcessingException(KeymanagerErrorCode.OFFLINE_KEYSTORE_ACCESS_ERROR.getErrorCode(), - KeymanagerErrorCode.OFFLINE_KEYSTORE_ACCESS_ERROR.getErrorMessage()); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.kernel.core.keymanager.spi.SofthsmKeystore#getPrivateKey(java.lang. - * String) - */ - @Override - public PrivateKey getPrivateKey(String alias) { - throw new KeystoreProcessingException(KeymanagerErrorCode.OFFLINE_KEYSTORE_ACCESS_ERROR.getErrorCode(), - KeymanagerErrorCode.OFFLINE_KEYSTORE_ACCESS_ERROR.getErrorMessage()); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.kernel.core.keymanager.spi.SofthsmKeystore#getPublicKey(java.lang. - * String) - */ - @Override - public PublicKey getPublicKey(String alias) { - throw new KeystoreProcessingException(KeymanagerErrorCode.OFFLINE_KEYSTORE_ACCESS_ERROR.getErrorCode(), - KeymanagerErrorCode.OFFLINE_KEYSTORE_ACCESS_ERROR.getErrorMessage()); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.kernel.core.keymanager.spi.SofthsmKeystore#getCertificate(java.lang. - * String) - */ - @Override - public X509Certificate getCertificate(String alias) { - throw new KeystoreProcessingException(KeymanagerErrorCode.OFFLINE_KEYSTORE_ACCESS_ERROR.getErrorCode(), - KeymanagerErrorCode.OFFLINE_KEYSTORE_ACCESS_ERROR.getErrorMessage()); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.kernel.core.keymanager.spi.SofthsmKeystore#getSymmetricKey(java.lang - * .String) - */ - @Override - public SecretKey getSymmetricKey(String alias) { - throw new KeystoreProcessingException(KeymanagerErrorCode.OFFLINE_KEYSTORE_ACCESS_ERROR.getErrorCode(), - KeymanagerErrorCode.OFFLINE_KEYSTORE_ACCESS_ERROR.getErrorMessage()); - } - - /* - * (non-Javadoc) - * - * @see io.mosip.kernel.core.keymanager.spi.SofthsmKeystore#deleteKey(java.lang. - * String) - */ - @Override - public void deleteKey(String alias) { - throw new KeystoreProcessingException(KeymanagerErrorCode.OFFLINE_KEYSTORE_ACCESS_ERROR.getErrorCode(), - KeymanagerErrorCode.OFFLINE_KEYSTORE_ACCESS_ERROR.getErrorMessage()); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.kernel.core.keymanager.spi.SofthsmKeystore#storeAsymmetricKey(java. - * security.KeyPair, java.lang.String) - */ - @Override - public void generateAndStoreAsymmetricKey(String alias, String signKeyAlias, CertificateParameters certParams) { - throw new KeystoreProcessingException(KeymanagerErrorCode.OFFLINE_KEYSTORE_ACCESS_ERROR.getErrorCode(), - KeymanagerErrorCode.OFFLINE_KEYSTORE_ACCESS_ERROR.getErrorMessage()); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.kernel.core.keymanager.spi.SofthsmKeystore#storeSymmetricKey(javax. - * crypto.SecretKey, java.lang.String) - */ - @Override - public void generateAndStoreSymmetricKey(String alias) { - throw new KeystoreProcessingException(KeymanagerErrorCode.OFFLINE_KEYSTORE_ACCESS_ERROR.getErrorCode(), - KeymanagerErrorCode.OFFLINE_KEYSTORE_ACCESS_ERROR.getErrorMessage()); - } - - @Override - public void storeCertificate(String alias, PrivateKey privateKey, Certificate certificate) { - throw new KeystoreProcessingException(KeymanagerErrorCode.OFFLINE_KEYSTORE_ACCESS_ERROR.getErrorCode(), - KeymanagerErrorCode.OFFLINE_KEYSTORE_ACCESS_ERROR.getErrorMessage()); - } - - @Override - public String getKeystoreProviderName() { - return KeymanagerConstant.KEYSTORE_TYPE_OFFLINE; - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanager/hsm/impl/pkcs/PKCS11KeyStoreImpl.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanager/hsm/impl/pkcs/PKCS11KeyStoreImpl.java deleted file mode 100644 index 9cbd9e41b2d..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanager/hsm/impl/pkcs/PKCS11KeyStoreImpl.java +++ /dev/null @@ -1,607 +0,0 @@ -package io.mosip.kernel.keymanager.hsm.impl.pkcs; - -import java.io.FileInputStream; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.security.InvalidParameterException; -import java.security.Key; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.KeyStore; -import java.security.KeyStore.PasswordProtection; -import java.security.KeyStore.PrivateKeyEntry; -import java.security.KeyStore.ProtectionParameter; -import java.security.KeyStore.SecretKeyEntry; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.Provider; -import java.security.ProviderException; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.Security; -import java.security.UnrecoverableEntryException; -import java.security.UnrecoverableKeyException; -import java.security.cert.Certificate; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.time.LocalDateTime; -import java.util.Collections; -import java.util.Enumeration; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.concurrent.ConcurrentHashMap; - -import javax.crypto.KeyGenerator; -import javax.crypto.SecretKey; -import javax.security.auth.x500.X500Principal; - -import io.mosip.kernel.core.keymanager.exception.KeystoreProcessingException; -import io.mosip.kernel.core.keymanager.exception.NoSuchSecurityProviderException; -import io.mosip.kernel.core.keymanager.model.CertificateParameters; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.DateUtils; -import io.mosip.kernel.keygenerator.bouncycastle.constant.KeyGeneratorExceptionConstant; -import io.mosip.kernel.keymanager.hsm.constant.KeymanagerConstant; -import io.mosip.kernel.keymanager.hsm.constant.KeymanagerErrorCode; -import io.mosip.kernel.keymanagerservice.logger.KeymanagerLogger; -import io.mosip.kernel.keymanager.hsm.util.CertificateUtility; - - -/** - * HSM Keymanager implementation based on OpenDNSSEC that handles and stores - * its cryptographic keys via the PKCS#11 interface. This is a software - * implementation of a generic cryptographic device. SoftHSM can work with other - * cryptographic device because of the PKCS#11 interface. - * - * @author Mahammed Taheer - * @since 1.1.4 - * - */ -public class PKCS11KeyStoreImpl implements io.mosip.kernel.core.keymanager.spi.KeyStore { - - private static final Logger LOGGER = KeymanagerLogger.getLogger(PKCS11KeyStoreImpl.class); - - /** - * The type of keystore, e.g. PKCS11, BouncyCastleProvider - */ - private String keystoreType; - - /** - * Path of HSM PKCS11 config file - * - */ - private String configPath; - - /** - * The passkey for Keystore - */ - private String keystorePass; - - /** - * Symmetric key algorithm Name - */ - private String symmetricKeyAlgorithm; - - /** - * Symmetric key length - */ - private int symmetricKeyLength; - - /** - * Asymmetric key algorithm Name - */ - private String asymmetricKeyAlgorithm; - - /** - * Asymmetric key length - */ - private int asymmetricKeyLength; - - /** - * Certificate Signing Algorithm - * - */ - private String signAlgorithm; - - private boolean enableKeyReferenceCache; - - private Map privateKeyReferenceCache; - - private Map secretKeyReferenceCache; - - /** - * The Keystore instance - */ - private KeyStore keyStore; - - private Provider provider = null; - - private LocalDateTime lastProviderLoadedTime; - - private static final int PROVIDER_ALLOWED_RELOAD_INTERVEL_IN_SECONDS = 60; - - private static final int NO_OF_RETRIES = 3; - - private char[] keystorePwdCharArr = null; - - - public PKCS11KeyStoreImpl(Map params) throws Exception { - this.keystoreType = KeymanagerConstant.KEYSTORE_TYPE_PKCS11; - this.configPath = params.get(KeymanagerConstant.CONFIG_FILE_PATH); - this.keystorePass = params.get(KeymanagerConstant.PKCS11_KEYSTORE_PASSWORD); - this.symmetricKeyAlgorithm = params.get(KeymanagerConstant.SYM_KEY_ALGORITHM); - this.symmetricKeyLength = Integer.valueOf(params.get(KeymanagerConstant.SYM_KEY_SIZE)); - this.asymmetricKeyAlgorithm = params.get(KeymanagerConstant.ASYM_KEY_ALGORITHM); - this.asymmetricKeyLength = Integer.valueOf(params.get(KeymanagerConstant.ASYM_KEY_SIZE)); - this.signAlgorithm = params.get(KeymanagerConstant.CERT_SIGN_ALGORITHM); - this.enableKeyReferenceCache = Boolean.parseBoolean(params.get(KeymanagerConstant.FLAG_KEY_REF_CACHE)); - initKeystore(); - } - - private void initKeystore() { - initKeyReferenceCache(); - keystorePwdCharArr = getKeystorePwd(); - provider = setupProvider(configPath); - addProvider(provider); - this.keyStore = getKeystoreInstance(keystoreType, provider); - lastProviderLoadedTime = DateUtils.getUTCCurrentDateTime(); - } - - private char[] getKeystorePwd() { - if (keystorePass.trim().length() == 0){ - return null; - } - return keystorePass.toCharArray(); - } - - /** - * Setup a new SunPKCS11 provider - * - * @param configPath The path of config file or keyStore in case of bouncycastle - * provider - * @return Provider - */ - private synchronized Provider setupProvider(String configPath) { - - try { - Provider sunPKCS11Provider = Security.getProvider(KeymanagerConstant.SUN_PKCS11_PROVIDER); - if(sunPKCS11Provider == null) - throw new ProviderException("SunPKCS11 provider not found"); - return sunPKCS11Provider.configure(configPath); - } catch (ProviderException | InvalidParameterException providerException ) { - throw new NoSuchSecurityProviderException(KeymanagerErrorCode.INVALID_CONFIG_FILE.getErrorCode(), - KeymanagerErrorCode.INVALID_CONFIG_FILE.getErrorMessage(), providerException); - } - } - - /** - * Adds a provider to the next position available. - * - * If there is a security manager, the - * java.lang.SecurityManager.checkSecurityAccess method is called with the - * "insertProvider" permission target name to see if it's ok to add a new - * provider. If this permission check is denied, checkSecurityAccess is called - * again with the "insertProvider."+provider.getName() permission target name. - * If both checks are denied, a SecurityException is thrown. - * - * @param provider - * the provider to be added - */ - private void addProvider(Provider provider) { - - // removing the provider before adding to providers list to avoid collusion. - Security.removeProvider(provider.getName()); - if (-1 == Security.addProvider(provider)) { - throw new NoSuchSecurityProviderException(KeymanagerErrorCode.NO_SUCH_SECURITY_PROVIDER.getErrorCode(), - KeymanagerErrorCode.NO_SUCH_SECURITY_PROVIDER.getErrorMessage()); - } - } - - /** - * Returns a keystore object of the specified type. - * - * A new KeyStore object encapsulating the KeyStoreSpi implementation from the - * specified Provider object is returned. Note that the specified Provider - * object does not have to be registered in the provider list. - * - * Loads this KeyStore for PKCS11 instance. - * - * @param keystoreType - * the type of keystore - * @param provider - * provider - * @return a keystore object of the specified type. - */ - private KeyStore getKeystoreInstance(String keystoreType, Provider provider) { - KeyStore mosipKeyStore = null; - try { - mosipKeyStore = KeyStore.getInstance(keystoreType, provider); - mosipKeyStore.load(null, keystorePwdCharArr); - } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) { - throw new KeystoreProcessingException(KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorCode(), - KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorMessage() + e.getMessage(), e); - } - return mosipKeyStore; - } - - /* - * (non-Javadoc) - * - * @see io.mosip.kernel.core.keymanager.spi.SofthsmKeystore#getAllAlias() - */ - @Override - public List getAllAlias() { - Enumeration enumeration = null; - try { - enumeration = keyStore.aliases(); - } catch (KeyStoreException e) { - throw new KeystoreProcessingException(KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorCode(), - KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorMessage() + e.getMessage(), e); - } - return Collections.list(enumeration); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.kernel.core.keymanager.spi.SofthsmKeystore#getKey(java.lang.String) - */ - @Override - public Key getKey(String alias) { - Key key = null; - try { - key = keyStore.getKey(alias, keystorePwdCharArr); - } catch (UnrecoverableKeyException | KeyStoreException | NoSuchAlgorithmException e) { - throw new KeystoreProcessingException(KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorCode(), - KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorMessage() + e.getMessage(), e); - } - return key; - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.kernel.core.keymanager.spi.SofthsmKeystore#getAsymmetricKey(java. - * lang.String) - */ - @SuppressWarnings("findsecbugs:HARD_CODE_PASSWORD") - @Override - public PrivateKeyEntry getAsymmetricKey(String alias) { - PrivateKeyEntry privateKeyEntry = getPrivateKeyEntryFromCache(alias); - if(privateKeyEntry != null) - return privateKeyEntry; - - int i = 0; - boolean isException = false; - String expMessage = ""; - Exception exp = null; - do { - try { - if (keyStore.entryInstanceOf(alias, PrivateKeyEntry.class)) { - LOGGER.debug("sessionId", "KeyStoreImpl", "getAsymmetricKey", "alias is instanceof keystore"); - ProtectionParameter password = getPasswordProtection(); - privateKeyEntry = (PrivateKeyEntry) keyStore.getEntry(alias, password); - if (privateKeyEntry != null) { - LOGGER.debug("sessionId", "KeyStoreImpl", "getAsymmetricKey", "privateKeyEntry is not null"); - break; - } - } else { - throw new NoSuchSecurityProviderException(KeymanagerErrorCode.NO_SUCH_ALIAS.getErrorCode(), - KeymanagerErrorCode.NO_SUCH_ALIAS.getErrorMessage() + alias); - } - } catch (NoSuchAlgorithmException | UnrecoverableEntryException e) { - throw new KeystoreProcessingException(KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorCode(), - KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorMessage() + e.getMessage(), e); - } catch (KeyStoreException kse) { - isException = true; - expMessage = kse.getMessage(); - exp = kse; - LOGGER.debug("sessionId", "KeyStoreImpl", "getAsymmetricKey", expMessage); - } - if (isException) { - reloadProvider(); - isException = false; - } - } while (i++ < NO_OF_RETRIES); - if (Objects.isNull(privateKeyEntry)) { - LOGGER.debug("sessionId", "KeyStoreImpl", "getAsymmetricKey", "privateKeyEntry is null"); - throw new KeystoreProcessingException(KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorCode(), - KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorMessage() + expMessage, exp); - } - addPrivateKeyEntryToCache(alias, privateKeyEntry); - return privateKeyEntry; - } - - private synchronized void reloadProvider() { - LOGGER.info("sessionId", "KeyStoreImpl", "KeyStoreImpl", "reloading provider"); - if(DateUtils.getUTCCurrentDateTime().isBefore( - lastProviderLoadedTime.plusSeconds(PROVIDER_ALLOWED_RELOAD_INTERVEL_IN_SECONDS))) { - LOGGER.warn("sessionId", "KeyStoreImpl", "reloadProvider", - "Last time successful reload done on " + lastProviderLoadedTime.toString() + - ", so reloading not done before interval of " + - PROVIDER_ALLOWED_RELOAD_INTERVEL_IN_SECONDS + " sec"); - return; - } - String existingProviderName = null; - if (Objects.nonNull(provider)) - existingProviderName = provider.getName(); - provider = setupProvider(configPath); - if(existingProviderName != null) - Security.removeProvider(existingProviderName); - addProvider(provider); - this.keyStore = getKeystoreInstance(keystoreType, provider); - lastProviderLoadedTime = DateUtils.getUTCCurrentDateTime(); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.kernel.core.keymanager.spi.SofthsmKeystore#getPrivateKey(java.lang. - * String) - */ - @Override - public PrivateKey getPrivateKey(String alias) { - PrivateKeyEntry privateKeyEntry = getAsymmetricKey(alias); - return privateKeyEntry.getPrivateKey(); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.kernel.core.keymanager.spi.SofthsmKeystore#getPublicKey(java.lang. - * String) - */ - @Override - public PublicKey getPublicKey(String alias) { - PrivateKeyEntry privateKeyEntry = getAsymmetricKey(alias); - Certificate[] certificates = privateKeyEntry.getCertificateChain(); - return certificates[0].getPublicKey(); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.kernel.core.keymanager.spi.SofthsmKeystore#getCertificate(java.lang. - * String) - */ - @Override - public X509Certificate getCertificate(String alias) { - PrivateKeyEntry privateKeyEntry = getAsymmetricKey(alias); - X509Certificate[] certificates = (X509Certificate[]) privateKeyEntry.getCertificateChain(); - return certificates[0]; - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.kernel.core.keymanager.spi.SofthsmKeystore#getSymmetricKey(java.lang - * .String) - */ - @SuppressWarnings("findsecbugs:HARD_CODE_PASSWORD") - @Override - public SecretKey getSymmetricKey(String alias) { - SecretKey secretKey = getSecretKeyFromCache(alias); - if(secretKey != null) - return secretKey; - - int i = 0; - boolean isException = false; - String expMessage = ""; - Exception exp = null; - do { - try { - if (keyStore.entryInstanceOf(alias, SecretKeyEntry.class)) { - ProtectionParameter password = getPasswordProtection(); - SecretKeyEntry retrivedSecret = (SecretKeyEntry) keyStore.getEntry(alias, password); - secretKey = retrivedSecret.getSecretKey(); - if (secretKey != null) { - LOGGER.debug("sessionId", "KeyStoreImpl", "getSymmetricKey", "secretKey is not null"); - break; - } - } else { - throw new NoSuchSecurityProviderException(KeymanagerErrorCode.NO_SUCH_ALIAS.getErrorCode(), - KeymanagerErrorCode.NO_SUCH_ALIAS.getErrorMessage() + alias); - } - } catch (NoSuchAlgorithmException | UnrecoverableEntryException e) { - throw new KeystoreProcessingException(KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorCode(), - KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorMessage() + e.getMessage(), e); - } catch (KeyStoreException kse) { - isException = true; - expMessage = kse.getMessage(); - exp = kse; - LOGGER.debug("sessionId", "KeyStoreImpl", "getSymmetricKey", expMessage); - } - if (isException) { - reloadProvider(); - isException = false; - } - } while (i++ < NO_OF_RETRIES); - if (Objects.isNull(secretKey)) { - LOGGER.debug("sessionId", "KeyStoreImpl", "getSymmetricKey", "secretKey is null"); - throw new KeystoreProcessingException(KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorCode(), - KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorMessage() + expMessage, exp); - } - addSecretKeyToCache(alias, secretKey); - return secretKey; - } - - /* - * (non-Javadoc) - * - * @see io.mosip.kernel.core.keymanager.spi.SofthsmKeystore#deleteKey(java.lang. - * String) - */ - @Override - public void deleteKey(String alias) { - try { - keyStore.deleteEntry(alias); - } catch (KeyStoreException e) { - throw new KeystoreProcessingException(KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorCode(), - KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorMessage() + e.getMessage(), e); - } - } - - private void storeCertificate(String alias, Certificate[] chain, PrivateKey privateKey) { - PrivateKeyEntry privateKeyEntry = new PrivateKeyEntry(privateKey, chain); - ProtectionParameter password = getPasswordProtection(); - try { - keyStore.setEntry(alias, privateKeyEntry, password); - keyStore.store(null, keystorePwdCharArr); - } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) { - throw new KeystoreProcessingException(KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorCode(), - KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorMessage() + e.getMessage()); - } - - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.kernel.core.keymanager.spi.SofthsmKeystore#storeAsymmetricKey(java. - * security.KeyPair, java.lang.String) - */ - @SuppressWarnings("findsecbugs:HARD_CODE_PASSWORD") - @Override - public void generateAndStoreAsymmetricKey(String alias, String signKeyAlias, CertificateParameters certParams) { - KeyPair keyPair = null; - PrivateKey signPrivateKey = null; - X500Principal signerPrincipal = null; - if (Objects.nonNull(signKeyAlias)) { - PrivateKeyEntry signKeyEntry = getAsymmetricKey(signKeyAlias); - signPrivateKey = signKeyEntry.getPrivateKey(); - X509Certificate signCert = (X509Certificate) signKeyEntry.getCertificate(); - signerPrincipal = signCert.getSubjectX500Principal(); - keyPair = generateKeyPair(); // To avoid key generation in HSM. - } else { - keyPair = generateKeyPair(); - signPrivateKey = keyPair.getPrivate(); - } - X509Certificate x509Cert = CertificateUtility.generateX509Certificate(signPrivateKey, keyPair.getPublic(), certParams, - signerPrincipal, signAlgorithm, provider.getName()); - X509Certificate[] chain = new X509Certificate[] {x509Cert}; - storeCertificate(alias, chain, keyPair.getPrivate()); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.kernel.core.keymanager.spi.SofthsmKeystore#storeSymmetricKey(javax. - * crypto.SecretKey, java.lang.String) - */ - @SuppressWarnings("findsecbugs:HARD_CODE_PASSWORD") - @Override - public void generateAndStoreSymmetricKey(String alias) { - SecretKey secretKey = generateSymmetricKey(); - SecretKeyEntry secret = new SecretKeyEntry(secretKey); - ProtectionParameter password = getPasswordProtection(); - try { - keyStore.setEntry(alias, secret, password); - keyStore.store(null, keystorePwdCharArr); - } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) { - throw new KeystoreProcessingException(KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorCode(), - KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorMessage() + e.getMessage(), e); - } - } - - private KeyPair generateKeyPair() { - try { - KeyPairGenerator generator = KeyPairGenerator.getInstance(asymmetricKeyAlgorithm, provider); - SecureRandom random = new SecureRandom(); - generator.initialize(asymmetricKeyLength, random); - return generator.generateKeyPair(); - } catch (java.security.NoSuchAlgorithmException e) { - throw new io.mosip.kernel.core.exception.NoSuchAlgorithmException( - KeyGeneratorExceptionConstant.MOSIP_NO_SUCH_ALGORITHM_EXCEPTION.getErrorCode(), - KeyGeneratorExceptionConstant.MOSIP_NO_SUCH_ALGORITHM_EXCEPTION.getErrorMessage(), e); - } - } - - private SecretKey generateSymmetricKey() { - try { - KeyGenerator generator = KeyGenerator.getInstance(symmetricKeyAlgorithm, provider); - SecureRandom random = new SecureRandom(); - generator.init(symmetricKeyLength, random); - return generator.generateKey(); - } catch (java.security.NoSuchAlgorithmException e) { - throw new io.mosip.kernel.core.exception.NoSuchAlgorithmException( - KeyGeneratorExceptionConstant.MOSIP_NO_SUCH_ALGORITHM_EXCEPTION.getErrorCode(), - KeyGeneratorExceptionConstant.MOSIP_NO_SUCH_ALGORITHM_EXCEPTION.getErrorMessage(), e); - } - - } - - @Override - public void storeCertificate(String alias, PrivateKey privateKey, Certificate certificate) { - try { - PrivateKeyEntry privateKeyEntry = new PrivateKeyEntry(privateKey, new Certificate[] {certificate}); - ProtectionParameter password = getPasswordProtection(); - keyStore.setEntry(alias, privateKeyEntry, password); - keyStore.store(null, keystorePwdCharArr); - } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) { - throw new KeystoreProcessingException(KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorCode(), - KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorMessage() + e.getMessage(), e); - } - } - - @Override - public String getKeystoreProviderName() { - if (Objects.nonNull(keyStore)) { - return keyStore.getProvider().getName(); - } - throw new KeystoreProcessingException(KeymanagerErrorCode.KEYSTORE_NOT_INSTANTIATED.getErrorCode(), - KeymanagerErrorCode.KEYSTORE_NOT_INSTANTIATED.getErrorMessage()); - } - - private PasswordProtection getPasswordProtection() { - if (keystorePwdCharArr == null) { - return null; - } - return new PasswordProtection(keystorePwdCharArr); - } - - private void initKeyReferenceCache() { - if(!enableKeyReferenceCache) - return; - this.privateKeyReferenceCache = new ConcurrentHashMap<>(); - this.secretKeyReferenceCache = new ConcurrentHashMap<>(); - } - - private void addPrivateKeyEntryToCache(String alias, PrivateKeyEntry privateKeyEntry) { - if(!enableKeyReferenceCache) - return; - LOGGER.debug("sessionId", "KeyStoreImpl", "addPrivateKeyEntryToCache", - "Adding private key reference to map for alias " + alias); - this.privateKeyReferenceCache.put(alias, privateKeyEntry); - } - - private PrivateKeyEntry getPrivateKeyEntryFromCache(String alias) { - if(!enableKeyReferenceCache) - return null; - return this.privateKeyReferenceCache.get(alias); - } - - private void addSecretKeyToCache(String alias, SecretKey secretKey) { - if(!enableKeyReferenceCache) - return; - LOGGER.debug("sessionId", "KeyStoreImpl", "addSecretKeyToCache", - "Adding secretKey reference to map for alias " + alias); - this.secretKeyReferenceCache.put(alias, secretKey); - } - - private SecretKey getSecretKeyFromCache(String alias) { - if(!enableKeyReferenceCache) - return null; - return this.secretKeyReferenceCache.get(alias); - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanager/hsm/impl/pkcs/PKCS12KeyStoreImpl.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanager/hsm/impl/pkcs/PKCS12KeyStoreImpl.java deleted file mode 100644 index a99384f7b36..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanager/hsm/impl/pkcs/PKCS12KeyStoreImpl.java +++ /dev/null @@ -1,510 +0,0 @@ -package io.mosip.kernel.keymanager.hsm.impl.pkcs; - -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.security.Key; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.KeyStore; -import java.security.KeyStore.PasswordProtection; -import java.security.KeyStore.PrivateKeyEntry; -import java.security.KeyStore.ProtectionParameter; -import java.security.KeyStore.SecretKeyEntry; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.Provider; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.Security; -import java.security.UnrecoverableEntryException; -import java.security.UnrecoverableKeyException; -import java.security.cert.Certificate; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.util.Collections; -import java.util.Enumeration; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -import javax.crypto.KeyGenerator; -import javax.crypto.SecretKey; -import javax.security.auth.x500.X500Principal; - -import org.bouncycastle.jce.provider.BouncyCastleProvider; - -import io.mosip.kernel.core.keymanager.exception.KeystoreProcessingException; -import io.mosip.kernel.core.keymanager.exception.NoSuchSecurityProviderException; -import io.mosip.kernel.core.keymanager.model.CertificateParameters; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.keygenerator.bouncycastle.constant.KeyGeneratorExceptionConstant; -import io.mosip.kernel.keymanager.hsm.constant.KeymanagerConstant; -import io.mosip.kernel.keymanager.hsm.constant.KeymanagerErrorCode; -import io.mosip.kernel.keymanager.hsm.util.CertificateUtility; -import io.mosip.kernel.keymanagerservice.logger.KeymanagerLogger; - - -/** - * HSM Keymanager implementation based on OpenDNSSEC that handles and stores - * its cryptographic keys via the PKCS#11 interface. This is a software - * implementation of a generic cryptographic device. SoftHSM can work with other - * cryptographic device because of the PKCS#11 interface. - * - * @author Mahammed Taheer - * @since 1.1.4 - * - */ -public class PKCS12KeyStoreImpl implements io.mosip.kernel.core.keymanager.spi.KeyStore { - - private static final Logger LOGGER = KeymanagerLogger.getLogger(PKCS12KeyStoreImpl.class); - - /** - * The type of keystore, e.g. PKCS11, BouncyCastleProvider - */ - private String keystoreType; - - /** - * Path of PKCS12 file of the Keystore in case of bouncy castle - * provider - */ - private String p12FilePath; - - /** - * The passkey for Keystore - */ - private String keystorePass; - - /** - * Symmetric key algorithm Name - */ - private String symmetricKeyAlgorithm; - - /** - * Symmetric key length - */ - private int symmetricKeyLength; - - /** - * Asymmetric key algorithm Name - */ - private String asymmetricKeyAlgorithm; - - /** - * Asymmetric key length - */ - private int asymmetricKeyLength; - - /** - * Certificate Signing Algorithm - * - */ - private String signAlgorithm; - - /** - * The Keystore instance - */ - private KeyStore keyStore; - - private Provider provider = null; - - private char[] keystorePwdCharArr = null; - - - public PKCS12KeyStoreImpl(Map params) throws Exception { - this.keystoreType = KeymanagerConstant.KEYSTORE_TYPE_PKCS12; - this.p12FilePath = params.get(KeymanagerConstant.CONFIG_FILE_PATH); - this.keystorePass = params.get(KeymanagerConstant.PKCS11_KEYSTORE_PASSWORD); - this.symmetricKeyAlgorithm = params.get(KeymanagerConstant.SYM_KEY_ALGORITHM); - this.symmetricKeyLength = Integer.valueOf(params.get(KeymanagerConstant.SYM_KEY_SIZE)); - this.asymmetricKeyAlgorithm = params.get(KeymanagerConstant.ASYM_KEY_ALGORITHM); - this.asymmetricKeyLength = Integer.valueOf(params.get(KeymanagerConstant.ASYM_KEY_SIZE)); - this.signAlgorithm = params.get(KeymanagerConstant.CERT_SIGN_ALGORITHM); - initKeystore(); - } - - private void initKeystore() { - keystorePwdCharArr = getKeystorePwd(); - provider = setupProvider(); - addProvider(provider); - this.keyStore = getKeystoreInstance(keystoreType, p12FilePath, provider); - } - - private char[] getKeystorePwd() { - if (keystorePass.trim().length() == 0){ - throw new KeystoreProcessingException(KeymanagerErrorCode.NOT_VALID_STORE_PASSWORD.getErrorCode(), - KeymanagerErrorCode.NOT_VALID_STORE_PASSWORD.getErrorMessage()); - } - return keystorePass.toCharArray(); - } - - /** - * Setup a new SunPKCS11 provider - * - * @param configPath The path of config file or keyStore in case of bouncycastle - * provider - * @return Provider - */ - private Provider setupProvider() { - // Adding BC provider because Certificate creation algorithm is not support by Sun Provider. - return new BouncyCastleProvider(); - } - - /** - * Adds a provider to the next position available. - * - * If there is a security manager, the - * java.lang.SecurityManager.checkSecurityAccess method is called with the - * "insertProvider" permission target name to see if it's ok to add a new - * provider. If this permission check is denied, checkSecurityAccess is called - * again with the "insertProvider."+provider.getName() permission target name. - * If both checks are denied, a SecurityException is thrown. - * - * @param provider - * the provider to be added - */ - private void addProvider(Provider provider) { - - // removing the provider before adding to providers list to avoid collusion. - Security.removeProvider(provider.getName()); - if (-1 == Security.addProvider(provider)) { - throw new NoSuchSecurityProviderException(KeymanagerErrorCode.NO_SUCH_SECURITY_PROVIDER.getErrorCode(), - KeymanagerErrorCode.NO_SUCH_SECURITY_PROVIDER.getErrorMessage()); - } - } - - /** - * Returns a keystore object of the specified type. - * - * A new KeyStore object encapsulating the KeyStoreSpi implementation from the - * specified Provider object is returned. Note that the specified Provider - * object does not have to be registered in the provider list. - * - * Loads this KeyStore for PKCS11 instance. - * - * @param keystoreType - * the type of keystore - * @param provider - * provider - * @return a keystore object of the specified type. - */ - private KeyStore getKeystoreInstance(String keystoreType, String p12FilePath, Provider provider) { - KeyStore mosipKeyStore = null; - try { - // Not adding Provider because BC provider is not allowing to add symmetric key in keystore file. - mosipKeyStore = KeyStore.getInstance(keystoreType); - Path path = Paths.get(p12FilePath); - // if file is not available, it will get created when new key get created. - if (!Files.exists(path)){ - mosipKeyStore.load(null, keystorePwdCharArr); - } else { - InputStream p12FileStream = new FileInputStream(p12FilePath); - mosipKeyStore.load(p12FileStream, keystorePwdCharArr); - } - return mosipKeyStore; - } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) { - throw new KeystoreProcessingException(KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorCode(), - KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorMessage() + e.getMessage(), e); - } - } - - /* - * (non-Javadoc) - * - * @see io.mosip.kernel.core.keymanager.spi.SofthsmKeystore#getAllAlias() - */ - @Override - public List getAllAlias() { - Enumeration enumeration = null; - try { - enumeration = keyStore.aliases(); - } catch (KeyStoreException e) { - throw new KeystoreProcessingException(KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorCode(), - KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorMessage() + e.getMessage(), e); - } - return Collections.list(enumeration); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.kernel.core.keymanager.spi.SofthsmKeystore#getKey(java.lang.String) - */ - @Override - public Key getKey(String alias) { - Key key = null; - try { - key = keyStore.getKey(alias, keystorePwdCharArr); - } catch (UnrecoverableKeyException | KeyStoreException | NoSuchAlgorithmException e) { - throw new KeystoreProcessingException(KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorCode(), - KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorMessage() + e.getMessage(), e); - } - return key; - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.kernel.core.keymanager.spi.SofthsmKeystore#getAsymmetricKey(java. - * lang.String) - */ - @SuppressWarnings("findsecbugs:HARD_CODE_PASSWORD") - @Override - public PrivateKeyEntry getAsymmetricKey(String alias) { - - try { - if (keyStore.entryInstanceOf(alias, PrivateKeyEntry.class)) { - LOGGER.debug("sessionId", "KeyStoreImpl", "getAsymmetricKey", "alias is instanceof keystore"); - ProtectionParameter password = getPasswordProtection(); - return (PrivateKeyEntry) keyStore.getEntry(alias, password); - } else { - throw new NoSuchSecurityProviderException(KeymanagerErrorCode.NO_SUCH_ALIAS.getErrorCode(), - KeymanagerErrorCode.NO_SUCH_ALIAS.getErrorMessage() + alias); - } - } catch (NoSuchAlgorithmException | UnrecoverableEntryException | KeyStoreException e) { - throw new KeystoreProcessingException(KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorCode(), - KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorMessage() + e.getMessage(), e); - } - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.kernel.core.keymanager.spi.SofthsmKeystore#getPrivateKey(java.lang. - * String) - */ - @Override - public PrivateKey getPrivateKey(String alias) { - PrivateKeyEntry privateKeyEntry = getAsymmetricKey(alias); - return privateKeyEntry.getPrivateKey(); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.kernel.core.keymanager.spi.SofthsmKeystore#getPublicKey(java.lang. - * String) - */ - @Override - public PublicKey getPublicKey(String alias) { - PrivateKeyEntry privateKeyEntry = getAsymmetricKey(alias); - Certificate[] certificates = privateKeyEntry.getCertificateChain(); - return certificates[0].getPublicKey(); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.kernel.core.keymanager.spi.SofthsmKeystore#getCertificate(java.lang. - * String) - */ - @Override - public X509Certificate getCertificate(String alias) { - PrivateKeyEntry privateKeyEntry = getAsymmetricKey(alias); - X509Certificate[] certificates = (X509Certificate[]) privateKeyEntry.getCertificateChain(); - return certificates[0]; - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.kernel.core.keymanager.spi.SofthsmKeystore#getSymmetricKey(java.lang - * .String) - */ - @SuppressWarnings("findsecbugs:HARD_CODE_PASSWORD") - @Override - public SecretKey getSymmetricKey(String alias) { - - try { - if (keyStore.entryInstanceOf(alias, SecretKeyEntry.class)) { - ProtectionParameter password = getPasswordProtection(); - SecretKeyEntry retrivedSecret = (SecretKeyEntry) keyStore.getEntry(alias, password); - return retrivedSecret.getSecretKey(); - } else { - throw new NoSuchSecurityProviderException(KeymanagerErrorCode.NO_SUCH_ALIAS.getErrorCode(), - KeymanagerErrorCode.NO_SUCH_ALIAS.getErrorMessage() + alias); - } - } catch (NoSuchAlgorithmException | UnrecoverableEntryException | KeyStoreException e) { - throw new KeystoreProcessingException(KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorCode(), - KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorMessage() + e.getMessage(), e); - } - } - - /* - * (non-Javadoc) - * - * @see io.mosip.kernel.core.keymanager.spi.SofthsmKeystore#deleteKey(java.lang. - * String) - */ - @Override - public void deleteKey(String alias) { - try { - keyStore.deleteEntry(alias); - } catch (KeyStoreException e) { - throw new KeystoreProcessingException(KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorCode(), - KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorMessage() + e.getMessage(), e); - } - } - - /** - * Sets keystore - * - * @param keyStore - * keyStore - */ - public void setKeyStore(KeyStore keyStore) { - this.keyStore = keyStore; - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.kernel.core.keymanager.spi.SofthsmKeystore#storeAsymmetricKey(java. - * security.KeyPair, java.lang.String) - */ - @SuppressWarnings("findsecbugs:HARD_CODE_PASSWORD") - @Override - public void generateAndStoreAsymmetricKey(String alias, String signKeyAlias, CertificateParameters certParams) { - KeyPair keyPair = null; - PrivateKey signPrivateKey = null; - X500Principal signerPrincipal = null; - if (Objects.nonNull(signKeyAlias)) { - PrivateKeyEntry signKeyEntry = getAsymmetricKey(signKeyAlias); - signPrivateKey = signKeyEntry.getPrivateKey(); - X509Certificate signCert = (X509Certificate) signKeyEntry.getCertificate(); - signerPrincipal = signCert.getSubjectX500Principal(); - keyPair = generateKeyPair(); // To avoid key generation in HSM. - } else { - keyPair = generateKeyPair(); - signPrivateKey = keyPair.getPrivate(); - } - X509Certificate x509Cert = CertificateUtility.generateX509Certificate(signPrivateKey, keyPair.getPublic(), certParams, - signerPrincipal, signAlgorithm, provider.getName()); - X509Certificate[] chain = new X509Certificate[] {x509Cert}; - storeCertificate(alias, chain, keyPair.getPrivate()); - } - - private void storeCertificate(String alias, Certificate[] chain, PrivateKey privateKey) { - PrivateKeyEntry privateKeyEntry = new PrivateKeyEntry(privateKey, chain); - ProtectionParameter password = getPasswordProtection(); - try { - keyStore.setEntry(alias, privateKeyEntry, password); - storeKeyInFile(); - } catch (KeyStoreException e) { - throw new KeystoreProcessingException(KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorCode(), - KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorMessage() + e.getMessage()); - } - - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.kernel.core.keymanager.spi.SofthsmKeystore#storeSymmetricKey(javax. - * crypto.SecretKey, java.lang.String) - */ - @SuppressWarnings("findsecbugs:HARD_CODE_PASSWORD") - @Override - public void generateAndStoreSymmetricKey(String alias) { - SecretKey secretKey = generateSymmetricKey(); - SecretKeyEntry secret = new SecretKeyEntry(secretKey); - ProtectionParameter password = getPasswordProtection(); - try { - keyStore.setEntry(alias, secret, password); - storeKeyInFile(); - } catch (KeyStoreException e) { - throw new KeystoreProcessingException(KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorCode(), - KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorMessage() + e.getMessage(), e); - } - } - - private KeyPair generateKeyPair() { - try { - KeyPairGenerator generator = KeyPairGenerator.getInstance(asymmetricKeyAlgorithm); - SecureRandom random = new SecureRandom(); - generator.initialize(asymmetricKeyLength, random); - return generator.generateKeyPair(); - } catch (java.security.NoSuchAlgorithmException e) { - throw new io.mosip.kernel.core.exception.NoSuchAlgorithmException( - KeyGeneratorExceptionConstant.MOSIP_NO_SUCH_ALGORITHM_EXCEPTION.getErrorCode(), - KeyGeneratorExceptionConstant.MOSIP_NO_SUCH_ALGORITHM_EXCEPTION.getErrorMessage(), e); - } - } - - private SecretKey generateSymmetricKey() { - try { - KeyGenerator generator = KeyGenerator.getInstance(symmetricKeyAlgorithm, provider); - SecureRandom random = new SecureRandom(); - generator.init(symmetricKeyLength, random); - return generator.generateKey(); - } catch (java.security.NoSuchAlgorithmException e) { - throw new io.mosip.kernel.core.exception.NoSuchAlgorithmException( - KeyGeneratorExceptionConstant.MOSIP_NO_SUCH_ALGORITHM_EXCEPTION.getErrorCode(), - KeyGeneratorExceptionConstant.MOSIP_NO_SUCH_ALGORITHM_EXCEPTION.getErrorMessage(), e); - } - - } - - @Override - public void storeCertificate(String alias, PrivateKey privateKey, Certificate certificate) { - try { - PrivateKeyEntry privateKeyEntry = new PrivateKeyEntry(privateKey, new Certificate[] {certificate}); - ProtectionParameter password = getPasswordProtection(); - keyStore.setEntry(alias, privateKeyEntry, password); - storeKeyInFile(); - } catch (KeyStoreException e) { - throw new KeystoreProcessingException(KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorCode(), - KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorMessage() + e.getMessage(), e); - } - } - - @Override - public String getKeystoreProviderName() { - if (Objects.nonNull(keyStore)) { - return provider.getName(); - } - throw new KeystoreProcessingException(KeymanagerErrorCode.KEYSTORE_NOT_INSTANTIATED.getErrorCode(), - KeymanagerErrorCode.KEYSTORE_NOT_INSTANTIATED.getErrorMessage()); - } - - private PasswordProtection getPasswordProtection() { - if (keystorePwdCharArr == null) { - throw new KeystoreProcessingException(KeymanagerErrorCode.NOT_VALID_STORE_PASSWORD.getErrorCode(), - KeymanagerErrorCode.NOT_VALID_STORE_PASSWORD.getErrorMessage()); - } - return new PasswordProtection(keystorePwdCharArr); - } - - private void storeKeyInFile(){ - try { - Path parentPath = Paths.get(p12FilePath).getParent(); - // Creating the directories if not available. - if (parentPath != null && !Files.exists(parentPath)) { - Files.createDirectories(parentPath); - } - OutputStream outputStream = null; - if (keyStore.getType().equals(KeymanagerConstant.KEYSTORE_TYPE_PKCS12)) { - outputStream = new FileOutputStream(p12FilePath); - } - keyStore.store(outputStream, keystorePwdCharArr); - } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) { - throw new KeystoreProcessingException(KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorCode(), - KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorMessage() + e.getMessage(), e); - } - } - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanager/hsm/util/CertificateUtility.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanager/hsm/util/CertificateUtility.java deleted file mode 100644 index 48e6579b1d2..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanager/hsm/util/CertificateUtility.java +++ /dev/null @@ -1,191 +0,0 @@ -package io.mosip.kernel.keymanager.hsm.util; - -import java.io.IOException; -import java.math.BigInteger; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.util.Date; -import java.util.Objects; - -import javax.security.auth.x500.X500Principal; - -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.x500.X500Name; -import org.bouncycastle.asn1.x500.X500NameBuilder; -import org.bouncycastle.asn1.x500.style.BCStyle; -import org.bouncycastle.asn1.x500.style.RFC4519Style; -import org.bouncycastle.asn1.x509.BasicConstraints; -import org.bouncycastle.asn1.x509.Extension; -import org.bouncycastle.asn1.x509.KeyUsage; -import org.bouncycastle.cert.X509CertificateHolder; -import org.bouncycastle.cert.X509v3CertificateBuilder; -import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; -import org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils; -import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; -import org.bouncycastle.operator.ContentSigner; -import org.bouncycastle.operator.OperatorCreationException; -import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; - -import io.mosip.kernel.core.keymanager.exception.KeystoreProcessingException; -import io.mosip.kernel.core.keymanager.model.CertificateParameters; -import io.mosip.kernel.keymanager.hsm.constant.KeymanagerErrorCode; - -/** - * Certificate utility to generate and sign X509 Certificate - * - * @author Dharmesh Khandelwal - * @since 1.0.0 - * - */ -public class CertificateUtility { - - - /** - * Private constructor for CertificateUtility - */ - private CertificateUtility() { - } - - /** - * Generate and sign X509 Certificate - * - * @param keyPair the keypair - * @param commonName commonName - * @param organizationalUnit organizationalUnit - * @param organization organization - * @param country country - * @param validityFrom validityFrom - * @param validityTo validityTo - * @return The certificate - */ - public static X509Certificate generateX509Certificate(PrivateKey signPrivateKey, PublicKey publicKey, String commonName, String organizationalUnit, - String organization, String country, LocalDateTime validityFrom, LocalDateTime validityTo, String signAlgorithm, String providerName) { - - X500Name rootCertIssuer = new X500Name(getCertificateAttributes(commonName, organizationalUnit, organization, country)); - X500Name rootCertSubject = rootCertIssuer; - KeyUsage keyUsage = new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign); - BasicConstraints basicConstraints = new BasicConstraints(1); - if (rootCertSubject.equals(rootCertIssuer)) { - basicConstraints = new BasicConstraints(2); - } - return generateX509Certificate(signPrivateKey, publicKey, rootCertIssuer, rootCertSubject, signAlgorithm, providerName, - validityFrom, validityTo, keyUsage, basicConstraints); - } - - /** - * Generate and sign X509 Certificate - * - * @param signPrivateKey the private key for signing certificate - * @param publicKey the public key for generating certificate - * @param certParams the certificate parameters - * - * @return The certificate - */ - public static X509Certificate generateX509Certificate(PrivateKey signPrivateKey, PublicKey publicKey, CertificateParameters certParams, - X500Principal signerPrincipal, String signAlgorithm, String providerName) { - // Using RFC4519Style instance to preserve the RDN sequence because in certificate creation the RDN sequence is getting reversed. - X500Name certSubject = getCertificateAttributes(certParams); //new X500Name(RFC4519Style.INSTANCE, getCertificateAttributes(certParams)); - X500Name certIssuer = Objects.nonNull(signerPrincipal)? new X500Name(RFC4519Style.INSTANCE, signerPrincipal.getName()) : certSubject; - KeyUsage keyUsage = new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign); - BasicConstraints basicConstraints = new BasicConstraints(1); - if (certSubject.equals(certIssuer)) { - basicConstraints = new BasicConstraints(2); - } - return generateX509Certificate(signPrivateKey, publicKey, certIssuer, certSubject, signAlgorithm, providerName, - certParams.getNotBefore(), certParams.getNotAfter(), keyUsage, basicConstraints); - } - - private static X509Certificate generateX509Certificate(PrivateKey signPrivateKey, PublicKey publicKey, X500Name certIssuer, X500Name certSubject, - String signAlgorithm, String providerName, LocalDateTime notBefore, LocalDateTime notAfter, KeyUsage keyUsage, - BasicConstraints basicConstraints) { - try { - BigInteger certSerialNum = new BigInteger(Long.toString(new SecureRandom().nextLong())); - - ContentSigner certContentSigner = new JcaContentSignerBuilder(signAlgorithm).setProvider(providerName).build(signPrivateKey); - X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(certIssuer, certSerialNum, getDateFromLocalDateTime(notBefore), - getDateFromLocalDateTime(notAfter), certSubject, publicKey); - JcaX509ExtensionUtils certExtUtils = new JcaX509ExtensionUtils(); - certBuilder.addExtension(Extension.basicConstraints, true, basicConstraints); - certBuilder.addExtension(Extension.subjectKeyIdentifier, false, certExtUtils.createSubjectKeyIdentifier(publicKey)); - certBuilder.addExtension(Extension.keyUsage, true, keyUsage); - X509CertificateHolder certHolder = certBuilder.build(certContentSigner); - return new JcaX509CertificateConverter().getCertificate(certHolder); - } catch (OperatorCreationException|NoSuchAlgorithmException | CertificateException | IOException e) { - throw new KeystoreProcessingException(KeymanagerErrorCode.CERTIFICATE_PROCESSING_ERROR.getErrorCode(), - KeymanagerErrorCode.CERTIFICATE_PROCESSING_ERROR.getErrorMessage() + e.getMessage(), e); - } - } - - public static X509Certificate generateX509Certificate(PrivateKey signPrivateKey, PublicKey publicKey, CertificateParameters certParams, - X500Principal signerPrincipal, String signAlgorithm, String providerName, boolean encKeyUsage) { - - X500Name certSubject = getCertificateAttributes(certParams); - X500Name certIssuer = Objects.nonNull(signerPrincipal)? new X500Name(RFC4519Style.INSTANCE, signerPrincipal.getName()) : certSubject; - KeyUsage keyUsage = new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign); - if (encKeyUsage) { - keyUsage = new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.keyEncipherment); - } - BasicConstraints basicConstraints = new BasicConstraints(true); - return generateX509Certificate(signPrivateKey, publicKey, certIssuer, certSubject, signAlgorithm, providerName, - certParams.getNotBefore(), certParams.getNotAfter(), keyUsage, basicConstraints); - } - - public static X509Certificate generateX509Certificate(PrivateKey signPrivateKey, PublicKey publicKey, CertificateParameters certParams, - X500Principal signerPrincipal, String signAlgorithm, String providerName, String encryptionKey) { - - X500Name certSubject = getCertificateAttributes(certParams); - X500Name certIssuer = Objects.nonNull(signerPrincipal)? new X500Name(RFC4519Style.INSTANCE, signerPrincipal.getName()) : certSubject; - KeyUsage keyUsage = new KeyUsage(KeyUsage.keyEncipherment); - BasicConstraints basicConstraints = new BasicConstraints(false); - return generateX509Certificate(signPrivateKey, publicKey, certIssuer, certSubject, signAlgorithm, providerName, - certParams.getNotBefore(), certParams.getNotAfter(), keyUsage, basicConstraints); - } - - /** - * Converts the local date time to Date - * @param localDateTime - * @return - */ - private static Date getDateFromLocalDateTime(LocalDateTime localDateTime) { - return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()); - } - - /** - * Concatenates the cert attributes - * @param commonName - * @param organizationalUnit - * @param organization - * @param country - * @return - */ - private static String getCertificateAttributes(String commonName, String organizationalUnit, - String organization, String country ) { - return "CN=" + commonName + ", OU =" + organizationalUnit + ",O=" + organization + ", C=" + country; - } - - - private static X500Name getCertificateAttributes(CertificateParameters certParams) { - - /* return "CN=" + certParams.getCommonName() + ", OU =" + certParams.getOrganizationUnit() + ",O=" + certParams.getOrganization() - + ", L=" + certParams.getLocation() + ", ST=" + certParams.getState() + ", C=" + certParams.getCountry(); */ - X500NameBuilder builder = new X500NameBuilder(RFC4519Style.INSTANCE); - addRDN(certParams.getCountry(), builder, BCStyle.C); - addRDN(certParams.getState(), builder, BCStyle.ST); - addRDN(certParams.getLocation(), builder, BCStyle.L); - addRDN(certParams.getOrganization(), builder, BCStyle.O); - addRDN(certParams.getOrganizationUnit(), builder, BCStyle.OU); - addRDN(certParams.getCommonName(), builder, BCStyle.CN); - return builder.build(); - } - - private static void addRDN(String dnValue, X500NameBuilder builder, ASN1ObjectIdentifier identifier) { - if (dnValue != null && !dnValue.isEmpty()) - builder.addRDN(identifier, dnValue); - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/KeymanagerBootApplication.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/KeymanagerBootApplication.java deleted file mode 100644 index 2d28ca6c77e..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/KeymanagerBootApplication.java +++ /dev/null @@ -1,30 +0,0 @@ -package io.mosip.kernel.keymanagerservice; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -/** - * Key Manager Application - * - * @author Dharmesh Khandelwal - * @since 1.0.0 - * - */ -@SpringBootApplication(scanBasePackages = { "io.mosip.kernel.cryptomanager.*", "io.mosip.kernel.keymanagerservice.*", - "${mosip.auth.adapter.impl.basepackage}", "io.mosip.kernel.signature.*", "io.mosip.kernel.tokenidgenerator.*", - "io.mosip.kernel.lkeymanager.*", "io.mosip.kernel.keymanager.*", "io.mosip.kernel.keygenerator.*", - "io.mosip.kernel.crypto.*", "io.mosip.kernel.zkcryptoservice.*", "io.mosip.kernel.partnercertservice.*", - "io.mosip.kernel.clientcrypto.*", "io.mosip.kernel.core.logger.config", "io.mosip.kernel.keymigrate.*"}) -public class KeymanagerBootApplication { - - /** - * Main method to run spring boot application - * - * @param args args - */ - - public static void main(String[] args) { - - SpringApplication.run(KeymanagerBootApplication.class, args); - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/config/KeymanagerConfig.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/config/KeymanagerConfig.java deleted file mode 100644 index 76c0eb10755..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/config/KeymanagerConfig.java +++ /dev/null @@ -1,44 +0,0 @@ -package io.mosip.kernel.keymanagerservice.config; - -import javax.servlet.Filter; - -import org.springframework.boot.web.servlet.FilterRegistrationBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.filter.CommonsRequestLoggingFilter; - -/** - * Config class with beans for keymanager service and request logging - * - * @author Bal Vikash Sharma - * @since 1.0.0 - * - */ -@Configuration -public class KeymanagerConfig { - - @Bean - public FilterRegistrationBean registerReqResFilter() { - FilterRegistrationBean corsBean = new FilterRegistrationBean<>(); - corsBean.setFilter(getReqResFilter()); - corsBean.setOrder(1); - return corsBean; - } - - @Bean - public Filter getReqResFilter() { - return new ReqResFilter(); - } - - // TODO: Logging To Be removed - added temporarily - @Bean - public CommonsRequestLoggingFilter logFilter() { - CommonsRequestLoggingFilter filter = new CommonsRequestLoggingFilter(); - filter.setIncludeQueryString(true); - filter.setIncludePayload(true); - filter.setMaxPayloadLength(100000); - filter.setIncludeHeaders(true); - filter.setAfterMessagePrefix("REQUEST DATA : "); - return filter; - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/config/KeymanagerDaoConfig.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/config/KeymanagerDaoConfig.java deleted file mode 100644 index bffc1c9b75e..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/config/KeymanagerDaoConfig.java +++ /dev/null @@ -1,222 +0,0 @@ -package io.mosip.kernel.keymanagerservice.config; - -import java.util.HashMap; -import java.util.Map; - -import javax.sql.DataSource; - -import com.zaxxer.hikari.HikariConfig; -import com.zaxxer.hikari.HikariDataSource; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.BeanInstantiationException; -import org.springframework.beans.BeanUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Primary; -import org.springframework.core.env.Environment; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; -import org.springframework.orm.jpa.JpaDialect; -import org.springframework.orm.jpa.JpaTransactionManager; -import org.springframework.orm.jpa.JpaVendorAdapter; -import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; -import org.springframework.orm.jpa.vendor.HibernateJpaDialect; -import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; -import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.annotation.EnableTransactionManagement; - -import io.mosip.kernel.keymanagerservice.constant.HibernatePersistenceConstant; - - -@ConditionalOnProperty(value = "mosip.keymanager.dao.enabled", matchIfMissing = true) -@Configuration -@EnableTransactionManagement -@EnableJpaRepositories( - basePackages = {"io.mosip.kernel.keymanagerservice.repository", "io.mosip.kernel.lkeymanager.repository"}, - entityManagerFactoryRef = "keymanagerEntityManagerFactory", - transactionManagerRef = "keymanagerTransactionManager") -public class KeymanagerDaoConfig { - - @Autowired - private Environment environment; - - private static final Logger LOGGER = LoggerFactory.getLogger(KeymanagerDaoConfig.class); - - @Value("${keymanager.hikari.maximumPoolSize:25}") - private int maximumPoolSize; - @Value("${keymanager.hikari.validationTimeout:3000}") - private int validationTimeout; - @Value("${keymanager.hikari.connectionTimeout:60000}") - private int connectionTimeout; - @Value("${keymanager.hikari.idleTimeout:200000}") - private int idleTimeout; - @Value("${keymanager.hikari.minimumIdle:0}") - private int minimumIdle; - - @Primary - @Bean - public DataSource keymanagerDataSource() { - - HikariConfig hikariConfig = new HikariConfig(); - hikariConfig.setDriverClassName(environment.getProperty("keymanager.persistence.jdbc.driver")); - hikariConfig.setJdbcUrl(environment.getProperty("keymanager_database_url")); - hikariConfig.setUsername(environment.getProperty("keymanager_database_username")); - hikariConfig.setPassword(environment.getProperty("keymanager_database_password")); - if (environment.containsProperty(HibernatePersistenceConstant.KEYMANAGER_JDBC_SCHEMA)) { - hikariConfig.setSchema(environment.getProperty(HibernatePersistenceConstant.KEYMANAGER_JDBC_SCHEMA)); - } - hikariConfig.setMaximumPoolSize(maximumPoolSize); - hikariConfig.setValidationTimeout(validationTimeout); - hikariConfig.setConnectionTimeout(connectionTimeout); - hikariConfig.setIdleTimeout(idleTimeout); - hikariConfig.setMinimumIdle(minimumIdle); - - return new HikariDataSource(hikariConfig); - } - - /* - * (non-Javadoc) - * - * @see io.mosip.kernel.core.dao.config.BaseDaoConfig#entityManagerFactory() - */ - @Primary - @Bean - public LocalContainerEntityManagerFactoryBean keymanagerEntityManagerFactory() { - LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean(); - entityManagerFactory.setDataSource(keymanagerDataSource()); - entityManagerFactory.setPackagesToScan(new String [] - {"io.mosip.kernel.keymanagerservice.entity", - "io.mosip.kernel.lkeymanager.entity" }); - entityManagerFactory.setPersistenceUnitName(HibernatePersistenceConstant.HIBERNATE); - entityManagerFactory.setJpaPropertyMap(keymanagerJpaProperties()); - entityManagerFactory.setJpaVendorAdapter(keymanagerJpaVendorAdapter()); - entityManagerFactory.setJpaDialect(keymanagerJpaDialect()); - return entityManagerFactory; - } - - /* - * (non-Javadoc) - * - * @see io.mosip.kernel.core.dao.config.BaseDaoConfig#jpaVendorAdapter() - */ - @Primary - @Bean - public JpaVendorAdapter keymanagerJpaVendorAdapter() { - HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); - vendorAdapter.setGenerateDdl(true); - vendorAdapter.setShowSql(true); - return vendorAdapter; - } - - /* - * (non-Javadoc) - * - * @see io.mosip.kernel.core.dao.config.BaseDaoConfig#jpaDialect() - */ - @Primary - @Bean - public JpaDialect keymanagerJpaDialect() { - return new HibernateJpaDialect(); - } - - /* - * (non-Javadoc) - * - * @see io.mosip.kernel.core.dao.config.BaseDaoConfig#transactionManager(javax. - * persistence.EntityManagerFactory) - */ - @Primary - @Bean - public PlatformTransactionManager keymanagerTransactionManager() { - JpaTransactionManager jpaTransactionManager = new JpaTransactionManager(); - jpaTransactionManager.setEntityManagerFactory(keymanagerEntityManagerFactory().getObject()); - jpaTransactionManager.setDataSource(keymanagerDataSource()); - jpaTransactionManager.setJpaDialect(keymanagerJpaDialect()); - return jpaTransactionManager; - } - - /* - * (non-Javadoc) - * - * @see io.mosip.kernel.core.dao.config.BaseDaoConfig#jpaProperties() - */ - public Map keymanagerJpaProperties() { - HashMap jpaProperties = new HashMap<>(); - getProperty(jpaProperties, HibernatePersistenceConstant.HIBERNATE_HBM2DDL_AUTO, - HibernatePersistenceConstant.UPDATE); - getProperty(jpaProperties, HibernatePersistenceConstant.HIBERNATE_DIALECT, - HibernatePersistenceConstant.MY_SQL5_DIALECT); - getProperty(jpaProperties, HibernatePersistenceConstant.HIBERNATE_SHOW_SQL, HibernatePersistenceConstant.TRUE); - getProperty(jpaProperties, HibernatePersistenceConstant.HIBERNATE_FORMAT_SQL, - HibernatePersistenceConstant.TRUE); - getProperty(jpaProperties, HibernatePersistenceConstant.HIBERNATE_CONNECTION_CHAR_SET, - HibernatePersistenceConstant.UTF8); - getProperty(jpaProperties, HibernatePersistenceConstant.HIBERNATE_CACHE_USE_SECOND_LEVEL_CACHE, - HibernatePersistenceConstant.FALSE); - getProperty(jpaProperties, HibernatePersistenceConstant.HIBERNATE_CACHE_USE_QUERY_CACHE, - HibernatePersistenceConstant.FALSE); - getProperty(jpaProperties, HibernatePersistenceConstant.HIBERNATE_CACHE_USE_STRUCTURED_ENTRIES, - HibernatePersistenceConstant.FALSE); - getProperty(jpaProperties, HibernatePersistenceConstant.HIBERNATE_GENERATE_STATISTICS, - HibernatePersistenceConstant.FALSE); - getProperty(jpaProperties, HibernatePersistenceConstant.HIBERNATE_NON_CONTEXTUAL_CREATION, - HibernatePersistenceConstant.FALSE); - getProperty(jpaProperties, HibernatePersistenceConstant.HIBERNATE_CURRENT_SESSION_CONTEXT, - HibernatePersistenceConstant.JTA); - getProperty(jpaProperties, HibernatePersistenceConstant.HIBERNATE_EJB_INTERCEPTOR, - HibernatePersistenceConstant.EMPTY_INTERCEPTOR); - return jpaProperties; - } - -// @Bean -// public RestTemplate restTemplate() -// { -// return new RestTemplate(); -// } -// @Profile("!test") -// @Bean -// public EncryptionInterceptor encryptionInterceptor() { -// return new EncryptionInterceptor(); -// } - - /** - * Function to associate the specified value with the specified key in the map. - * If the map previously contained a mapping for the key, the old value is - * replaced. - * - * @param jpaProperties The map of jpa properties - * @param property The property whose value is to be set - * @param defaultValue The default value to set - * @return The map of jpa properties with properties set - */ - private HashMap getProperty(HashMap jpaProperties, String property, - String defaultValue) { - /** - * if property found in properties file then add that interceptor to the jpa - * properties. - */ - if (property.equals(HibernatePersistenceConstant.HIBERNATE_EJB_INTERCEPTOR)) { - try { - if (environment.containsProperty(property)) { - jpaProperties.put(property, - // encryptionInterceptor()); - BeanUtils.instantiateClass(Class.forName(environment.getProperty(property)))); - } - /** - * We can add a default interceptor whenever we require here. - */ - } catch (BeanInstantiationException | ClassNotFoundException e) { - LOGGER.error("Error while configuring Interceptor."); - } - } else { - jpaProperties.put(property, - environment.containsProperty(property) ? environment.getProperty(property) : defaultValue); - } - return jpaProperties; - } - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/config/LoggerConfiguration.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/config/LoggerConfiguration.java deleted file mode 100644 index ae6e6223f7a..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/config/LoggerConfiguration.java +++ /dev/null @@ -1,30 +0,0 @@ -package io.mosip.kernel.keymanagerservice.config; - -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.logger.logback.appender.ConsoleAppender; -import io.mosip.kernel.logger.logback.factory.Logfactory; - -/** - * Console Logger Configuration. - * - * @author Bal Vikash Sharma - * @since 1.0.0 - * - */ -public class LoggerConfiguration { - /** - * Private Constructor to prevent instantiation. - */ - private LoggerConfiguration() { - } - - /** - * This method sets the logger target, and returns appender. - * - * @param clazz the class. - * @return the appender. - */ - public static Logger logConfig(Class clazz) { - return Logfactory.getSlf4jLogger(clazz); - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/config/ReqResFilter.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/config/ReqResFilter.java deleted file mode 100644 index 129adf4ee6a..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/config/ReqResFilter.java +++ /dev/null @@ -1,54 +0,0 @@ -package io.mosip.kernel.keymanagerservice.config; - -import java.io.IOException; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.springframework.web.util.ContentCachingRequestWrapper; -import org.springframework.web.util.ContentCachingResponseWrapper; - -/** - * This class is for input logging of all parameters in HTTP requests - * - * @author Bal Vikash Sharma - * - */ -public class ReqResFilter implements Filter { - - @Override - public void init(FilterConfig filterConfig) throws ServletException { - // init method overriding - } - - @Override - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) - throws IOException, ServletException { - HttpServletRequest httpServletRequest = (HttpServletRequest) request; - HttpServletResponse httpServletResponse = (HttpServletResponse) response; - ContentCachingRequestWrapper requestWrapper = null; - ContentCachingResponseWrapper responseWrapper = null; - - // Default processing for url ends with .stream - if (httpServletRequest.getRequestURI().endsWith(".stream")) { - chain.doFilter(request, response); - return; - } - requestWrapper = new ContentCachingRequestWrapper(httpServletRequest); - responseWrapper = new ContentCachingResponseWrapper(httpServletResponse); - chain.doFilter(requestWrapper, responseWrapper); - responseWrapper.copyBodyToResponse(); - - } - - @Override - public void destroy() { - // Auto-generated method stub - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/config/ResponseBodyAdviceConfig.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/config/ResponseBodyAdviceConfig.java deleted file mode 100644 index 10e65f7ce1a..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/config/ResponseBodyAdviceConfig.java +++ /dev/null @@ -1,96 +0,0 @@ -package io.mosip.kernel.keymanagerservice.config; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletRequestWrapper; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.MethodParameter; -import org.springframework.http.MediaType; -import org.springframework.http.converter.HttpMessageConverter; -import org.springframework.http.server.ServerHttpRequest; -import org.springframework.http.server.ServerHttpResponse; -import org.springframework.http.server.ServletServerHttpRequest; -import org.springframework.web.bind.annotation.RestControllerAdvice; -import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; -import org.springframework.web.util.ContentCachingRequestWrapper; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; - -import io.mosip.kernel.core.http.RequestWrapper; -import io.mosip.kernel.core.http.ResponseFilter; -import io.mosip.kernel.core.http.ResponseWrapper; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.EmptyCheckUtils; - -/** - * @author Bal Vikash Sharma - * - */ -@RestControllerAdvice -public class ResponseBodyAdviceConfig implements ResponseBodyAdvice> { - - private static final Logger mosipLogger = LoggerConfiguration.logConfig(ResponseBodyAdviceConfig.class); - - - @Autowired - private ObjectMapper objectMapper; - - /* - * (non-Javadoc) - * - * @see - * org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice# - * supports(org.springframework.core.MethodParameter, java.lang.Class) - */ - @Override - public boolean supports(MethodParameter returnType, Class> converterType) { - return returnType.hasMethodAnnotation(ResponseFilter.class); - } - - /* - * (non-Javadoc) - * - * @see - * org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice# - * beforeBodyWrite(java.lang.Object, org.springframework.core.MethodParameter, - * org.springframework.http.MediaType, java.lang.Class, - * org.springframework.http.server.ServerHttpRequest, - * org.springframework.http.server.ServerHttpResponse) - */ - @Override - public ResponseWrapper beforeBodyWrite(ResponseWrapper body, MethodParameter returnType, - MediaType selectedContentType, Class> selectedConverterType, - ServerHttpRequest request, ServerHttpResponse response) { - - RequestWrapper requestWrapper = null; - String requestBody = null; - - try { - HttpServletRequest httpServletRequest = ((ServletServerHttpRequest) request).getServletRequest(); - - if (httpServletRequest instanceof ContentCachingRequestWrapper) { - requestBody = new String(((ContentCachingRequestWrapper) httpServletRequest).getContentAsByteArray()); - } else if (httpServletRequest instanceof HttpServletRequestWrapper - && ((HttpServletRequestWrapper) httpServletRequest) - .getRequest() instanceof ContentCachingRequestWrapper) { - requestBody = new String( - ((ContentCachingRequestWrapper) ((HttpServletRequestWrapper) httpServletRequest).getRequest()) - .getContentAsByteArray()); - } - - objectMapper.registerModule(new JavaTimeModule()); - if (!EmptyCheckUtils.isNullEmpty(requestBody)) { - requestWrapper = objectMapper.readValue(requestBody, RequestWrapper.class); - body.setId(requestWrapper.getId()); - body.setVersion(requestWrapper.getVersion()); - } - body.setErrors(null); - return body; - } catch (Exception e) { - mosipLogger.error("", "", "", e.getMessage()); - } - return body; - } - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/config/SwaggerConfig.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/config/SwaggerConfig.java deleted file mode 100644 index d3b4b80786a..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/config/SwaggerConfig.java +++ /dev/null @@ -1,113 +0,0 @@ -package io.mosip.kernel.keymanagerservice.config; - -import java.net.MalformedURLException; -import java.net.URL; -import java.util.HashSet; -import java.util.Set; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import springfox.documentation.builders.ApiInfoBuilder; -import springfox.documentation.builders.PathSelectors; -import springfox.documentation.builders.RequestHandlerSelectors; -import springfox.documentation.service.ApiInfo; -import springfox.documentation.service.Tag; -import springfox.documentation.spi.DocumentationType; -import springfox.documentation.spring.web.plugins.Docket; -import springfox.documentation.swagger2.annotations.EnableSwagger2; - -/** - * Configuration class for swagger config - * - * @author Dharmesh Khandelwal - * @since 1.0.0 - * - */ -@Configuration -@EnableSwagger2 -public class SwaggerConfig { - - private static final Logger logger = LoggerFactory.getLogger(SwaggerConfig.class); - - /** - * Master service Version - */ - private static final String KEYMANAGER_SERVICE_VERSION = "1.0"; - /** - * Application Title - */ - private static final String TITLE = "Key Manager Service"; - /** - * Master Data Service - */ - private static final String DISCRIPTION = "Key Manager Service for Security"; - - @Value("${application.env.local:false}") - private Boolean localEnv; - - @Value("${swagger.base-url:#{null}}") - private String swaggerBaseUrl; - - @Value("${server.port:8080}") - private int serverPort; - - String proto = "http"; - String host = "localhost"; - int port = -1; - String hostWithPort = "localhost:8080"; - - /** - * Produces {@link ApiInfo} - * - * @return {@link ApiInfo} - */ - private ApiInfo apiInfo() { - return new ApiInfoBuilder().title(TITLE).description(DISCRIPTION).version(KEYMANAGER_SERVICE_VERSION).build(); - } - - /** - * Produce Docket bean - * - * @return Docket bean - */ - @Bean - public Docket api() { - boolean swaggerBaseUrlSet = false; - if (!localEnv && swaggerBaseUrl != null && !swaggerBaseUrl.isEmpty()) { - try { - proto = new URL(swaggerBaseUrl).getProtocol(); - host = new URL(swaggerBaseUrl).getHost(); - port = new URL(swaggerBaseUrl).getPort(); - if (port == -1) { - hostWithPort = host; - } else { - hostWithPort = host + ":" + port; - } - swaggerBaseUrlSet = true; - } catch (MalformedURLException e) { - logger.error("SwaggerUrlException: ", e); - } - } - - Docket docket = new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()) - .tags(new Tag("keymanager", "Operations related to keymanagement and interaction with Softhsm/real HSM for Key Generation.")) - .groupName(TITLE).select().apis(RequestHandlerSelectors.any()) - .paths(PathSelectors.regex("(?!/(error).*).*")).build(); - - if (swaggerBaseUrlSet) { - docket.protocols(protocols()).host(hostWithPort); - logger.info("Swagger Base URL: {}://{}", proto, hostWithPort); - } - return docket; - } - - private Set protocols() { - Set protocols = new HashSet<>(); - protocols.add(proto); - return protocols; - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/constant/HibernatePersistenceConstant.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/constant/HibernatePersistenceConstant.java deleted file mode 100644 index 691330151f5..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/constant/HibernatePersistenceConstant.java +++ /dev/null @@ -1,121 +0,0 @@ -package io.mosip.kernel.keymanagerservice.constant; - -/** - * @author Dharmesh Khandelwal - * @since 1.0.0 - * - */ -public class HibernatePersistenceConstant { - - /** - * Private constructor for HibernatePersistenceConstants - */ - private HibernatePersistenceConstant() { - } - - /** - - /** - * The string constant jdbc schema - */ - public static final String KEYMANAGER_JDBC_SCHEMA = "keymanager.persistence.jdbc.schema"; - - /** - * The string constant jdbc schema - */ - public static final String LKEYMANAGER_JDBC_SCHEMA = "licensekeymanager.persistence.jdbc.schema"; - - /** - * The string constant cache query property - */ - public static final String CACHE_QUERY_PROPERTY = "javax.persistence.cache.storeMode"; - /** - * The string constant my sql dialect - */ - public static final String MY_SQL5_DIALECT = "org.hibernate.dialect.MySQL5Dialect"; - /** - * The string constant my sql dialect - */ - public static final String POSTGRESQL_95_DIALECT = "org.hibernate.dialect.PostgreSQL95Dialect"; - /** - * The string constant for hibernate statistics - */ - public static final String HIBERNATE_GENERATE_STATISTICS = "hibernate.generate_statistics"; - /** - * The string constant for use_structured_entries - */ - public static final String HIBERNATE_CACHE_USE_STRUCTURED_ENTRIES = "hibernate.cache.use_structured_entries"; - /** - * The string constant for use_query_cache - */ - public static final String HIBERNATE_CACHE_USE_QUERY_CACHE = "hibernate.cache.use_query_cache"; - /** - * The string constant for use_second_level_cache - */ - public static final String HIBERNATE_CACHE_USE_SECOND_LEVEL_CACHE = "hibernate.cache.use_second_level_cache"; - /** - * The string constant for charSet - */ - public static final String HIBERNATE_CONNECTION_CHAR_SET = "hibernate.connection.charSet"; - /** - * The string constant for format_sql - */ - public static final String HIBERNATE_FORMAT_SQL = "hibernate.format_sql"; - /** - * The string constant for show_sql - */ - public static final String HIBERNATE_SHOW_SQL = "hibernate.show_sql"; - /** - * The string constant for dialect - */ - public static final String HIBERNATE_DIALECT = "hibernate.dialect"; - /** - * The string constant for hbm2ddl - */ - public static final String HIBERNATE_HBM2DDL_AUTO = "hibernate.hbm2ddl.auto"; - /** - * The string constant for non_contextual_creation - */ - public static final String HIBERNATE_NON_CONTEXTUAL_CREATION = "hibernate.jdbc.lob.non_contextual_creation"; - /** - * The string constant for current_session_context_class - */ - public static final String HIBERNATE_CURRENT_SESSION_CONTEXT = "hibernate.current_session_context_class"; - - - - /** - * The string constant false - */ - public static final String FALSE = "false"; - /** - * The string constant utf8 - */ - public static final String UTF8 = "utf8"; - /** - * The string constant true - */ - public static final String TRUE = "true"; - - /** - * The string constant update - */ - public static final String UPDATE = "update"; - /** - * The string constant jta - */ - public static final String JTA = "jta"; - /** - * The string constant hibernate - */ - public static final String HIBERNATE = "hibernate"; - /** - * - */ - public static final String HIBERNATE_EJB_INTERCEPTOR = "hibernate.ejb.interceptor"; - /** - * - */ - public static final String EMPTY_INTERCEPTOR = "hibernate.empty.interceptor"; - -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/constant/KeymanagerConstant.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/constant/KeymanagerConstant.java deleted file mode 100644 index 550af7dba32..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/constant/KeymanagerConstant.java +++ /dev/null @@ -1,179 +0,0 @@ -package io.mosip.kernel.keymanagerservice.constant; - -/** - * Constants for Keymanager - * - * @author Dharmesh Khandelwal - * @since 1.0.0 - * - */ -public class KeymanagerConstant { - - /** - * Private constructor for KeyManagerConstant - */ - private KeymanagerConstant() { - } - - /** - * The constant Whitespace - */ - public static final String WHITESPACE = " "; - - /** - * The constant EMPTY - */ - public static final String EMPTY = ""; - - /** - * The constant keyalias - */ - public static final String KEYALIAS = "keyAlias"; - - /** - * The constant currentkeyalias - */ - public static final String CURRENTKEYALIAS = "currentKeyAlias"; - - /** - * The constant timestamp - */ - public static final String TIMESTAMP = "timestamp"; - - /** - * The constant sessionID - */ - public static final String SESSIONID = "sessionId"; - - /** - * The constant applicationId - */ - public static final String APPLICATIONID = "applicationId"; - - /** - * The constant referenceId - */ - public static final String REFERENCEID = "referenceId"; - - /** - * The constant Request received to getPublicKey - */ - public static final String GET_CERTIFICATE = "Request received to getCertificate"; - - /** - * The constant Getting public key from DB Store - */ - public static final String GETPUBLICKEYDB = "Getting public key from DB Store"; - - /** - * The constant Getting public key from SoftHSM - */ - public static final String GETPUBLICKEYHSM = "Getting Certificate from KeyStore."; - - /** - * The constant Getting key alias - */ - public static final String GETALIAS = "Getting key alias"; - - /** - * The constant Getting expiry policy - */ - public static final String GETEXPIRYPOLICY = "Getting expiry policy"; - - /** - * The constant Request received to decryptSymmetricKey - */ - public static final String DECRYPTKEY = "Request received to decryptSymmetricKey"; - - /** - * The constant Getting private key - */ - public static final String GETPRIVATEKEY = "Getting private key"; - - /** - * The constant Storing key in KeyAlias - */ - public static final String STOREKEYALIAS = "Storing key in KeyAlias"; - - /** - * The constant Storing key in dbKeyStore - */ - public static final String STOREDBKEY = "Storing key in dbKeyStore"; - - /** - * The constant keyFromDBStore - */ - public static final String KEYFROMDB = "keyFromDBStore"; - - /** - * The constant keyPolicy - */ - public static final String KEYPOLICY = "keyPolicy"; - - /** - * The constant symmetricKeyRequestDto - */ - public static final String SYMMETRICKEYREQUEST = "symmetricKeyRequestDto"; - - /** - * The constant fetchedKeyAlias - */ - public static final String FETCHEDKEYALIAS = "fetchedKeyAlias"; - - /** - * The constant dbKeyStore - */ - public static final String DBKEYSTORE = "dbKeyStore"; - - /** - * The constant RSA - */ - public static final String RSA = "RSA"; - - /** - * The constant INVALID_REQUEST - */ - public static final String INVALID_REQUEST = "should not be null or empty"; - - public static final String STORECERTIFICATE = "Storing certificate"; - - /** - * The constant INVALID_REQUEST - */ - public static final String REQUEST_FOR_MASTER_KEY_GENERATION = "Request for Master Key Generation"; - - public static final String REQUEST_TYPE_CERTIFICATE = "CERTIFICATE"; - - public static final String REQUEST_TYPE_CSR = "CSR"; - - public static final String ROOT_KEY = "Root Key"; - - public static final String CERTIFICATE_TYPE = "X.509"; - - public static final String BASE_KEY_POLICY_CONST = "BASE"; - - public static final String UPLOAD_SUCCESS = "Upload Success"; - - public static final String CERTIFICATE_PARSE = "CERTIFICATE_PARSE"; - - /** - * The constant KeyStore PrivateKey NotAvailable - */ - public static final String KS_PK_NA = "NA"; - - public static final String ROOT = "ROOT"; - - public static final String REQ_SYM_KEY_GEN = "Request for Symmetric Key Generation."; - - public static final int SYMMETRIC_KEY_VALIDITY = 365 * 10; - - public static final String GENERATE_SUCCESS = "Generation Success"; - - public static final String SYMM_KEY_EXISTS = "Key Exists."; - - public static final String REQ_REV_KEY = "Request for key revocation."; - - public static final String KEY_REVOKED = "Key Revoked"; - - public static final String ENCRYPTION_KEY = "EncryptionKey"; -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/constant/KeymanagerErrorConstant.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/constant/KeymanagerErrorConstant.java deleted file mode 100644 index 9b493a34c28..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/constant/KeymanagerErrorConstant.java +++ /dev/null @@ -1,88 +0,0 @@ -package io.mosip.kernel.keymanagerservice.constant; - -/** - * This ENUM provides all the constant identified for Keymanager Service errors. - * - * @author Dharmesh Khandelwal - * @version 1.0.0 - * - */ -public enum KeymanagerErrorConstant { - - VALIDITY_CHECK_FAIL("KER-KMS-001", "Certificate is not valid"), - - APPLICATIONID_NOT_VALID("KER-KMS-002", "ApplicationId not found in Key Policy"), - - NO_UNIQUE_ALIAS("KER-KMS-003", "No unique alias is found"), - - NO_SUCH_ALGORITHM_EXCEPTION("KER-KMS-004", "No Such algorithm is supported"), - - INVALID_REQUEST("KER-KMS-005", "Invalid request"), - - DATE_TIME_PARSE_EXCEPTION("KER-KMS-006", "timestamp should be in ISO 8601 format yyyy-MM-ddTHH::mm:ss.SSSZ"), - - CRYPTO_EXCEPTION("KER-KMS-007", "Exception occured in cypto library: "), - - KEY_STORE_EXCEPTION("KER-KMS-008", "Service is not able to store sign certificate"), - - INVALID_RESPONSE_TYPE("KER-KMS-009", "Invalid Response Object Type."), - - REFERENCE_ID_NOT_SUPPORTED("KER-KMS-010", "Reference Id Not Supported for the Application ID."), - - ROOT_KEY_NOT_FOUND("KER-KMS-011", "Root Key not available to sign."), - - KEY_GENERATION_NOT_DONE("KER-KMS-012", "Key Generation Process is not completed."), - - CERTIFICATE_PARSING_ERROR("KER-KMS-013", "Certificate Parsing Error."), - - KEY_NOT_MATCHING("KER-KMS-014", "Certificate Key Not Matching with stored Key."), - - UPLOAD_NOT_ALLOWED("KER-KMS-015", "Upload of certificate will not be allowed to update other domain certificate."), - - GENERATION_NOT_ALLOWED("KER-KMS-016", "Not allowed to generate new key pair for other domains."), - - CERTIFICATE_NOT_FOUND("KER-KMS-017", "Certificate Not found in keystore table."), - - DECRYPTION_NOT_ALLOWED("KER-KMS-018", "Not Allowed to perform decryption with other domain key."), - - SYMMETRIC_KEY_DECRYPTION_FAILED("KER-KMS-019", "Not able to decrypt Symmetric Key using the Private Key."), - - NOT_VALID_SIGNATURE_KEY("KER-KMS-020", "Signing operation for allowed for the provided application id & reference id."), - - REVOKE_NOT_ALLOWED("KER-KMS-021", "Key Revocation not allowed."), - - INTERNAL_SERVER_ERROR("KER-KMS-500", "Internal server error"); - - /** - * The error code. - */ - private final String errorCode; - - /** - * The error message. - */ - private final String errorMessage; - - /** - * @param errorCode The error code to be set. - * @param errorMessage The error message to be set. - */ - private KeymanagerErrorConstant(String errorCode, String errorMessage) { - this.errorCode = errorCode; - this.errorMessage = errorMessage; - } - - /** - * @return The error code. - */ - public String getErrorCode() { - return errorCode; - } - - /** - * @return The error message. - */ - public String getErrorMessage() { - return errorMessage; - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/controller/KeymanagerController.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/controller/KeymanagerController.java deleted file mode 100644 index dd1652abf72..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/controller/KeymanagerController.java +++ /dev/null @@ -1,175 +0,0 @@ -package io.mosip.kernel.keymanagerservice.controller; - -import java.util.Optional; - -import javax.validation.Valid; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.CrossOrigin; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -import io.mosip.kernel.core.http.RequestWrapper; -import io.mosip.kernel.core.http.ResponseFilter; -import io.mosip.kernel.core.http.ResponseWrapper; -import io.mosip.kernel.keymanagerservice.dto.CSRGenerateRequestDto; -import io.mosip.kernel.keymanagerservice.dto.KeyPairGenerateRequestDto; -import io.mosip.kernel.keymanagerservice.dto.KeyPairGenerateResponseDto; -import io.mosip.kernel.keymanagerservice.dto.RevokeKeyRequestDto; -import io.mosip.kernel.keymanagerservice.dto.RevokeKeyResponseDto; -import io.mosip.kernel.keymanagerservice.dto.SymmetricKeyGenerateRequestDto; -import io.mosip.kernel.keymanagerservice.dto.SymmetricKeyGenerateResponseDto; -import io.mosip.kernel.keymanagerservice.dto.UploadCertificateRequestDto; -import io.mosip.kernel.keymanagerservice.dto.UploadCertificateResponseDto; -import io.mosip.kernel.keymanagerservice.service.KeymanagerService; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiParam; - -/** - * This class provides controller methods for Key manager. - * - * @author Dharmesh Khandelwal - * @author Urvil Joshi - * @since 1.0.0 - * - */ -@CrossOrigin -@RestController -@Api(tags = { "keymanager" }, value = "Operation related to Keymanagement") -public class KeymanagerController { - - /** - * Instance for KeymanagerService - */ - @Autowired - KeymanagerService keymanagerService; - - /** - * Generate Master Key for the provided APP ID. - * - * @param objectType response Object Type. Support types are Certificate/CSR. Path Parameter. - * @param keyPairGenRequestDto {@link KeyPairGenerateRequestDto} request - * @return {@link KeyPairGenerateResponseDto} instance - */ - @PreAuthorize("hasAnyRole('ZONAL_ADMIN','GLOBAL_ADMIN','KEY_MAKER', 'INDIVIDUAL','REGISTRATION_PROCESSOR','REGISTRATION_ADMIN','REGISTRATION_SUPERVISOR','REGISTRATION_OFFICER','ID_AUTHENTICATION','TEST','PRE_REGISTRATION_ADMIN','RESIDENT')") - @ResponseFilter - @PostMapping(value = "/generateMasterKey/{objectType}") - public ResponseWrapper generateMasterKey( - @ApiParam("Response Type CERTIFICATE/CSR") @PathVariable("objectType") String objectType, - @RequestBody @Valid RequestWrapper keyPairGenRequestDto) { - - ResponseWrapper response = new ResponseWrapper<>(); - response.setResponse(keymanagerService.generateMasterKey(objectType, keyPairGenRequestDto.getRequest())); - return response; - } - - /** - * Request to get Certificate for the Provided APP ID & REF ID. - * - * @param applicationId Application id of the application requesting Certificate - * @param referenceId Reference id of the application requesting Certificate. Blank in case of Master Key. - * @return {@link KeyPairGenerateResponseDto} instance - */ - @PreAuthorize("hasAnyRole('ZONAL_ADMIN','GLOBAL_ADMIN','INDIVIDUAL','REGISTRATION_PROCESSOR','REGISTRATION_ADMIN','REGISTRATION_SUPERVISOR','REGISTRATION_OFFICER','ID_AUTHENTICATION','TEST','PRE_REGISTRATION_ADMIN','RESIDENT')") - @ResponseFilter - @GetMapping(value = "/getCertificate") - public ResponseWrapper getCertificate( - @ApiParam("Id of application") @RequestParam("applicationId") String applicationId, - @ApiParam("Refrence Id as metadata") @RequestParam("referenceId") Optional referenceId) { - - ResponseWrapper response = new ResponseWrapper<>(); - response.setResponse(keymanagerService.getCertificate(applicationId, referenceId)); - return response; - } - - /** - * Request to Generate CSR for the provided APP ID & REF ID along with other certificate params. - * - * @param csrGenRequestDto {@link CSRGenerateRequestDto} request - * @return {@link KeyPairGenerateResponseDto} instance - */ - @PreAuthorize("hasAnyRole('ZONAL_ADMIN','GLOBAL_ADMIN','INDIVIDUAL','REGISTRATION_PROCESSOR','REGISTRATION_ADMIN','REGISTRATION_SUPERVISOR','REGISTRATION_OFFICER','ID_AUTHENTICATION','TEST','PRE_REGISTRATION_ADMIN','RESIDENT')") - @ResponseFilter - @PostMapping(value = "/generateCSR") - public ResponseWrapper generateCSR( - @RequestBody @Valid RequestWrapper csrGenRequestDto) { - - ResponseWrapper response = new ResponseWrapper<>(); - response.setResponse(keymanagerService.generateCSR(csrGenRequestDto.getRequest())); - return response; - } - - /** - * Update signed certificate for the provided APP ID & REF ID. - * - * @param uploadCertRequestDto {@link UploadCertificateRequestDto} request - * @return {@link UploadCertificateResponseDto} instance - */ - @PreAuthorize("hasAnyRole('ZONAL_ADMIN','GLOBAL_ADMIN','INDIVIDUAL','REGISTRATION_PROCESSOR','REGISTRATION_ADMIN','REGISTRATION_SUPERVISOR','REGISTRATION_OFFICER','ID_AUTHENTICATION','TEST','PRE_REGISTRATION_ADMIN','RESIDENT')") - @ResponseFilter - @PostMapping(value = "/uploadCertificate") - public ResponseWrapper uploadCertificate( - @RequestBody @Valid RequestWrapper uploadCertRequestDto) { - - ResponseWrapper response = new ResponseWrapper<>(); - response.setResponse(keymanagerService.uploadCertificate(uploadCertRequestDto.getRequest())); - return response; - } - - /** - * Update signed certificate for the provided APP ID & REF ID for other domains. - * - * @param uploadCertRequestDto {@link UploadCertificateRequestDto} request - * @return {@link UploadCertificateResponseDto} instance - */ - @PreAuthorize("hasAnyRole('ZONAL_ADMIN','GLOBAL_ADMIN','INDIVIDUAL','REGISTRATION_PROCESSOR','REGISTRATION_ADMIN','REGISTRATION_SUPERVISOR','REGISTRATION_OFFICER','ID_AUTHENTICATION','TEST','PRE_REGISTRATION_ADMIN','RESIDENT')") - @ResponseFilter - @PostMapping(value = "/uploadOtherDomainCertificate") - public ResponseWrapper uploadOtherDomainCertificate( - @RequestBody @Valid RequestWrapper uploadCertRequestDto) { - - ResponseWrapper response = new ResponseWrapper<>(); - response.setResponse(keymanagerService.uploadOtherDomainCertificate(uploadCertRequestDto.getRequest())); - return response; - } - - /** - * Request to Generate Symmetric key for the provided APP ID & REF ID. - * - * @param symGenRequestDto {@link SymmetricKeyGenerateRequestDto} request - * @return {@link SymmetricKeyGenerateResponseDto} instance - */ - @PreAuthorize("hasAnyRole('ZONAL_ADMIN','GLOBAL_ADMIN','INDIVIDUAL','REGISTRATION_PROCESSOR','REGISTRATION_ADMIN','REGISTRATION_SUPERVISOR','REGISTRATION_OFFICER','ID_AUTHENTICATION','TEST','PRE_REGISTRATION_ADMIN','RESIDENT')") - @ResponseFilter - @PostMapping(value = "/generateSymmetricKey") - public ResponseWrapper generateSymmetricKey( - @RequestBody @Valid RequestWrapper symGenRequestDto) { - - ResponseWrapper response = new ResponseWrapper<>(); - response.setResponse(keymanagerService.generateSymmetricKey(symGenRequestDto.getRequest())); - return response; - } - - /** - * Request to Revoke Base Key for the provided APP ID & REF ID. - * - * @param revokeKeyRequestDto {@link RevokeKeyRequestDto} request - * @return {@link RevokeKeyResponseDto} instance - */ - @PreAuthorize("hasAnyRole('ZONAL_ADMIN','GLOBAL_ADMIN','INDIVIDUAL','REGISTRATION_PROCESSOR','REGISTRATION_ADMIN','REGISTRATION_SUPERVISOR','REGISTRATION_OFFICER','ID_AUTHENTICATION','TEST','PRE_REGISTRATION_ADMIN','RESIDENT')") - @ResponseFilter - @PutMapping(value = "/revokeKey") - public ResponseWrapper revokeKey( - @RequestBody @Valid RequestWrapper revokeKeyRequestDto) { - - ResponseWrapper response = new ResponseWrapper<>(); - response.setResponse(keymanagerService.revokeKey(revokeKeyRequestDto.getRequest())); - return response; - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/CSRGenerateRequestDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/CSRGenerateRequestDto.java deleted file mode 100644 index d2b75a09c8b..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/CSRGenerateRequestDto.java +++ /dev/null @@ -1,75 +0,0 @@ -package io.mosip.kernel.keymanagerservice.dto; - -import javax.validation.constraints.NotBlank; - -import io.mosip.kernel.keymanagerservice.constant.KeymanagerConstant; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * CSR-Request model - * - * @author Mahammed Taheer - * - * @since 1.0.10 - */ -@Data -@AllArgsConstructor -@NoArgsConstructor -@ApiModel(description = "Model representing a CSR Generation Request") -public class CSRGenerateRequestDto { - - - /** - * Application Id For Generating KeyPair - */ - @ApiModelProperty(notes = "Application ID", example = "KERNEL", required = true) - @NotBlank(message = KeymanagerConstant.INVALID_REQUEST) - private String applicationId; - - /** - * Reference Id For Generating KeyPair - */ - @ApiModelProperty(notes = "Reference ID", example = "", required = false) - private String referenceId; - - /** - * Common Name For Generating Certificate or CSR - */ - @ApiModelProperty(notes = "Common Name (CN)", example = "MOSIP", required = false) - private String commonName; - - /** - * Organization Unit For Generating Certificate or CSR - */ - @ApiModelProperty(notes = "Organization Unit (OU)", example = "MOSIP-TECH-CENTER", required = false) - private String organizationUnit; - - /** - * Organization For Generating Certificate or CSR - */ - @ApiModelProperty(notes = "Organization (O)", example = "IIITB", required = false) - private String organization; - - /** - * Location For Generating Certificate or CSR - */ - @ApiModelProperty(notes = "Location (L)", example = "BANGALORE", required = false) - private String location; - - /** - * State For Generating Certificate or CSR - */ - @ApiModelProperty(notes = "State (ST)", example = "KA", required = false) - @NotBlank(message = KeymanagerConstant.INVALID_REQUEST) - private String state; - - /** - * Country For Generating Certificate or CSR - */ - @ApiModelProperty(notes = "Country (C)", example = "IN", required = false) - private String country; -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/CertificateEntry.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/CertificateEntry.java deleted file mode 100644 index 1d2a51fd24d..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/CertificateEntry.java +++ /dev/null @@ -1,24 +0,0 @@ -package io.mosip.kernel.keymanagerservice.dto; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * Certificate Key Entry from SoftHsm - * - * @author Urvil Joshi - * - * @param Certificate Type - * @param

PrivateKey Type - */ -@Data -@NoArgsConstructor -@AllArgsConstructor -public class CertificateEntry { - - private C[] chain; - - private P privateKey; - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/CertificateInfo.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/CertificateInfo.java deleted file mode 100644 index cbc439c9640..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/CertificateInfo.java +++ /dev/null @@ -1,23 +0,0 @@ -package io.mosip.kernel.keymanagerservice.dto; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * Certificate Info class - * - * @author Mahammed Taheer - * @since 1.1.2 - * - */ -@Data -@AllArgsConstructor -@NoArgsConstructor -public class CertificateInfo { - - private String alias; - - private T certificate; - -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/EncryptDataRequestDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/EncryptDataRequestDto.java deleted file mode 100644 index e94b984a458..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/EncryptDataRequestDto.java +++ /dev/null @@ -1,40 +0,0 @@ -package io.mosip.kernel.keymanagerservice.dto; - -import com.fasterxml.jackson.annotation.JsonFormat; - -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -@Data -@AllArgsConstructor -@NoArgsConstructor -public class EncryptDataRequestDto { - - /** - * The string applicationID - */ - @ApiModelProperty(notes = "Application id of decrypting module", example = "REGISTRATION", required = true) - private String applicationId; - - /** - * The field for timestamp - */ - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") - @ApiModelProperty(notes = "Timestamp", example = "2018-12-10T06:12:52.994Z", required = true) - private String timeStamp; - - /** - * The string reference id - */ - - @ApiModelProperty(notes = "Reference Id", example = "REF01") - private String referenceId; - - /** - * The string encryptedSymmetricKey - */ - @ApiModelProperty(notes = "Hashed data in BASE64 encoding to encrypt", required = true) - private String hashedData; -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/EncryptDataResponseDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/EncryptDataResponseDto.java deleted file mode 100644 index b0c892e33c8..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/EncryptDataResponseDto.java +++ /dev/null @@ -1,25 +0,0 @@ -package io.mosip.kernel.keymanagerservice.dto; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * - * @author Srinivasan - * @since 1.0.0 - * - */ -@Data -@NoArgsConstructor -@AllArgsConstructor -@ApiModel("class which handles keypair") -public class EncryptDataResponseDto { - - /** The encrypted data. */ - @ApiModelProperty(notes = "Encrypted data with private key", required = true) - private String encryptedData; - -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/KeyPairGenerateRequestDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/KeyPairGenerateRequestDto.java deleted file mode 100644 index a39f2a83009..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/KeyPairGenerateRequestDto.java +++ /dev/null @@ -1,80 +0,0 @@ -package io.mosip.kernel.keymanagerservice.dto; - -import javax.validation.constraints.NotBlank; - -import io.mosip.kernel.keymanagerservice.constant.KeymanagerConstant; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * Crypto-Manager-Request model - * - * @author Mahammed Taheer - * - * @since 1.0.10 - */ -@Data -@AllArgsConstructor -@NoArgsConstructor -@ApiModel(description = "Model representing a Keypair Generation Request") -public class KeyPairGenerateRequestDto { - - - /** - * Application Id For Generating KeyPair - */ - @ApiModelProperty(notes = "Application ID", example = "REGISTRATION", required = true) - @NotBlank(message = KeymanagerConstant.INVALID_REQUEST) - private String applicationId; - - /** - * Reference Id For Generating KeyPair - */ - @ApiModelProperty(notes = "Reference ID", example = "", required = false) - private String referenceId; - - /** - * Force Flag - */ - @ApiModelProperty(notes = "Flag to force new generation of KeyPair by invalidating existing keys.", example = "false", required = false) - private Boolean force; - - /** - * Common Name For Generating Certificate or CSR - */ - @ApiModelProperty(notes = "Common Name (CN)", example = "", required = false) - private String commonName; - - /** - * Organization Unit For Generating Certificate or CSR - */ - @ApiModelProperty(notes = "Organization Unit (OU)", example = "", required = false) - private String organizationUnit; - - /** - * Organization For Generating Certificate or CSR - */ - @ApiModelProperty(notes = "Organization (O)", example = "", required = false) - private String organization; - - /** - * Location For Generating Certificate or CSR - */ - @ApiModelProperty(notes = "Location (L)", example = "", required = false) - private String location; - - /** - * State For Generating Certificate or CSR - */ - @ApiModelProperty(notes = "State (ST)", example = "", required = false) - private String state; - - /** - * Country For Generating Certificate or CSR - */ - @ApiModelProperty(notes = "Country (C)", example = "", required = false) - private String country; -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/KeyPairGenerateResponseDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/KeyPairGenerateResponseDto.java deleted file mode 100644 index b1ee907199d..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/KeyPairGenerateResponseDto.java +++ /dev/null @@ -1,59 +0,0 @@ -package io.mosip.kernel.keymanagerservice.dto; - -import java.time.LocalDateTime; - -import com.fasterxml.jackson.annotation.JsonFormat; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * Response class for Key Pair Generation. - * - * @author Mahammed Taheer - * @since 1.0.10 - * - */ -@Data -@AllArgsConstructor -@NoArgsConstructor -@ApiModel(description = "Class representing a KeyPair Generator Response") -public class KeyPairGenerateResponseDto { - - /** - * Field for certificate - */ - @ApiModelProperty(notes = "X509 self-signed certificate", required = false) - private String certificate; - - /** - * Field for CSR - */ - @ApiModelProperty(notes = "Certificate Signing Request Data", required = false) - private String certSignRequest; - - /** - * Key creation time - */ - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") - @ApiModelProperty(notes = "Timestamp of issuance of certificate", required = true) - private LocalDateTime issuedAt; - - /** - * Key expiry time - */ - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") - @ApiModelProperty(notes = "Timestamp of expiry of certificate", required = true) - private LocalDateTime expiryAt; - - /** - * Key expiry time - */ - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") - @ApiModelProperty(notes = "Timestamp of public key", required = true) - private LocalDateTime timestamp; - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/PublicKeyResponse.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/PublicKeyResponse.java deleted file mode 100644 index 10323d60bfc..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/PublicKeyResponse.java +++ /dev/null @@ -1,53 +0,0 @@ -package io.mosip.kernel.keymanagerservice.dto; - -import java.time.LocalDateTime; - -import com.fasterxml.jackson.annotation.JsonFormat; -import com.fasterxml.jackson.annotation.JsonIgnore; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * Response class for Public Key - * - * @author Dharmesh Khandelwal - * @since 1.0.0 - * - */ -@Data -@AllArgsConstructor -@NoArgsConstructor -@ApiModel(description = "Class representing a Public Key Response") -public class PublicKeyResponse { - - /** - * The string alias - */ - @JsonIgnore - private String alias; - - /** - * Field for public key - */ - @ApiModelProperty(notes = "Public key in BASE64 encoding format", required = true) - private T publicKey; - - /** - * Key creation time - */ - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") - @ApiModelProperty(notes = "Timestamp of issuance of public key", required = true) - private LocalDateTime issuedAt; - - /** - * Key expiry time - */ - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") - @ApiModelProperty(notes = "Timestamp of expiry of public key", required = true) - private LocalDateTime expiryAt; - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/RevokeKeyRequestDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/RevokeKeyRequestDto.java deleted file mode 100644 index 50b262fae8d..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/RevokeKeyRequestDto.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.mosip.kernel.keymanagerservice.dto; - -import javax.validation.constraints.NotBlank; - -import io.mosip.kernel.keymanagerservice.constant.KeymanagerConstant; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * Revoke Base Key -Request model - * - * @author Mahammed Taheer - * - * @since 1.1.6 - */ -@Data -@AllArgsConstructor -@NoArgsConstructor -@ApiModel(description = "Model representing to revoke any base key.") -public class RevokeKeyRequestDto { - - - /** - * Application Id For Key to be revoked - */ - @ApiModelProperty(notes = "Application ID", example = "REGISTRATION", required = true) - @NotBlank(message = KeymanagerConstant.INVALID_REQUEST) - private String applicationId; - - /** - * Reference Id For Key to be revoked - */ - @ApiModelProperty(notes = "Reference ID", example = "1001_1001", required = true) - private String referenceId; - - /** - * Disable auto generation of key. - */ - @ApiModelProperty(notes = "Flag to stop auto generation of new key pair", example = "false", required = false) - private Boolean disableAutoGen; - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/RevokeKeyResponseDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/RevokeKeyResponseDto.java deleted file mode 100644 index 1bad025a169..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/RevokeKeyResponseDto.java +++ /dev/null @@ -1,26 +0,0 @@ -package io.mosip.kernel.keymanagerservice.dto; - -import java.time.LocalDateTime; - -import lombok.Data; - -/** - * DTO class for revoke key response. - * - * @author Mahammed Taheer - * @since 1.1.6 - * - */ -@Data -public class RevokeKeyResponseDto { - - /** - * Status of revoke key. - */ - private String status; - - /** - * Timestamp. - */ - private LocalDateTime timestamp; -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/SignatureCertificate.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/SignatureCertificate.java deleted file mode 100644 index 19128dd9abe..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/SignatureCertificate.java +++ /dev/null @@ -1,68 +0,0 @@ -package io.mosip.kernel.keymanagerservice.dto; - -import java.security.PrivateKey; -import java.security.cert.X509Certificate; -import java.time.LocalDateTime; - -import com.fasterxml.jackson.annotation.JsonFormat; -import com.fasterxml.jackson.annotation.JsonIgnore; - -import io.mosip.kernel.core.keymanager.model.CertificateEntry; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * Response class for Signature - * - * @author Urvil Joshi - * @since 1.0.0 - * - */ -@Data -@AllArgsConstructor -@NoArgsConstructor -@ApiModel(description = "Class representing a Signature Response") -public class SignatureCertificate { - - /** - * The string alias - */ - @JsonIgnore - private String alias; - - /** - * Field for public key - */ - @ApiModelProperty(notes = "Public key in BASE64 encoding format", required = true) - private CertificateEntry certificateEntry; - - /** - * Key creation time - */ - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") - @ApiModelProperty(notes = "Timestamp of issuance of public key", required = true) - private LocalDateTime issuedAt; - - /** - * Key expiry time - */ - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") - @ApiModelProperty(notes = "Timestamp of expiry of public key", required = true) - private LocalDateTime expiryAt; - - /** - * The string keystore provider name - */ - private String providerName; - - - @Override - public String toString() { - return "SignatureCertificate [alias=" + alias + ", certificateEntry=" + certificateEntry + ", issuedAt=" - + issuedAt + ", expiryAt=" + expiryAt + "]"; - } - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/SymmetricKeyGenerateRequestDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/SymmetricKeyGenerateRequestDto.java deleted file mode 100644 index 02847416cab..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/SymmetricKeyGenerateRequestDto.java +++ /dev/null @@ -1,47 +0,0 @@ -package io.mosip.kernel.keymanagerservice.dto; - -import javax.validation.constraints.NotBlank; - -import io.mosip.kernel.keymanagerservice.constant.KeymanagerConstant; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * Symmetric Key Generate Model - * - * @author Mahammed Taheer - * - * @since 1.1.4 - */ -@Data -@AllArgsConstructor -@NoArgsConstructor -@ApiModel(description = "Model representing a Symmetric Key Generation Request") -public class SymmetricKeyGenerateRequestDto { - - - /** - * Application Id For Generating Symmetric Key - */ - @ApiModelProperty(notes = "Application ID", example = "KERNEL", required = true) - @NotBlank(message = KeymanagerConstant.INVALID_REQUEST) - private String applicationId; - - /** - * Reference Id For Generating Symmetric Key - */ - @ApiModelProperty(notes = "Reference ID", example = "IDENTITY_CACHE", required = true) - @NotBlank(message = KeymanagerConstant.INVALID_REQUEST) - private String referenceId; - - /** - * Force Flag - */ - @ApiModelProperty(notes = "Flag to force new generation of Symmetric Key by invalidating existing keys.", example = "false", required = false) - private Boolean force; - -} - diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/SymmetricKeyGenerateResponseDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/SymmetricKeyGenerateResponseDto.java deleted file mode 100644 index f1b27b9448f..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/SymmetricKeyGenerateResponseDto.java +++ /dev/null @@ -1,26 +0,0 @@ -package io.mosip.kernel.keymanagerservice.dto; - -import java.time.LocalDateTime; - -import lombok.Data; - -/** - * DTO class for Symmetric Key Generate response. - * - * @author Mahammed Taheer - * @since 1.1.4 - * - */ -@Data -public class SymmetricKeyGenerateResponseDto { - - /** - * Status of Key Generation. - */ - private String status; - - /** - * Timestamp. - */ - private LocalDateTime timestamp; -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/SymmetricKeyRequestDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/SymmetricKeyRequestDto.java deleted file mode 100644 index 0d48c304741..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/SymmetricKeyRequestDto.java +++ /dev/null @@ -1,58 +0,0 @@ -package io.mosip.kernel.keymanagerservice.dto; - -import java.time.LocalDateTime; - -import com.fasterxml.jackson.annotation.JsonFormat; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * Request DTO for Symmetric Key - * - * @author Dharmesh Khandelwal - * @since 1.0.0 - * - */ -@Data -@AllArgsConstructor -@NoArgsConstructor -@ApiModel(description = "Class representing a Decrypt Request") -public class SymmetricKeyRequestDto { - - /** - * The string applicationID - */ - @ApiModelProperty(notes = "Application id of decrypting module", example = "REGISTRATION", required = true) - private String applicationId; - - /** - * The field for timestamp - */ - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") - @ApiModelProperty(notes = "Timestamp", example = "2018-12-10T06:12:52.994Z", required = true) - private LocalDateTime timeStamp; - - /** - * The string reference id - */ - - @ApiModelProperty(notes = "Reference Id", example = "REF01") - private String referenceId; - - /** - * The string encryptedSymmetricKey - */ - @ApiModelProperty(notes = "Encrypted Data in BASE64 encoding to decrypt", required = true) - private String encryptedSymmetricKey; - - /** - * flag to prepend certificate thumbprint, default to false. - */ - @ApiModelProperty(notes = "flag to prepend certificate thumbprint to encrypted/decrypted data.", example = "false", required = false) - private Boolean prependThumbprint; - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/SymmetricKeyResponseDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/SymmetricKeyResponseDto.java deleted file mode 100644 index 9db4847c31c..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/SymmetricKeyResponseDto.java +++ /dev/null @@ -1,28 +0,0 @@ -package io.mosip.kernel.keymanagerservice.dto; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * Response DTO for symmetric Key - * - * @author Dharmesh Khandelwal - * @since 1.0.0 - * - */ -@Data -@AllArgsConstructor -@NoArgsConstructor -@ApiModel(description = "Class representing a Decrypt Response") -public class SymmetricKeyResponseDto { - - /** - * The string symmetric Key - */ - @ApiModelProperty(notes = "Decrypted Data in BASE64 encoding", required = true) - private String symmetricKey; - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/UploadCertificateRequestDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/UploadCertificateRequestDto.java deleted file mode 100644 index 2c95281e6a1..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/UploadCertificateRequestDto.java +++ /dev/null @@ -1,46 +0,0 @@ -package io.mosip.kernel.keymanagerservice.dto; - -import javax.validation.constraints.NotBlank; - -import io.mosip.kernel.keymanagerservice.constant.KeymanagerConstant; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * CSR-Request model - * - * @author Mahammed Taheer - * - * @since 1.0.10 - */ -@Data -@AllArgsConstructor -@NoArgsConstructor -@ApiModel(description = "Model representing a Uploading CA signed Certificate Request") -public class UploadCertificateRequestDto { - - - /** - * Application Id For Uploading Certificate - */ - @ApiModelProperty(notes = "Application ID", example = "KERNEL", required = true) - @NotBlank(message = KeymanagerConstant.INVALID_REQUEST) - private String applicationId; - - /** - * Reference Id For Uploading Certificate - */ - @ApiModelProperty(notes = "Reference ID", example = "", required = false) - private String referenceId; - - /** - * Certificate Data - */ - @ApiModelProperty(notes = "X509 PEM Encoded Certificate", example = "", required = true) - @NotBlank(message = KeymanagerConstant.INVALID_REQUEST) - private String certificateData; - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/UploadCertificateResponseDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/UploadCertificateResponseDto.java deleted file mode 100644 index 048e3d47e8a..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/dto/UploadCertificateResponseDto.java +++ /dev/null @@ -1,26 +0,0 @@ -package io.mosip.kernel.keymanagerservice.dto; - -import java.time.LocalDateTime; - -import lombok.Data; - -/** - * DTO class for upload certificate response. - * - * @author Mahammed Taheer - * @since 1.0.10 - * - */ -@Data -public class UploadCertificateResponseDto { - - /** - * Status of upload certificate. - */ - private String status; - - /** - * Timestamp. - */ - private LocalDateTime timestamp; -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/entity/BaseEntity.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/entity/BaseEntity.java deleted file mode 100644 index c4825da8806..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/entity/BaseEntity.java +++ /dev/null @@ -1,61 +0,0 @@ -package io.mosip.kernel.keymanagerservice.entity; - -import java.time.LocalDateTime; - -import javax.persistence.Column; -import javax.persistence.MappedSuperclass; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * Superclass for entities - * - * @author Dharmesh Khandelwal - * @since 1.0.0 - * - */ -@Data -@AllArgsConstructor -@NoArgsConstructor -@MappedSuperclass -public class BaseEntity { - - /** - * The field createdBy - */ - @Column(name = "cr_by", length = 256) - private String createdBy; - - /** - * The field createdtimes - */ - @Column(name = "cr_dtimes") - private LocalDateTime createdtimes; - - /** - * The field updatedBy - */ - @Column(name = "upd_by", length = 256) - private String updatedBy; - - /** - * The field updatedtimes - */ - @Column(name = "upd_dtimes") - private LocalDateTime updatedtimes; - - /** - * The field isDeleted - */ - @Column(name = "is_deleted") - private Boolean isDeleted; - - /** - * The field deletedtimes - */ - @Column(name = "del_dtimes") - private LocalDateTime deletedtimes; - -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/entity/CACertificateStore.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/entity/CACertificateStore.java deleted file mode 100644 index f0a1762e585..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/entity/CACertificateStore.java +++ /dev/null @@ -1,95 +0,0 @@ -package io.mosip.kernel.keymanagerservice.entity; - -import java.time.LocalDateTime; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; - -/** - * @author Mahammed Taheer - * - */ - -@Entity -@Table(name = "ca_cert_store") -@Data -@EqualsAndHashCode(callSuper = false) -@NoArgsConstructor -@AllArgsConstructor -public class CACertificateStore extends BaseEntity { - - /** - * The field cert_id - */ - @Id - @Column(name = "cert_id", nullable = false, length = 36) - private String certId; - - /** - * The field cert_id - */ - @Column(name = "cert_subject", nullable = false) - private String certSubject; - - /** - * The field cert_issuer - */ - @Column(name = "cert_issuer", nullable = false) - private String certIssuer; - - /** - * The field issuer_id - */ - @Column(name = "issuer_id", nullable = false) - private String issuerId; - - /** - * The field cert_not_nefore - */ - @Column(name = "cert_not_before", nullable = false) - private LocalDateTime certNotBefore; - - /** - * The field cert_not_after - */ - @Column(name = "cert_not_after", nullable = false) - private LocalDateTime certNotAfter; - - /** - * The field crl_uri - */ - @Column(name = "crl_uri") - private String crlUri; - - /** - * The field cert_data - */ - @Column(name = "cert_data", nullable = false) - private String certData; - - /** - * The field cert_thumbprint - */ - @Column(name = "cert_thumbprint") - private String certThumbprint; - - /** - * The field cert_serial_no - */ - @Column(name = "cert_serial_no") - private String certSerialNo; - - /** - * The field partner_domain - */ - @Column(name = "partner_domain") - private String partnerDomain; - -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/entity/DataEncryptKeystore.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/entity/DataEncryptKeystore.java deleted file mode 100644 index c1cc8397bd7..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/entity/DataEncryptKeystore.java +++ /dev/null @@ -1,48 +0,0 @@ -package io.mosip.kernel.keymanagerservice.entity; - -import java.time.LocalDateTime; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; - -/** - * @author Mahammed Taheer - * - */ - -@Entity -@Table(name = "data_encrypt_keystore") -@Data -@EqualsAndHashCode(callSuper = false) -@NoArgsConstructor -@AllArgsConstructor -public class DataEncryptKeystore { - - @Id - private Integer id; - - @Column(name = "key") - private String key; - - @Column(name = "key_status") - private String keyStatus; - - @Column(name = "cr_by") - private String crBy; - - @Column(name = "cr_dtimes") - private LocalDateTime crDTimes; - - @Column(name = "upd_by") - private String updBy; - - @Column(name = "upd_dtimes") - private LocalDateTime updDTimes; -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/entity/KeyAlias.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/entity/KeyAlias.java deleted file mode 100644 index faa1874ee3e..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/entity/KeyAlias.java +++ /dev/null @@ -1,67 +0,0 @@ -package io.mosip.kernel.keymanagerservice.entity; - -import java.time.LocalDateTime; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; - -/** - * Entity class for KeyAlias - * - * @author Dharmesh Khandelwal - * @since 1.0.0 - * - */ -@Entity -@Table(name = "key_alias") -@Data -@EqualsAndHashCode(callSuper = true) -@NoArgsConstructor -@AllArgsConstructor -public class KeyAlias extends BaseEntity { - - /** - * The field alias - */ - @Id - @Column(name = "id", nullable = false, length = 36) - private String alias; - - /** - * The field applicationId - */ - @Column(name = "app_id", nullable = false, length = 36) - private String applicationId; - - /** - * The field referenceId - */ - @Column(name = "ref_id", length = 36) - private String referenceId; - - /** - * The field keyGenerationTime - */ - @Column(name = "key_gen_dtimes") - private LocalDateTime keyGenerationTime; - - /** - * The field keyExpiryTime - */ - @Column(name = "key_expire_dtimes") - private LocalDateTime keyExpiryTime; - - /** - * The field status - */ - @Column(name = "status_code", length = 36) - private String status; - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/entity/KeyPolicy.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/entity/KeyPolicy.java deleted file mode 100644 index 5b3d70697de..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/entity/KeyPolicy.java +++ /dev/null @@ -1,47 +0,0 @@ -package io.mosip.kernel.keymanagerservice.entity; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; - -/** - * Entity class for KeyPolicy - * - * @author Dharmesh Khandelwal - * @since 1.0.0 - * - */ -@Entity -@Table(name = "key_policy_def") -@Data -@EqualsAndHashCode(callSuper = false) -@NoArgsConstructor -@AllArgsConstructor -public class KeyPolicy extends BaseEntity { - - /** - * The field applicationId - */ - @Id - @Column(name = "app_id", nullable = false, length = 36) - private String applicationId; - - /** - * The field validityInDays - */ - @Column(name = "key_validity_duration") - private int validityInDays; - - /** - * The field isActive - */ - @Column(name = "is_active") - private boolean isActive; - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/entity/KeyStore.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/entity/KeyStore.java deleted file mode 100644 index e49553d60cb..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/entity/KeyStore.java +++ /dev/null @@ -1,53 +0,0 @@ -package io.mosip.kernel.keymanagerservice.entity; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; - -/** - * Entity class for KeyStore - * - * @author Dharmesh Khandelwal - * @since 1.0.0 - * - */ -@Entity -@Table(name = "key_store") -@Data -@EqualsAndHashCode(callSuper = false) -@NoArgsConstructor -@AllArgsConstructor -public class KeyStore extends BaseEntity { - - /** - * The field alias - */ - @Id - @Column(name = "id", nullable = false, length = 36) - private String alias; - - /** - * The field publicKey - */ - @Column(name = "certificate_data") - private String certificateData; - - /** - * The field privateKey - */ - @Column(name = "private_key") - private String privateKey; - - /** - * The field masterAlias - */ - @Column(name = "master_key") - private String masterAlias; - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/entity/PartnerCertificateStore.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/entity/PartnerCertificateStore.java deleted file mode 100644 index 7fa137adb17..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/entity/PartnerCertificateStore.java +++ /dev/null @@ -1,107 +0,0 @@ -package io.mosip.kernel.keymanagerservice.entity; - -import java.time.LocalDateTime; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; - -/** - * @author Mahammed Taheer - * - */ - -@Entity -@Table(name = "partner_cert_store") -@Data -@EqualsAndHashCode(callSuper = false) -@NoArgsConstructor -@AllArgsConstructor -public class PartnerCertificateStore extends BaseEntity { - - /** - * The field cert_id - */ - @Id - @Column(name = "cert_id", nullable = false, length = 36) - private String certId; - - /** - * The field cert_id - */ - @Column(name = "cert_subject", nullable = false) - private String certSubject; - - /** - * The field cert_issuer - */ - @Column(name = "cert_issuer", nullable = false) - private String certIssuer; - - /** - * The field issuer_id - */ - @Column(name = "issuer_id", nullable = false) - private String issuerId; - - /** - * The field cert_not_nefore - */ - @Column(name = "cert_not_before", nullable = false) - private LocalDateTime certNotBefore; - - /** - * The field cert_not_after - */ - @Column(name = "cert_not_after", nullable = false) - private LocalDateTime certNotAfter; - - /** - * The field partner_domain - */ - @Column(name = "partner_domain", nullable = false) - private String partnerDomain; - - /** - * The field cert_data - */ - @Column(name = "cert_data", nullable = false) - private String certData; - - /** - * The field key_usage - */ - @Column(name = "key_usage") - private String keyUsage; - - /** - * The field organization_name - */ - @Column(name = "organization_name") - private String organizationName; - - /** - * The field cert_thumbprint - */ - @Column(name = "cert_thumbprint") - private String certThumbprint; - - /** - * The field cert_serial_no - */ - @Column(name = "cert_serial_no") - private String certSerialNo; - - /** - * The field cert_serial_no - */ - @Column(name = "signed_cert_data") - private String signedCertData; - -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/entity/SecreteKeyStore.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/entity/SecreteKeyStore.java deleted file mode 100644 index 8126c501407..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/entity/SecreteKeyStore.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * package io.mosip.kernel.keymanagerservice.entity; - * - * import java.time.LocalDateTime; - * - * import javax.persistence.Column; import javax.persistence.Entity; import - * javax.persistence.Id; import javax.persistence.Table; - * - * import lombok.AllArgsConstructor; import lombok.Data; import - * lombok.NoArgsConstructor; import lombok.ToString; - * - * @Data - * - * @NoArgsConstructor - * - * @AllArgsConstructor - * - * @ToString - * - * @Entity - * - * @Table(name = "dao_key_store", schema = "kernel") public class - * SecreteKeyStore { - * - * @Id private String id; - * - * private String key; - * - * @Column(name = "is_expired") private Boolean expired; - * - * - * @Column(name = "key_gen_dtimes") private LocalDateTime genratedtimes; - * - * - * @Column(name = "key_expire_dtimes") private LocalDateTime expiryDate; - * - * @Column(name = "cr_by") private String createdBy; - * - * @Column(name = "cr_dtimes") private LocalDateTime createDateTime; - * - * @Column(name = "upd_by") private String updatedBy; - * - * @Column(name = "upd_dtimes") private LocalDateTime updateDateTime; - * - * @Column(name = "is_deleted") private Boolean isDeleted; - * - * @Column(name = "del_dtimes") private LocalDateTime deletedtimes; - * - * } - */ \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/exception/CryptoException.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/exception/CryptoException.java deleted file mode 100644 index d81dcb8c75b..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/exception/CryptoException.java +++ /dev/null @@ -1,38 +0,0 @@ -package io.mosip.kernel.keymanagerservice.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; - -/** - * Custom Exception Class in case of CryptoException - * - * @author Dharmesh Khandelwal - * @since 1.0.0 - * - */ -public class CryptoException extends BaseUncheckedException { - - /** - * Generated serial version id - */ - private static final long serialVersionUID = 8621530697947108810L; - - /** - * Constructor the initialize Handler exception - * - * @param errorCode The errorcode for this exception - * @param errorMessage The error message for this exception - */ - public CryptoException(String errorCode, String errorMessage) { - super(errorCode, errorMessage); - } - - /** - * @param errorCode The errorcode for this exception - * @param errorMessage The error message for this exception - * @param rootCause cause of the error occoured - */ - public CryptoException(String errorCode, String errorMessage, Throwable rootCause) { - super(errorCode, errorMessage, rootCause); - } - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/exception/InvalidApplicationIdException.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/exception/InvalidApplicationIdException.java deleted file mode 100644 index c46d684b274..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/exception/InvalidApplicationIdException.java +++ /dev/null @@ -1,29 +0,0 @@ -package io.mosip.kernel.keymanagerservice.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; - -/** - * Custom Exception Class in case of applicationId is not present - * - * @author Dharmesh Khandelwal - * @since 1.0.0 - * - */ -public class InvalidApplicationIdException extends BaseUncheckedException { - - /** - * Generated serial version id - */ - private static final long serialVersionUID = 8621530697947108810L; - - /** - * Constructor the initialize Handler exception - * - * @param errorCode The errorcode for this exception - * @param errorMessage The error message for this exception - */ - public InvalidApplicationIdException(String errorCode, String errorMessage) { - super(errorCode, errorMessage); - } - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/exception/InvalidResponseObjectTypeException.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/exception/InvalidResponseObjectTypeException.java deleted file mode 100644 index 92a07c48b12..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/exception/InvalidResponseObjectTypeException.java +++ /dev/null @@ -1,29 +0,0 @@ -package io.mosip.kernel.keymanagerservice.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; - -/** - * Custom Exception Class in case of Invalid Key Generation Response object type - * - * @author Mahammed Taheer - * @since 1.0.10 - * - */ -public class InvalidResponseObjectTypeException extends BaseUncheckedException { - - /** - * Generated serial version id - */ - private static final long serialVersionUID = 8621530697947108810L; - - /** - * Constructor the initialize Handler exception - * - * @param errorCode The errorcode for this exception - * @param errorMessage The error message for this exception - */ - public InvalidResponseObjectTypeException(String errorCode, String errorMessage) { - super(errorCode, errorMessage); - } - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/exception/KeyStoreException.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/exception/KeyStoreException.java deleted file mode 100644 index 8d937461546..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/exception/KeyStoreException.java +++ /dev/null @@ -1,29 +0,0 @@ -package io.mosip.kernel.keymanagerservice.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; - -/** - * Custom Exception Class in case of keystore is not able to store key - * - * @author Dharmesh Khandelwal - * @since 1.0.0 - * - */ -public class KeyStoreException extends BaseUncheckedException { - - /** - * Generated serial version id - */ - private static final long serialVersionUID = 8621530697947108810L; - - /** - * Constructor the initialize Handler exception - * - * @param errorCode The errorcode for this exception - * @param errorMessage The error message for this exception - */ - public KeyStoreException(String errorCode, String errorMessage) { - super(errorCode, errorMessage); - } - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/exception/KeymanagerExceptionHandler.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/exception/KeymanagerExceptionHandler.java deleted file mode 100644 index 28ee9dcf63a..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/exception/KeymanagerExceptionHandler.java +++ /dev/null @@ -1,373 +0,0 @@ -/* - * - * - * - * - */ -package io.mosip.kernel.keymanagerservice.exception; - -import java.io.IOException; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.time.format.DateTimeParseException; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.exc.InvalidFormatException; -import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.http.converter.HttpMessageNotReadableException; -import org.springframework.validation.FieldError; -import org.springframework.web.bind.MethodArgumentNotValidException; -import org.springframework.web.bind.MissingServletRequestParameterException; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.RestControllerAdvice; -import org.springframework.web.util.ContentCachingRequestWrapper; - -import io.mosip.kernel.core.crypto.exception.InvalidDataException; -import io.mosip.kernel.core.crypto.exception.InvalidKeyException; -import io.mosip.kernel.core.crypto.exception.NullDataException; -import io.mosip.kernel.core.exception.BaseUncheckedException; -import io.mosip.kernel.core.exception.ErrorResponse; -import io.mosip.kernel.core.exception.ExceptionUtils; -import io.mosip.kernel.core.exception.NoSuchAlgorithmException; -import io.mosip.kernel.core.exception.ServiceError; -import io.mosip.kernel.core.http.ResponseWrapper; -import io.mosip.kernel.core.idgenerator.exception.TokenIdGeneratorException; -import io.mosip.kernel.core.keymanager.exception.KeystoreProcessingException; -import io.mosip.kernel.core.signatureutil.exception.ParseResponseException; -import io.mosip.kernel.core.signatureutil.exception.SignatureUtilClientException; -import io.mosip.kernel.core.signatureutil.exception.SignatureUtilException; -import io.mosip.kernel.core.util.EmptyCheckUtils; -import io.mosip.kernel.cryptomanager.constant.CryptomanagerErrorCode; -import io.mosip.kernel.cryptomanager.exception.CryptoManagerSerivceException; -import io.mosip.kernel.keymanagerservice.constant.KeymanagerConstant; -import io.mosip.kernel.keymanagerservice.constant.KeymanagerErrorConstant; -import io.mosip.kernel.lkeymanager.exception.InvalidArgumentsException; -import io.mosip.kernel.lkeymanager.exception.LicenseKeyServiceException; -import io.mosip.kernel.partnercertservice.exception.PartnerCertManagerException; -import io.mosip.kernel.signature.exception.RequestException; -import io.mosip.kernel.signature.exception.SignatureFailureException; -import io.mosip.kernel.zkcryptoservice.exception.ZKCryptoException; -import io.mosip.kernel.zkcryptoservice.exception.ZKKeyDerivationException; -import io.mosip.kernel.zkcryptoservice.exception.ZKRandomKeyDecryptionException; - -/** - * Rest Controller Advice for Keymanager Service - * - * @author Dharmesh Khandelwal - * - * @since 1.0.0 - */ -@RestControllerAdvice -public class KeymanagerExceptionHandler { - - @Autowired - private ObjectMapper objectMapper; - - @ExceptionHandler(NullDataException.class) - public ResponseEntity> nullDataException(HttpServletRequest httpServletRequest, - final NullDataException e) throws IOException { - ExceptionUtils.logRootCause(e); - return new ResponseEntity<>( - getErrorResponse(httpServletRequest, e.getErrorCode(), e.getErrorText(), HttpStatus.OK), HttpStatus.OK); - } - - @ExceptionHandler(InvalidKeyException.class) - public ResponseEntity> invalidKeyException(HttpServletRequest httpServletRequest, - final InvalidKeyException e) throws IOException { - ExceptionUtils.logRootCause(e); - return new ResponseEntity<>( - getErrorResponse(httpServletRequest, e.getErrorCode(), e.getErrorText(), HttpStatus.OK), HttpStatus.OK); - } - - @ExceptionHandler(NoSuchAlgorithmException.class) - public ResponseEntity> noSuchAlgorithmException(HttpServletRequest httpServletRequest, - final NoSuchAlgorithmException e) throws IOException { - ExceptionUtils.logRootCause(e); - return new ResponseEntity<>( - getErrorResponse(httpServletRequest, e.getErrorCode(), e.getErrorText(), HttpStatus.OK), HttpStatus.OK); - } - - - @ExceptionHandler(IllegalArgumentException.class) - public ResponseEntity> illegalArgumentException(HttpServletRequest httpServletRequest, - final IllegalArgumentException e) throws IOException { - return new ResponseEntity<>( - getErrorResponse(httpServletRequest, - CryptomanagerErrorCode.INVALID_DATA_WITHOUT_KEY_BREAKER.getErrorCode(), - CryptomanagerErrorCode.INVALID_DATA_WITHOUT_KEY_BREAKER.getErrorMessage(), HttpStatus.OK), - HttpStatus.OK); - } - - @ExceptionHandler(InvalidFormatException.class) - public ResponseEntity> invalidFormatException(HttpServletRequest httpServletRequest, - final InvalidFormatException e) throws IOException { - return new ResponseEntity<>( - getErrorResponse(httpServletRequest, KeymanagerErrorConstant.DATE_TIME_PARSE_EXCEPTION.getErrorCode(), - e.getMessage() + KeymanagerConstant.WHITESPACE - + KeymanagerErrorConstant.DATE_TIME_PARSE_EXCEPTION.getErrorMessage(), - HttpStatus.OK), - HttpStatus.OK); - } - - @ExceptionHandler(DateTimeParseException.class) - public ResponseEntity> dateTimeParseException(HttpServletRequest httpServletRequest, - final DateTimeParseException e) throws IOException { - return new ResponseEntity<>( - getErrorResponse(httpServletRequest, KeymanagerErrorConstant.DATE_TIME_PARSE_EXCEPTION.getErrorCode(), - e.getMessage() + KeymanagerConstant.WHITESPACE - + KeymanagerErrorConstant.DATE_TIME_PARSE_EXCEPTION.getErrorMessage(), - HttpStatus.OK), - HttpStatus.OK); - } - - @ExceptionHandler(InvalidDataException.class) - public ResponseEntity> invalidDataException(HttpServletRequest httpServletRequest, - final InvalidDataException e) throws IOException { - ExceptionUtils.logRootCause(e); - return new ResponseEntity<>( - getErrorResponse(httpServletRequest, e.getErrorCode(), e.getErrorText(), HttpStatus.OK), HttpStatus.OK); - } - - @ExceptionHandler(NoUniqueAliasException.class) - public ResponseEntity> noUniqueAliasException(HttpServletRequest httpServletRequest, - final NoUniqueAliasException e) throws IOException { - ExceptionUtils.logRootCause(e); - return new ResponseEntity<>( - getErrorResponse(httpServletRequest, e.getErrorCode(), e.getErrorText(), HttpStatus.OK), HttpStatus.OK); - } - - @ExceptionHandler(CryptoException.class) - public ResponseEntity> cryptoException(HttpServletRequest httpServletRequest, - final CryptoException e) throws IOException { - ExceptionUtils.logRootCause(e); - return new ResponseEntity<>( - getErrorResponse(httpServletRequest, e.getErrorCode(), e.getErrorText(), HttpStatus.OK), HttpStatus.OK); - } - - @ExceptionHandler(KeymanagerServiceException.class) - public ResponseEntity> keymanagerServiceException( - HttpServletRequest httpServletRequest, final KeymanagerServiceException e) throws IOException { - ExceptionUtils.logRootCause(e); - return new ResponseEntity<>( - getErrorResponse(httpServletRequest, e.getErrorCode(), e.getErrorText(), HttpStatus.OK), HttpStatus.OK); - } - - @ExceptionHandler(CryptoManagerSerivceException.class) - public ResponseEntity> cryptoManagerServieException( - HttpServletRequest httpServletRequest, final CryptoManagerSerivceException e) throws IOException { - ExceptionUtils.logRootCause(e); - return new ResponseEntity<>( - getErrorResponse(httpServletRequest, e.getErrorCode(), e.getErrorText(), HttpStatus.OK), HttpStatus.OK); - } - - @ExceptionHandler(InvalidApplicationIdException.class) - public ResponseEntity> invalidApplicationIdException( - HttpServletRequest httpServletRequest, final InvalidApplicationIdException e) throws IOException { - ExceptionUtils.logRootCause(e); - return new ResponseEntity<>( - getErrorResponse(httpServletRequest, e.getErrorCode(), e.getErrorText(), HttpStatus.OK), HttpStatus.OK); - } - - @ExceptionHandler(MethodArgumentNotValidException.class) - public ResponseEntity> methodArgumentNotValidException( - HttpServletRequest httpServletRequest, final MethodArgumentNotValidException e) throws IOException { - ResponseWrapper errorResponse = setErrors(httpServletRequest); - final List fieldErrors = e.getBindingResult().getFieldErrors(); - fieldErrors.forEach(x -> { - ServiceError error = new ServiceError(KeymanagerErrorConstant.INVALID_REQUEST.getErrorCode(), - x.getField() + KeymanagerConstant.WHITESPACE + x.getDefaultMessage()); - errorResponse.getErrors().add(error); - }); - return new ResponseEntity<>(errorResponse, HttpStatus.OK); - } - - @ExceptionHandler(HttpMessageNotReadableException.class) - public ResponseEntity> onHttpMessageNotReadable(HttpServletRequest httpServletRequest, - final HttpMessageNotReadableException e) throws IOException { - ResponseWrapper errorResponse = setErrors(httpServletRequest); - ServiceError error = new ServiceError(KeymanagerErrorConstant.INVALID_REQUEST.getErrorCode(), e.getMessage()); - errorResponse.getErrors().add(error); - return new ResponseEntity<>(errorResponse, HttpStatus.OK); - } - - @ExceptionHandler(MissingServletRequestParameterException.class) - public ResponseEntity> onMissingServletRequestParameterException( - HttpServletRequest httpServletRequest, final MissingServletRequestParameterException e) throws IOException { - ResponseWrapper errorResponse = setErrors(httpServletRequest); - ServiceError error = new ServiceError(KeymanagerErrorConstant.INVALID_REQUEST.getErrorCode(), e.getMessage()); - errorResponse.getErrors().add(error); - return new ResponseEntity<>(errorResponse, HttpStatus.OK); - } - - @ExceptionHandler(TokenIdGeneratorException.class) - public ResponseEntity> emptyLengthException( - final HttpServletRequest httpServletRequest, final TokenIdGeneratorException e) throws IOException { - ResponseWrapper responseWrapper = setErrors(httpServletRequest); - ServiceError error = new ServiceError(e.getErrorCode(), e.getErrorText()); - responseWrapper.getErrors().add(error); - return new ResponseEntity<>(responseWrapper, HttpStatus.OK); - - } - - @ExceptionHandler(ZKCryptoException.class) - public ResponseEntity> zkCryptoException( - HttpServletRequest httpServletRequest, final ZKCryptoException e) throws IOException { - ExceptionUtils.logRootCause(e); - return new ResponseEntity<>( - getErrorResponse(httpServletRequest, e.getErrorCode(), e.getErrorText(), HttpStatus.OK), HttpStatus.OK); - } - - @ExceptionHandler(ZKKeyDerivationException.class) - public ResponseEntity> zkKeyDerivationException( - HttpServletRequest httpServletRequest, final ZKKeyDerivationException e) throws IOException { - ExceptionUtils.logRootCause(e); - return new ResponseEntity<>( - getErrorResponse(httpServletRequest, e.getErrorCode(), e.getErrorText(), HttpStatus.OK), HttpStatus.OK); - } - - @ExceptionHandler(ZKRandomKeyDecryptionException.class) - public ResponseEntity> zkRandomKeyDecryptionException( - HttpServletRequest httpServletRequest, final ZKRandomKeyDecryptionException e) throws IOException { - ExceptionUtils.logRootCause(e); - return new ResponseEntity<>( - getErrorResponse(httpServletRequest, e.getErrorCode(), e.getErrorText(), HttpStatus.OK), HttpStatus.OK); - } - - @ExceptionHandler(PartnerCertManagerException.class) - public ResponseEntity> partnerCertManagerException( - HttpServletRequest httpServletRequest, final PartnerCertManagerException e) throws IOException { - ExceptionUtils.logRootCause(e); - return new ResponseEntity<>( - getErrorResponse(httpServletRequest, e.getErrorCode(), e.getErrorText(), HttpStatus.OK), HttpStatus.OK); - } - - - @ExceptionHandler(KeystoreProcessingException.class) - public ResponseEntity> keystoreProcessingException( - HttpServletRequest httpServletRequest, final KeystoreProcessingException e) throws IOException { - ExceptionUtils.logRootCause(e); - return new ResponseEntity<>( - getErrorResponse(httpServletRequest, e.getErrorCode(), e.getErrorText(), HttpStatus.OK), HttpStatus.OK); - } - /** - * Method to handle {@link InvalidArgumentsException}. - * - * @param httpServletRequest the request - * @param exception the exception. - * @return {@link ErrorResponse}. - * @throws IOException the IO exception - */ - @ExceptionHandler(InvalidArgumentsException.class) - public ResponseEntity> validateInputArguments(HttpServletRequest httpServletRequest, - final InvalidArgumentsException exception) throws IOException { - ResponseWrapper errorResponse = setErrors(httpServletRequest); - errorResponse.getErrors().addAll(exception.getList()); - return new ResponseEntity<>(errorResponse, HttpStatus.OK); - } - - /** - * Method to handle {@link LicenseKeyServiceException}. - * - * @param httpServletRequest the request - * @param exception the exception. - * @return {@link ErrorResponse}. - * @throws IOException the IO exception - */ - @ExceptionHandler(LicenseKeyServiceException.class) - public ResponseEntity> handleServiceException(HttpServletRequest httpServletRequest, - final LicenseKeyServiceException exception) throws IOException { - ResponseWrapper errorResponse = setErrors(httpServletRequest); - errorResponse.getErrors().addAll(exception.getList()); - return new ResponseEntity<>(errorResponse, HttpStatus.OK); - } - - - @ExceptionHandler(RequestException.class) - public ResponseEntity> controlRequestException( - final HttpServletRequest httpServletRequest, final RequestException e) throws IOException { - ExceptionUtils.logRootCause(e); - return getErrorResponseEntity(e, HttpStatus.OK, httpServletRequest); - } - - @ExceptionHandler(SignatureFailureException.class) - public ResponseEntity> signatureFailureException( - final HttpServletRequest httpServletRequest, final SignatureFailureException e) throws IOException { - ExceptionUtils.logRootCause(e); - return getErrorResponseEntity(e, HttpStatus.OK, httpServletRequest); - } - - @ExceptionHandler(SignatureUtilClientException.class) - public ResponseEntity> signatureUtilClientException( - final HttpServletRequest httpServletRequest, final SignatureUtilClientException e) throws IOException { - ResponseWrapper responseWrapper = setErrors(httpServletRequest); - responseWrapper.getErrors().addAll(e.getList()); - ExceptionUtils.logRootCause(e); - return new ResponseEntity<>(responseWrapper, HttpStatus.OK); - } - - @ExceptionHandler(SignatureUtilException.class) - public ResponseEntity> signatureUtilException( - final HttpServletRequest httpServletRequest, final SignatureUtilException e) throws IOException { - ExceptionUtils.logRootCause(e); - return getErrorResponseEntity(e, HttpStatus.OK, httpServletRequest); - } - - @ExceptionHandler(ParseResponseException.class) - public ResponseEntity> parseResponseException( - final HttpServletRequest httpServletRequest, final ParseResponseException e) throws IOException { - ExceptionUtils.logRootCause(e); - return getErrorResponseEntity(e, HttpStatus.OK, httpServletRequest); - } - - @ExceptionHandler(value = { Exception.class, RuntimeException.class }) - public ResponseEntity> defaultErrorHandler(HttpServletRequest httpServletRequest, - Exception e) throws IOException { - ResponseWrapper errorResponse = setErrors(httpServletRequest); - ServiceError error = new ServiceError(KeymanagerErrorConstant.INTERNAL_SERVER_ERROR.getErrorCode(), - e.getMessage()); - errorResponse.getErrors().add(error); - ExceptionUtils.logRootCause(e); - return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR); - } - - private ResponseWrapper getErrorResponse(HttpServletRequest httpServletRequest, String errorCode, - String errorMessage, HttpStatus httpStatus) throws IOException { - ResponseWrapper errorResponse = setErrors(httpServletRequest); - ServiceError error = new ServiceError(errorCode, errorMessage); - errorResponse.getErrors().add(error); - return errorResponse; - } - - private ResponseWrapper setErrors(HttpServletRequest httpServletRequest) throws IOException { - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - responseWrapper.setResponsetime(LocalDateTime.now(ZoneId.of("UTC"))); - String requestBody = null; - if (httpServletRequest instanceof ContentCachingRequestWrapper) { - requestBody = new String(((ContentCachingRequestWrapper) httpServletRequest).getContentAsByteArray()); - } - if (EmptyCheckUtils.isNullEmpty(requestBody)) { - return responseWrapper; - } - objectMapper.registerModule(new JavaTimeModule()); - JsonNode reqNode = objectMapper.readTree(requestBody); - responseWrapper.setId(reqNode.path("id").asText()); - responseWrapper.setVersion(reqNode.path("version").asText()); - return responseWrapper; - } - - private ResponseEntity> getErrorResponseEntity(BaseUncheckedException e, - HttpStatus httpStatus, HttpServletRequest httpServletRequest) throws IOException { - ResponseWrapper responseWrapper = setErrors(httpServletRequest); - ServiceError error = new ServiceError(e.getErrorCode(), e.getErrorText()); - responseWrapper.getErrors().add(error); - return new ResponseEntity<>(responseWrapper, httpStatus); - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/exception/KeymanagerServiceException.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/exception/KeymanagerServiceException.java deleted file mode 100644 index 87783785e8e..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/exception/KeymanagerServiceException.java +++ /dev/null @@ -1,38 +0,0 @@ -package io.mosip.kernel.keymanagerservice.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; - -/** - * Custom Exception Class in case of CryptoException - * - * @author Dharmesh Khandelwal - * @since 1.0.0 - * - */ -public class KeymanagerServiceException extends BaseUncheckedException { - - /** - * Generated serial version id - */ - private static final long serialVersionUID = 8621530697947108810L; - - /** - * Constructor the initialize Handler exception - * - * @param errorCode The errorcode for this exception - * @param errorMessage The error message for this exception - */ - public KeymanagerServiceException(String errorCode, String errorMessage) { - super(errorCode, errorMessage); - } - - /** - * @param errorCode The errorcode for this exception - * @param errorMessage The error message for this exception - * @param rootCause cause of the error occoured - */ - public KeymanagerServiceException(String errorCode, String errorMessage, Throwable rootCause) { - super(errorCode, errorMessage, rootCause); - } - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/exception/NoUniqueAliasException.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/exception/NoUniqueAliasException.java deleted file mode 100644 index d6a61e2e713..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/exception/NoUniqueAliasException.java +++ /dev/null @@ -1,29 +0,0 @@ -package io.mosip.kernel.keymanagerservice.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; - -/** - * Custom Exception Class in case of applicationId is not present - * - * @author Dharmesh Khandelwal - * @since 1.0.0 - * - */ -public class NoUniqueAliasException extends BaseUncheckedException { - - /** - * Generated serial version id - */ - private static final long serialVersionUID = 8621530697947108810L; - - /** - * Constructor the initialize Handler exception - * - * @param errorCode The errorcode for this exception - * @param errorMessage The error message for this exception - */ - public NoUniqueAliasException(String errorCode, String errorMessage) { - super(errorCode, errorMessage); - } - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/helper/KeymanagerDBHelper.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/helper/KeymanagerDBHelper.java deleted file mode 100644 index 41229fffa62..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/helper/KeymanagerDBHelper.java +++ /dev/null @@ -1,200 +0,0 @@ -package io.mosip.kernel.keymanagerservice.helper; - -import java.time.LocalDateTime; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.keymanagerservice.constant.KeymanagerConstant; -import io.mosip.kernel.keymanagerservice.constant.KeymanagerErrorConstant; -import io.mosip.kernel.keymanagerservice.entity.KeyAlias; -import io.mosip.kernel.keymanagerservice.entity.KeyPolicy; -import io.mosip.kernel.keymanagerservice.entity.KeyStore; -import io.mosip.kernel.keymanagerservice.exception.InvalidApplicationIdException; -import io.mosip.kernel.keymanagerservice.logger.KeymanagerLogger; -import io.mosip.kernel.keymanagerservice.repository.KeyAliasRepository; -import io.mosip.kernel.keymanagerservice.repository.KeyPolicyRepository; -import io.mosip.kernel.keymanagerservice.repository.KeyStoreRepository; -import io.mosip.kernel.keymanagerservice.util.KeymanagerUtil; - -/** - * DB Helper class for Keymanager - * - * @author Mahammed Taheer - * @since 1.1.2 - * - */ - -@Component -public class KeymanagerDBHelper { - - private static final Logger LOGGER = KeymanagerLogger.getLogger(KeymanagerDBHelper.class); - - /** - * {@link KeyAliasRepository} instance - */ - @Autowired - KeyAliasRepository keyAliasRepository; - - /** - * {@link KeyPolicyRepository} instance - */ - @Autowired - KeyPolicyRepository keyPolicyRepository; - - /** - * {@link KeyStoreRepository} instance - */ - @Autowired - KeyStoreRepository keyStoreRepository; - - /** - * Utility to generate Metadata - */ - @Autowired - KeymanagerUtil keymanagerUtil; - - /** - * Function to store key in keyalias table - * - * @param applicationId applicationId - * @param timeStamp timeStamp - * @param referenceId referenceId - * @param alias alias - * @param expiryDateTime expiryDateTime - */ - public void storeKeyInAlias(String applicationId, LocalDateTime timeStamp, String referenceId, String alias, - LocalDateTime expiryDateTime) { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.EMPTY, KeymanagerConstant.EMPTY, KeymanagerConstant.STOREKEYALIAS); - KeyAlias keyAlias = new KeyAlias(); - keyAlias.setAlias(alias); - keyAlias.setApplicationId(applicationId); - keyAlias.setReferenceId(referenceId); - keyAlias.setKeyGenerationTime(timeStamp); - keyAlias.setKeyExpiryTime(expiryDateTime); - keyAliasRepository.saveAndFlush(keymanagerUtil.setMetaData(keyAlias)); - } - - /** - * Function to store key in DB store - * - * @param alias alias - * @param masterAlias masterAlias - * @param publicKey publicKey - * @param encryptedPrivateKey encryptedPrivateKey - */ - public void storeKeyInDBStore(String alias, String masterAlias, String certificateData, String encryptedPrivateKey) { - KeyStore dbKeyStore = new KeyStore(); - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.EMPTY, KeymanagerConstant.EMPTY, KeymanagerConstant.STOREDBKEY); - dbKeyStore.setAlias(alias); - dbKeyStore.setMasterAlias(masterAlias); - dbKeyStore.setCertificateData(certificateData); - dbKeyStore.setPrivateKey(encryptedPrivateKey); - keyStoreRepository.saveAndFlush(keymanagerUtil.setMetaData(dbKeyStore)); - } - - /** - * Function to get keyalias from keyalias table - * - * @param applicationId applicationId - * @param referenceId referenceId - * @param timeStamp timeStamp - * @return a map containing a list of all keyalias matching applicationId and - * referenceId with key "keyAlias"; and a list of all keyalias with - * matching timestamp with key "currentKeyAlias" - */ - public Map> getKeyAliases(String applicationId, String referenceId, LocalDateTime timeStamp) { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.EMPTY, KeymanagerConstant.EMPTY, KeymanagerConstant.GETALIAS); - Map> hashmap = new HashMap<>(); - List keyAliases = keyAliasRepository.findByApplicationIdAndReferenceId(applicationId, referenceId) - .stream() - .sorted((alias1, alias2) -> alias1.getKeyGenerationTime().compareTo(alias2.getKeyGenerationTime())) - .collect(Collectors.toList()); - List currentKeyAliases = keyAliases.stream() - .filter(keyAlias -> keymanagerUtil.isValidTimestamp(timeStamp, keyAlias)).collect(Collectors.toList()); - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.KEYALIAS, Arrays.toString(keyAliases.toArray()), - KeymanagerConstant.KEYALIAS); - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.CURRENTKEYALIAS, - Arrays.toString(currentKeyAliases.toArray()), KeymanagerConstant.CURRENTKEYALIAS); - hashmap.put(KeymanagerConstant.KEYALIAS, keyAliases); - hashmap.put(KeymanagerConstant.CURRENTKEYALIAS, currentKeyAliases); - return hashmap; - } - - /** - * Function to get expiry datetime using keypolicy table. If a overlapping key - * exists for same time interval, then expiry datetime of current key will be - * till generation datetime of overlapping key - * - * @param applicationId applicationId - * @param timeStamp timeStamp - * @param keyAlias keyAlias - * @return expiry datetime - */ - public LocalDateTime getExpiryPolicy(String applicationId, LocalDateTime timeStamp, List keyAlias) { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.APPLICATIONID, applicationId, - KeymanagerConstant.GETEXPIRYPOLICY); - Optional keyPolicy = keyPolicyRepository.findByApplicationId(applicationId); - if (!keyPolicy.isPresent()) { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.KEYPOLICY, keyPolicy.toString(), - "Key Policy not found for this application Id. Throwing exception"); - throw new InvalidApplicationIdException(KeymanagerErrorConstant.APPLICATIONID_NOT_VALID.getErrorCode(), - KeymanagerErrorConstant.APPLICATIONID_NOT_VALID.getErrorMessage()); - } - LocalDateTime policyExpiryTime = timeStamp.plusDays(keyPolicy.get().getValidityInDays()); - if (!keyAlias.isEmpty()) { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.KEYALIAS, String.valueOf(keyAlias.size()), - "Getting expiry policy. KeyAlias exists"); - for (KeyAlias alias : keyAlias) { - if (keymanagerUtil.isOverlapping(timeStamp, policyExpiryTime, alias.getKeyGenerationTime(), - alias.getKeyExpiryTime())) { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.EMPTY, KeymanagerConstant.EMPTY, - "Overlapping timestamp found. Changing policyExpiryTime"); - policyExpiryTime = alias.getKeyGenerationTime().minusSeconds(1); - break; - } - } - } - return policyExpiryTime; - } - - /** - * Function to fetch Keystore from DB. - * - * @param keyAlias alias of the key. - * @return KeyStore {@KeyStore} - */ - public Optional getKeyStoreFromDB(String keyAlias) { - Optional dbKeyStore = keyStoreRepository.findByAlias(keyAlias); - /* if (!dbKeyStore.isPresent()) { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.DBKEYSTORE, dbKeyStore.toString(), - "Key in DB Store does not exists. Throwing exception"); - throw new NoUniqueAliasException(KeymanagerErrorConstant.NO_UNIQUE_ALIAS.getErrorCode(), KeymanagerErrorConstant.NO_UNIQUE_ALIAS.getErrorMessage()); - } */ - return dbKeyStore; - } - - /** - * Function to fetch KeyPolicy from DB. - * - * @param applicationId App Id of the key. - * @return KeyPolicy {@KeyPolicy} - */ - public Optional getKeyPolicy(String applicationId){ - Optional keyPolicy = keyPolicyRepository.findByApplicationIdAndIsActive(applicationId, true); - if (!keyPolicy.isPresent()) { - LOGGER.error(KeymanagerConstant.SESSIONID, KeymanagerConstant.KEYPOLICY, keyPolicy.toString(), - "Key Policy not found for this application Id."); - throw new InvalidApplicationIdException(KeymanagerErrorConstant.APPLICATIONID_NOT_VALID.getErrorCode(), - KeymanagerErrorConstant.APPLICATIONID_NOT_VALID.getErrorMessage()); - } - return keyPolicy; - } -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/logger/KeymanagerLogger.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/logger/KeymanagerLogger.java deleted file mode 100644 index 762eabd3cb7..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/logger/KeymanagerLogger.java +++ /dev/null @@ -1,30 +0,0 @@ -package io.mosip.kernel.keymanagerservice.logger; - -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.logger.logback.factory.Logfactory; - -/** - * Keymanager logger. - * - * @author Dharmesh Khandelwal - * @since 1.0.0 - * - */ -public final class KeymanagerLogger { - - /** - * Instantiates a new logger. - */ - private KeymanagerLogger() { - } - - /** - * Method to get the rolling file logger for the class provided. - * - * @param clazz the clazz - * @return the logger - */ - public static Logger getLogger(Class clazz) { - return Logfactory.getSlf4jLogger(clazz); - } -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/repository/CACertificateStoreRepository.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/repository/CACertificateStoreRepository.java deleted file mode 100644 index dc3e4e99103..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/repository/CACertificateStoreRepository.java +++ /dev/null @@ -1,83 +0,0 @@ - -package io.mosip.kernel.keymanagerservice.repository; - -import java.time.LocalDateTime; -import java.util.List; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; -import org.springframework.stereotype.Repository; - -import io.mosip.kernel.keymanagerservice.entity.CACertificateStore; - -/** - * This interface CACertificateStoreRepository for CRUD operations for CA/Sub-CA certificates. - * - * @author Mahammed Taheer - * @since 1.1.2 - * - */ -@Repository -public interface CACertificateStoreRepository extends JpaRepository { - - /** - * Function to find CACertificates by Certificate Subject and Certificate Issuer. - * - * @param certSubject Certificate Subject - * @param certIssuer Certificate Issuer - * @return list of CACertificateStore - */ - List findByCertSubjectAndCertIssuer(String certSubject, String certIssuer); - - - /** - * Function to find CACertificate by Certificate thumbprint. - * - * @param certThumbprint Certificate Thumbprint - * @return CACertificateStore - */ - CACertificateStore findByCertThumbprint(String certThumbprint); - - /** - * Function to fetch all CACertificates. - * - * @return list of CACertificateStore - */ - List findAll(); - - /** - * Function to find CACertificates by Certificate Subject. - * - * @param certSubject Certificate Subject - * @return list of CACertificateStore - */ - List findByCertSubject(String certSubject); - - /** - * Function to find CACertificates by Partner Domain. - * - * @param partnerDomain Certificate Subject - * @return list of CACertificateStore - */ - List findByPartnerDomain(String partnerDomain); - - /** - * Function to find CACertificate by Certificate thumbprint and Partner domain. - * - * @param certThumbprint Certificate Thumbprint - * @param partnerDomain Partner Domain - * - * @return CACertificateStore - */ - CACertificateStore findByCertThumbprintAndPartnerDomain(String certThumbprint, String partnerDomain); - - /** - * Function to find all CACertificate created , updated or deleted time is within the lastUpdated and current time - * @param lastUpdated - * @param currentTimestamp - * @return - */ - @Query("FROM CACertificateStore WHERE (createdtimes BETWEEN ?1 AND ?2) OR (updatedtimes BETWEEN ?1 AND ?2) OR (deletedtimes BETWEEN ?1 AND ?2)") - List findAllLatestCreatedUpdateDeleted(LocalDateTime lastUpdated, LocalDateTime currentTimestamp); - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/repository/DataEncryptKeystoreRepository.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/repository/DataEncryptKeystoreRepository.java deleted file mode 100644 index 59b51a8d053..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/repository/DataEncryptKeystoreRepository.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.mosip.kernel.keymanagerservice.repository; - -import java.util.List; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; -import org.springframework.stereotype.Repository; - -import io.mosip.kernel.keymanagerservice.entity.DataEncryptKeystore; - -/** - * The Interface DataEncryptKeystoreRepository. - * - * @author Mahammed Taheer - */ -@Repository -public interface DataEncryptKeystoreRepository extends JpaRepository{ - - /** - * Find key by id. - * - * @param id the id - * @return the string - */ - @Query("SELECT d.key from DataEncryptKeystore d where d.id = :id") - String findKeyById(@Param("id") Integer id); - - /** - * Gets the ids by key status. - * - * @param status the status - * @return the ids by key status - */ - @Query("SELECT d.id from DataEncryptKeystore d where d.keyStatus = :status") - List getIdsByKeyStatus(@Param("status") String status); - - /** - * Get the max id. - * - * @return the max id - */ - @Query("SELECT MAX(d.id) from DataEncryptKeystore d") - Long findMaxId(); -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/repository/EncryptionDao.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/repository/EncryptionDao.java deleted file mode 100644 index 84ddbb7a564..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/repository/EncryptionDao.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * package io.mosip.kernel.keymanagerservice.repository; - * - * import javax.persistence.EntityManager; import - * javax.persistence.PersistenceContext; import javax.persistence.Query; - * - * import org.springframework.stereotype.Repository; import - * org.springframework.transaction.annotation.Transactional; - * - * import io.mosip.kernel.keymanagerservice.entity.SecreteKeyStore; - * - * @Repository - * - * @Transactional public class EncryptionDao { - * - * - * @PersistenceContext private EntityManager entityManager; - * - * public void createPerson(Object entity) { try { - * entityManager.persist(entity); } catch (Exception e) { e.printStackTrace(); } - * finally { entityManager.close(); } } - * - * public void saveKey(SecreteKeyStore secretKey) { try { - * entityManager.persist(secretKey); } catch (Exception e) { - * e.printStackTrace(); } } - * - * public void updateKey(SecreteKeyStore secretKey) { try { - * entityManager.merge(secretKey); } catch (Exception e) { e.printStackTrace(); - * } } - * - * public SecreteKeyStore getKey(String id) { try { SecreteKeyStore - * secrteKeyStore = entityManager.find(SecreteKeyStore.class, id); return - * secrteKeyStore; } catch (Exception e) { e.printStackTrace(); } return null; } - * - * public SecreteKeyStore getKey() { try { Query query = entityManager. - * createQuery("SELECT e FROM SecreteKeyStore e where e.expired='false'"); - * return (SecreteKeyStore) query.getSingleResult(); } catch (Exception e) { - * e.printStackTrace(); } return null; - * - * } } - */ \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/repository/KeyAliasRepository.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/repository/KeyAliasRepository.java deleted file mode 100644 index 64ba2aa9319..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/repository/KeyAliasRepository.java +++ /dev/null @@ -1,37 +0,0 @@ -package io.mosip.kernel.keymanagerservice.repository; - -import java.util.List; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import io.mosip.kernel.keymanagerservice.entity.KeyAlias; - -/** - * This interface extends BaseRepository which provides with the methods for - * several CRUD operations. - * - * @author Dharmesh Khandelwal - * @since 1.0.0 - * - */ -@Repository -public interface KeyAliasRepository extends JpaRepository { - - /** - * Function to find keyalias by applicationId and referenceId - * - * @param applicationId applicationId - * @param referenceId referenceId - * @return list of keyalias - */ - List findByApplicationIdAndReferenceId(String applicationId, String referenceId); - - /** - * Function to find keyalias by applicationId - * - * @param applicationId applicationId - * @return list of keyalias - */ - List findByApplicationId(String applicationId); -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/repository/KeyPolicyRepository.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/repository/KeyPolicyRepository.java deleted file mode 100644 index 8bb4d4a95c2..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/repository/KeyPolicyRepository.java +++ /dev/null @@ -1,38 +0,0 @@ -package io.mosip.kernel.keymanagerservice.repository; - -import java.util.Optional; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import io.mosip.kernel.keymanagerservice.entity.KeyPolicy; - -/** - * This interface extends BaseRepository which provides with the methods for - * several CRUD operations. - * - * @author Dharmesh Khandelwal - * @since 1.0.0 - * - */ -@Repository -public interface KeyPolicyRepository extends JpaRepository { - - /** - * Function to find KeyPolicy by applicationId - * - * @param applicationId applicationId - * @return KeyPolicy - */ - Optional findByApplicationId(String applicationId); - - - /** - * Function to find KeyPolicy by applicationId - * - * @param applicationId applicationId - * @return KeyPolicy - */ - Optional findByApplicationIdAndIsActive(String applicationId, boolean isActive); - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/repository/KeyStoreRepository.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/repository/KeyStoreRepository.java deleted file mode 100644 index 701245bf437..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/repository/KeyStoreRepository.java +++ /dev/null @@ -1,38 +0,0 @@ -package io.mosip.kernel.keymanagerservice.repository; - -import java.util.List; -import java.util.Optional; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import io.mosip.kernel.keymanagerservice.entity.KeyStore; - -/** - * This interface extends BaseRepository which provides with the methods for - * several CRUD operations. - * - * @author Dharmesh Khandelwal - * @since 1.0.0 - * - */ -@Repository -public interface KeyStoreRepository extends JpaRepository { - - /** - * Function to find KeyStore by alias - * - * @param alias alias - * @return KeyStore - */ - Optional findByAlias(String alias); - - - /** - * Function to find all KeyStore objects by masterAlias - * - * @param masterAlias master Alias - * @return List of KeyStore - */ - List findByMasterAlias(String masterAlias); -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/repository/PartnerCertificateStoreRepository.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/repository/PartnerCertificateStoreRepository.java deleted file mode 100644 index e4b4a6bd608..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/repository/PartnerCertificateStoreRepository.java +++ /dev/null @@ -1,62 +0,0 @@ -package io.mosip.kernel.keymanagerservice.repository; - -import java.util.List; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import io.mosip.kernel.keymanagerservice.entity.PartnerCertificateStore; - -/** - * This interface PartnerCertificateStoreRepository for CRUD operations for Partner certificates. - * - * @author Mahammed Taheer - * @since 1.1.2 - * - */ -@Repository -public interface PartnerCertificateStoreRepository extends JpaRepository { - - /** - * Function to find Partner Certificates by Certificate Subject and Certificate Issuer. - * - * @param certSubject Certificate Subject - * @param cercertIssuertSubject Certificate Issuer - * @return list of PartnerCertificateStore - */ - List findByCertSubjectAndCertIssuer(String certSubject, String certIssuer); - - - /** - * Function to find Partner Certificate by Certificate thumbprint. - * - * @param certThumbprint Certificate Thumbprint - * @return PartnerCertificateStore - */ - PartnerCertificateStore findByCertThumbprint(String certThumbprint); - - /** - * Function to find CACertificates by Certificate Subject. - * - * @param certSubject Certificate Subject - * @return list of PartnerCertificateStore - */ - List findByCertSubject(String certSubject); - - /** - * Function to find Partner Certificate by Certificate ID. - * - * @param certId Certificate ID - * @return PartnerCertificateStore - */ - PartnerCertificateStore findByCertId(String certId); - - /** - * Function to find Partner Certificate by Certificate thumbprint. - * - * @param certThumbprint Certificate Thumbprint - * @param partnerDomain Partner Domain - * @return PartnerCertificateStore - */ - List findByCertThumbprintAndPartnerDomain(String certThumbprint, String partnerDomain); -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/repository/SimpleAES.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/repository/SimpleAES.java deleted file mode 100644 index c8716baaacc..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/repository/SimpleAES.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * package io.mosip.kernel.keymanagerservice.repository; - * - * import java.io.UnsupportedEncodingException; import - * java.security.MessageDigest; import java.security.NoSuchAlgorithmException; - * import java.time.LocalDateTime; import java.time.ZoneId; import - * java.util.Arrays; import java.util.Base64; import java.util.UUID; - * - * import javax.annotation.PostConstruct; import javax.crypto.Cipher; import - * javax.crypto.spec.SecretKeySpec; - * - * import org.springframework.beans.factory.annotation.Autowired; import - * org.springframework.stereotype.Component; - * - * import io.mosip.kernel.keymanagerservice.entity.SecreteKeyStore; - * - * - * - * @Component public class SimpleAES { - * - * private static EncryptionDao encryptionDao; - * - * final static String secret = "Encryption"; - * - * private static String index; - * - * @Autowired public SimpleAES(EncryptionDao encryptionDao) { - * SimpleAES.encryptionDao = encryptionDao; } - * - * private static SecretKeySpec secretKey; private static byte[] key; - * - * private static SecreteKeyStore keyStore; - * - * @PostConstruct public void initialKeyStore() { keyStore = - * encryptionDao.getKey(); LocalDateTime localTime = - * LocalDateTime.now(ZoneId.of("UTC")); if (keyStore == null) { - * newKey(localTime.plusDays(2)); } else { - * System.out.println(keyStore.getExpiryDate().compareTo(localTime)); if - * (keyStore.getExpiryDate().compareTo(localTime) < 0) { - * keyStore.setExpired(true); encryptionDao.updateKey(keyStore); - * newKey(localTime.plusDays(2)); } else { byte[] decodedKey = - * Base64.getDecoder().decode(keyStore.getKey()); secretKey = new - * SecretKeySpec(decodedKey, 0,decodedKey.length, "AES"); index = - * keyStore.getId(); } - * - * } } - * - * public static void setKey() { MessageDigest sha = null; try { key = - * secret.getBytes("UTF-8"); sha = MessageDigest.getInstance("SHA-1"); key = - * sha.digest(key); key = Arrays.copyOf(key, 16); secretKey = new - * SecretKeySpec(key, "AES"); } catch (NoSuchAlgorithmException e) { - * e.printStackTrace(); } catch (UnsupportedEncodingException e) { - * e.printStackTrace(); } } - * - * public static SecretKeySpec getKey(String skey) { MessageDigest sha = null; - * try { key = skey.getBytes("UTF-8"); sha = MessageDigest.getInstance("SHA-1"); - * key = sha.digest(key); key = Arrays.copyOf(key, 16); secretKey = new - * SecretKeySpec(key, "AES"); } catch (NoSuchAlgorithmException e) { - * e.printStackTrace(); } catch (UnsupportedEncodingException e) { - * e.printStackTrace(); } return secretKey; } - * - * public static void newKey(LocalDateTime d) { secretKey = getKey(secret); UUID - * uuid = UUID.randomUUID(); String randomUUIDString = uuid.toString(); - * SecreteKeyStore entity = new SecreteKeyStore(); - * entity.setKey(Base64.getEncoder().encodeToString(secretKey.getEncoded())); - * entity.setExpired(false); entity.setExpiryDate(d); - * entity.setCreateDateTime(LocalDateTime.now(ZoneId.of("UTC"))); - * entity.setCreatedBy("Rajath"); - * entity.setGenratedtimes(LocalDateTime.now(ZoneId.of("UTC"))); - * entity.setId(randomUUIDString); encryptionDao.saveKey(entity); keyStore = - * entity; index = entity.getId(); System.out.println("entity " + entity); } - * - * public static String encrypt(String strToEncrypt) { try { Cipher cipher = - * Cipher.getInstance("AES/ECB/PKCS5Padding"); LocalDateTime localTime = - * LocalDateTime.now(ZoneId.of("UTC")); if - * (keyStore.getExpiryDate().compareTo(localTime) < 0) { - * keyStore.setExpired(true); encryptionDao.updateKey(keyStore); - * newKey(localTime.plusDays(2)); } cipher.init(Cipher.ENCRYPT_MODE, secretKey); - * return index + ":" + - * Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes( - * "UTF-8"))); } catch (Exception e) { - * System.out.println("Error while encrypting: " + e.toString()); } return null; - * } - * - * public static String decrypt(String strToDecrypt) { try { - * - * String[] str = strToDecrypt.split(":"); String in = str[0]; SecreteKeyStore - * entity = encryptionDao.getKey(in); Cipher cipher = - * Cipher.getInstance("AES/ECB/PKCS5PADDING"); byte[] decodedKey = - * Base64.getDecoder().decode(entity.getKey()); cipher.init(Cipher.DECRYPT_MODE, - * new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES")); String op = new - * String(cipher.doFinal(Base64.getDecoder().decode(str[1]))); - * System.out.println("output " + op); return op; } catch (Exception e) { - * System.out.println("Error while decrypting: " + e.toString()); } return null; - * } - * - * } - */ \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/service/KeymanagerService.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/service/KeymanagerService.java deleted file mode 100644 index 132dc6db5ae..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/service/KeymanagerService.java +++ /dev/null @@ -1,120 +0,0 @@ -package io.mosip.kernel.keymanagerservice.service; - -import java.util.Optional; - -import io.mosip.kernel.keymanagerservice.dto.CSRGenerateRequestDto; -import io.mosip.kernel.keymanagerservice.dto.KeyPairGenerateRequestDto; -import io.mosip.kernel.keymanagerservice.dto.KeyPairGenerateResponseDto; -import io.mosip.kernel.keymanagerservice.dto.PublicKeyResponse; -import io.mosip.kernel.keymanagerservice.dto.RevokeKeyRequestDto; -import io.mosip.kernel.keymanagerservice.dto.RevokeKeyResponseDto; -import io.mosip.kernel.keymanagerservice.dto.SignatureCertificate; -import io.mosip.kernel.keymanagerservice.dto.SymmetricKeyGenerateRequestDto; -import io.mosip.kernel.keymanagerservice.dto.SymmetricKeyGenerateResponseDto; -import io.mosip.kernel.keymanagerservice.dto.SymmetricKeyRequestDto; -import io.mosip.kernel.keymanagerservice.dto.SymmetricKeyResponseDto; -import io.mosip.kernel.keymanagerservice.dto.UploadCertificateRequestDto; -import io.mosip.kernel.keymanagerservice.dto.UploadCertificateResponseDto; - -/** - * This interface provides the methods which can be used for Key management - * - * @author Dharmesh Khandelwal - * @author Urvil Joshi - * @since 1.0.0 - * - */ -public interface KeymanagerService { - - /** - * Function to decrypt symmetric key - * - * @param symmetricKeyRequestDto symmetricKeyRequestDto - * @return {@link SymmetricKeyResponseDto} instance - */ - public SymmetricKeyResponseDto decryptSymmetricKey(SymmetricKeyRequestDto symmetricKeyRequestDto); - - /** - * Function to get public key - * - * @param applicationId applicationId - * @param timeStamp timeStamp - * @param referenceId referenceId - * @return {@link PublicKeyResponse} instance - */ - //public PublicKeyResponse getPublicKey(String applicationId, String timeStamp, Optional referenceId); - - public PublicKeyResponse getSignPublicKey(String applicationId, String timeStamp, - Optional referenceId); - - public SignatureCertificate getSignatureCertificate(String applicationId, Optional referenceId, - String timestamp); - - /** - * Function to generate Master key pair in the HSM specified in config. - * - * @param KeyPairGenerateRequestDto request - * @return {@link KeyPairGenerateResponseDto} instance - */ - public KeyPairGenerateResponseDto generateMasterKey(String objectType, KeyPairGenerateRequestDto request); - - /** - * Function to get certificate for the provided appId & refId. - * - * @param Application ID appId - * @param Reference ID refId - * @return {@link KeyPairGenerateResponseDto} instance - */ - public KeyPairGenerateResponseDto getCertificate(String appId, Optional refId); - - /** - * Function to generate CSR for the provided appId & refId. - * - * @param CSRGenerateRequestDto request - * @return {@link CSRGenerateRequestDto} instance - */ - public KeyPairGenerateResponseDto generateCSR(CSRGenerateRequestDto csrGenRequestDto); - - /** - * Function to upload certificate for the provided appId & refId. - * - * @param UploadCertificateRequestDto request - * @return {@link UploadCertificateResponseDto} instance - */ - public UploadCertificateResponseDto uploadCertificate(UploadCertificateRequestDto uploadCertRequestDto); - - /** - * Function to upload other domain certificate for the provided appId & refId. - * - * @param UploadCertificateRequestDto request - * @return {@link UploadCertificateResponseDto} instance - */ - public UploadCertificateResponseDto uploadOtherDomainCertificate(UploadCertificateRequestDto uploadCertRequestDto); - - - /** - * Function to generate Symmetric key for the provided appId & refId. - * - * @param SymmetricKeyGenerateRequestDto symGenRequestDto - * @return {@link SymmetricKeyGenerateRequestDto} instance - */ - public SymmetricKeyGenerateResponseDto generateSymmetricKey(SymmetricKeyGenerateRequestDto symGenRequestDto); - - /** - * Check certificate exists for the provided appId & refId. - * - * @param UploadCertificateRequestDto uploadCertRequestDto - * @return {@link UploadCertificateResponseDto} instance - */ - //public UploadCertificateResponseDto isCertificateExists(UploadCertificateRequestDto uploadCertRequestDto); - - /** - * Key Revocation for the provided appId & refId. - * - * @param RevokeKeyRequestDto revokeKeyRequestDto - * @return {@link RevokeKeyResponseDto} instance - */ - public RevokeKeyResponseDto revokeKey(RevokeKeyRequestDto revokeKeyRequestDto); - -} - diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/service/impl/KeymanagerServiceImpl.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/service/impl/KeymanagerServiceImpl.java deleted file mode 100644 index a4c9b829053..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/service/impl/KeymanagerServiceImpl.java +++ /dev/null @@ -1,1368 +0,0 @@ -package io.mosip.kernel.keymanagerservice.service.impl; - -import java.security.KeyFactory; -import java.security.KeyPair; -import java.security.KeyStore.PrivateKeyEntry; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.cert.Certificate; -import java.security.cert.X509Certificate; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.PKCS8EncodedKeySpec; -import java.time.LocalDateTime; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.UUID; - -import javax.crypto.SecretKey; -import javax.security.auth.x500.X500Principal; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import io.mosip.kernel.core.crypto.exception.InvalidDataException; -import io.mosip.kernel.core.crypto.exception.InvalidKeyException; -import io.mosip.kernel.core.crypto.exception.NullDataException; -import io.mosip.kernel.core.crypto.exception.NullKeyException; -import io.mosip.kernel.core.crypto.exception.NullMethodException; -import io.mosip.kernel.core.crypto.spi.CryptoCoreSpec; -import io.mosip.kernel.core.exception.BaseUncheckedException; -import io.mosip.kernel.core.keymanager.exception.KeystoreProcessingException; -import io.mosip.kernel.core.keymanager.exception.NoSuchSecurityProviderException; -import io.mosip.kernel.core.keymanager.model.CertificateEntry; -import io.mosip.kernel.core.keymanager.model.CertificateParameters; -import io.mosip.kernel.core.keymanager.spi.KeyStore; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.CryptoUtil; -import io.mosip.kernel.core.util.DateUtils; -import io.mosip.kernel.cryptomanager.constant.CryptomanagerConstant; -import io.mosip.kernel.cryptomanager.util.CryptomanagerUtils; -import io.mosip.kernel.keygenerator.bouncycastle.KeyGenerator; -import io.mosip.kernel.keymanager.hsm.util.CertificateUtility; -import io.mosip.kernel.keymanagerservice.constant.KeymanagerConstant; -import io.mosip.kernel.keymanagerservice.constant.KeymanagerErrorConstant; -import io.mosip.kernel.keymanagerservice.dto.CSRGenerateRequestDto; -import io.mosip.kernel.keymanagerservice.dto.CertificateInfo; -import io.mosip.kernel.keymanagerservice.dto.KeyPairGenerateRequestDto; -import io.mosip.kernel.keymanagerservice.dto.KeyPairGenerateResponseDto; -import io.mosip.kernel.keymanagerservice.dto.PublicKeyResponse; -import io.mosip.kernel.keymanagerservice.dto.RevokeKeyRequestDto; -import io.mosip.kernel.keymanagerservice.dto.RevokeKeyResponseDto; -import io.mosip.kernel.keymanagerservice.dto.SignatureCertificate; -import io.mosip.kernel.keymanagerservice.dto.SymmetricKeyGenerateRequestDto; -import io.mosip.kernel.keymanagerservice.dto.SymmetricKeyGenerateResponseDto; -import io.mosip.kernel.keymanagerservice.dto.SymmetricKeyRequestDto; -import io.mosip.kernel.keymanagerservice.dto.SymmetricKeyResponseDto; -import io.mosip.kernel.keymanagerservice.dto.UploadCertificateRequestDto; -import io.mosip.kernel.keymanagerservice.dto.UploadCertificateResponseDto; -import io.mosip.kernel.keymanagerservice.entity.KeyAlias; -import io.mosip.kernel.keymanagerservice.entity.KeyPolicy; -import io.mosip.kernel.keymanagerservice.exception.CryptoException; -import io.mosip.kernel.keymanagerservice.exception.InvalidResponseObjectTypeException; -import io.mosip.kernel.keymanagerservice.exception.KeymanagerServiceException; -import io.mosip.kernel.keymanagerservice.exception.NoUniqueAliasException; -import io.mosip.kernel.keymanagerservice.helper.KeymanagerDBHelper; -import io.mosip.kernel.keymanagerservice.logger.KeymanagerLogger; -import io.mosip.kernel.keymanagerservice.service.KeymanagerService; -import io.mosip.kernel.keymanagerservice.util.KeymanagerUtil; - -/** - * This class provides the implementation for the methods of KeymanagerService - * interface. - * - * @author Dharmesh Khandelwal - * @author Urvil Joshi - * @author Srinivasan - * @since 1.0.0 - * - */ -@Service -@Transactional -public class KeymanagerServiceImpl implements KeymanagerService { - - private static final String VALID_REFERENCE_ID_GETTING_KEY_ALIAS_WITH_REFERENCE_ID = "Valid reference Id. Getting key alias with referenceId"; - - private static final String NOT_A_VALID_REFERENCE_ID_GETTING_KEY_ALIAS_WITHOUT_REFERENCE_ID = "Not a valid reference Id. Getting key alias without referenceId"; - - private static final Logger LOGGER = KeymanagerLogger.getLogger(KeymanagerServiceImpl.class); - - @Value("${mosip.root.key.applicationid:ROOT}") - private String rootKeyApplicationId; - - @Value("${mosip.sign-certificate-refid:SIGN}") - private String certificateSignRefID; - - /** The sign applicationid. */ - @Value("${mosip.sign.applicationid:KERNEL}") - private String signApplicationid; - - @Value("${mosip.kernel.certificate.sign.algorithm:SHA256withRSA}") - private String signAlgorithm; - - /** The 1.1.3 no thumbprint support flag. */ - @Value("${mosip.kernel.keymanager.113nothumbprint.support:false}") - private boolean noThumbprint; - - /** - * Keystore instance to handles and store cryptographic keys. - */ - @Autowired - private KeyStore keyStore; - - /** - * KeyGenerator instance to generate asymmetric key pairs - */ - @Autowired - private KeyGenerator keyGenerator; - - /** - * {@link CryptoCoreSpec} instance for cryptographic functionalities. - */ - @Autowired - private CryptoCoreSpec cryptoCore; - - /** - * Utility to generate Metadata - */ - @Autowired - KeymanagerUtil keymanagerUtil; - - /** - * KeymanagerDBHelper instance to handle all DB operations - */ - @Autowired - private KeymanagerDBHelper dbHelper; - - /** - * {@link CryptomanagerUtils} instance - */ - @Autowired - CryptomanagerUtils cryptomanagerUtil; - - /** - * Function to get Certificate from HSM. On first request for an applicationId - * and duration, will create a new keypair. - * - * @param applicationId applicationId - * @param timeStamp timeStamp - * @return {@link CertificateInfo} instance - */ - private CertificateInfo getCertificateFromHSM(String applicationId, LocalDateTime timeStamp, String referenceId) { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.APPLICATIONID, applicationId, - KeymanagerConstant.GETPUBLICKEYHSM); - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.TIMESTAMP, timeStamp.toString(), - KeymanagerConstant.GETPUBLICKEYHSM); - - String alias = null; - Optional keyPolicy = dbHelper.getKeyPolicy(applicationId); - Map> keyAliasMap = dbHelper.getKeyAliases(applicationId, referenceId, timeStamp); - List currentKeyAlias = keyAliasMap.get(KeymanagerConstant.CURRENTKEYALIAS); - List keyAlias = keyAliasMap.get(KeymanagerConstant.KEYALIAS); - - if (keyAlias.isEmpty()) { - LOGGER.error(KeymanagerConstant.SESSIONID, KeymanagerConstant.KEYALIAS, String.valueOf(keyAlias.size()), - "Initial Key generation process not completed."); - throw new KeymanagerServiceException(KeymanagerErrorConstant.KEY_GENERATION_NOT_DONE.getErrorCode(), - KeymanagerErrorConstant.KEY_GENERATION_NOT_DONE.getErrorMessage()); - } - - if (currentKeyAlias.size() > 1) { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.CURRENTKEYALIAS, - String.valueOf(currentKeyAlias.size()), "CurrentKeyAlias size more than one Throwing exception"); - throw new NoUniqueAliasException(KeymanagerErrorConstant.NO_UNIQUE_ALIAS.getErrorCode(), - KeymanagerErrorConstant.NO_UNIQUE_ALIAS.getErrorMessage()); - } else if (currentKeyAlias.size() == 1) { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.CURRENTKEYALIAS, - currentKeyAlias.get(0).getAlias(), "CurrentKeyAlias size is one fetching keypair using this alias"); - KeyAlias fetchedKeyAlias = currentKeyAlias.get(0); - alias = fetchedKeyAlias.getAlias(); - } else if (currentKeyAlias.isEmpty()) { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.CURRENTKEYALIAS, - String.valueOf(currentKeyAlias.size()), - "CurrentKeyAlias size is zero. Will create new Keypair for this applicationId and timestamp"); - alias = UUID.randomUUID().toString(); - generateKeyPairInHSM(alias, applicationId, referenceId, timeStamp, keyAlias); - } - X509Certificate x509Cert = (X509Certificate) keyStore.getCertificate(alias); - return new CertificateInfo<>(alias, x509Cert); - } - - private void generateKeyPairInHSM(String alias, String applicationId, String referenceId, - LocalDateTime timeStamp, List keyAlias) { - LocalDateTime generationDateTime = timeStamp; - LocalDateTime expiryDateTime = dbHelper.getExpiryPolicy(applicationId, generationDateTime, keyAlias); - String rootKeyAlias = getRootKeyAlias(applicationId, timeStamp); - X500Principal latestCertPrincipal = getLatestCertPrincipal(keyAlias); - CertificateParameters certParams = keymanagerUtil.getCertificateParameters(latestCertPrincipal, - generationDateTime, expiryDateTime); - keyStore.generateAndStoreAsymmetricKey(alias, rootKeyAlias, certParams); - dbHelper.storeKeyInAlias(applicationId, generationDateTime, referenceId, alias, expiryDateTime); - } - - - private X500Principal getLatestCertPrincipal(List keyAlias) { - KeyAlias latestKeyAlias = keyAlias.get(0); - String alias = latestKeyAlias.getAlias(); - X509Certificate signCert = (X509Certificate) keyStore.getCertificate(alias); - return signCert.getSubjectX500Principal(); - } - - /** - * Function to get public key from DB store. On first request for an - * applicationId, referenceId and duration, will create a new keypair. - * - * @param applicationId applicationId - * @param timeStamp timeStamp - * @param referenceId referenceId - * @return {@link PublicKeyResponse} instance - */ - private CertificateInfo getCertificateFromDBStore(String applicationId, LocalDateTime timeStamp, - String referenceId) { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.APPLICATIONID, applicationId, - KeymanagerConstant.GETPUBLICKEYDB); - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.TIMESTAMP, timeStamp.toString(), - KeymanagerConstant.GETPUBLICKEYDB); - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.REFERENCEID, referenceId, - KeymanagerConstant.GETPUBLICKEYDB); - - String alias = null; - X509Certificate x509Cert = null; - - Map> keyAliasMap = dbHelper.getKeyAliases(applicationId, referenceId, timeStamp); - List currentKeyAlias = keyAliasMap.get(KeymanagerConstant.CURRENTKEYALIAS); - - if (currentKeyAlias.size() > 1) { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.CURRENTKEYALIAS, - String.valueOf(currentKeyAlias.size()), "CurrentKeyAlias size more than one. Throwing exception"); - throw new NoUniqueAliasException(KeymanagerErrorConstant.NO_UNIQUE_ALIAS.getErrorCode(), - KeymanagerErrorConstant.NO_UNIQUE_ALIAS.getErrorMessage()); - } else if (currentKeyAlias.size() == 1) { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.CURRENTKEYALIAS, - currentKeyAlias.get(0).getAlias(), - "CurrentKeyAlias size is one. Will fetch keypair using this alias"); - Optional keyFromDBStore = dbHelper - .getKeyStoreFromDB(currentKeyAlias.get(0).getAlias()); - if (!keyFromDBStore.isPresent()) { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.KEYFROMDB, keyFromDBStore.toString(), - "Key in DBStore does not exist for this alias. Throwing exception"); - throw new NoUniqueAliasException(KeymanagerErrorConstant.NO_UNIQUE_ALIAS.getErrorCode(), - KeymanagerErrorConstant.NO_UNIQUE_ALIAS.getErrorMessage()); - } else { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.KEYFROMDB, - currentKeyAlias.get(0).getAlias(), - "Key in DBStore exists for this alias. Fetching Certificate."); - KeyAlias fetchedKeyAlias = currentKeyAlias.get(0); - alias = fetchedKeyAlias.getAlias(); - String certificateData = keyFromDBStore.get().getCertificateData(); - x509Cert = (X509Certificate) keymanagerUtil.convertToCertificate(certificateData); - } - } else if (currentKeyAlias.isEmpty()) { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.CURRENTKEYALIAS, - String.valueOf(currentKeyAlias.size()), - "CurrentKeyAlias size is zero. Will create new Keypair for this applicationId, referenceId and timestamp"); - List keyAlias = keyAliasMap.get(KeymanagerConstant.KEYALIAS); - if (!keyAlias.isEmpty()) { - keyAlias.forEach(innerAlias -> { - String ksAlias = innerAlias.getAlias(); - Optional keyFromDBStore = dbHelper.getKeyStoreFromDB(ksAlias); - String masterKeyAlias = keyFromDBStore.get().getMasterAlias(); - String privateKeyObj = keyFromDBStore.get().getPrivateKey(); - - if (ksAlias.equals(masterKeyAlias) || privateKeyObj.equals(KeymanagerConstant.KS_PK_NA)) { - LOGGER.error(KeymanagerConstant.SESSIONID, KeymanagerConstant.APPLICATIONID, null, - "Not Allowed to generate New Key Pair for other domains."); - throw new KeymanagerServiceException(KeymanagerErrorConstant.GENERATION_NOT_ALLOWED.getErrorCode(), - KeymanagerErrorConstant.GENERATION_NOT_ALLOWED.getErrorMessage()); - } - }); - } - if (applicationId.equalsIgnoreCase(KeymanagerConstant.ROOT)){ - LOGGER.error(KeymanagerConstant.SESSIONID, KeymanagerConstant.APPLICATIONID, null, - "Not Allowed to generate Base Key for Root Key."); - throw new KeymanagerServiceException(KeymanagerErrorConstant.GENERATION_NOT_ALLOWED.getErrorCode(), - KeymanagerErrorConstant.GENERATION_NOT_ALLOWED.getErrorMessage()); - } - Optional keyPolicy = dbHelper.getKeyPolicy(applicationId); - String encryptedPrivateKey; - alias = UUID.randomUUID().toString(); - KeyPair keypair = keyGenerator.getAsymmetricKey(); - PrivateKey privateKey = keypair.getPrivate(); - /** - * Will get application's master key information from HSM. On first request for - * an applicationId and duration, will create a new keypair. - */ - CertificateInfo certInfo = getCertificateFromHSM(applicationId, timeStamp, KeymanagerConstant.EMPTY); - X509Certificate hsmX509Cert = certInfo.getCertificate(); - PublicKey masterPublicKey = hsmX509Cert.getPublicKey(); - - String masterAlias = certInfo.getAlias(); - LocalDateTime generationDateTime = timeStamp; - LocalDateTime expiryDateTime = dbHelper.getExpiryPolicy(KeymanagerConstant.BASE_KEY_POLICY_CONST, - generationDateTime, keyAliasMap.get(KeymanagerConstant.KEYALIAS)); - /** - * Before storing a keypair in db, will first encrypt its private key with - * application's master public key from softhsm's/HSM's keystore - */ - try { - encryptedPrivateKey = CryptoUtil.encodeBase64(keymanagerUtil.encryptKey(privateKey, masterPublicKey)); - } catch (InvalidDataException | InvalidKeyException | NullDataException | NullKeyException - | NullMethodException e) { - throw new CryptoException(KeymanagerErrorConstant.CRYPTO_EXCEPTION.getErrorCode(), - KeymanagerErrorConstant.CRYPTO_EXCEPTION.getErrorMessage() + e.getErrorText()); - } - PrivateKeyEntry signKeyEntry = keyStore.getAsymmetricKey(masterAlias); - PrivateKey signPrivateKey = signKeyEntry.getPrivateKey(); - X509Certificate signCert = (X509Certificate) signKeyEntry.getCertificate(); - X500Principal signerPrincipal = signCert.getSubjectX500Principal(); - - CertificateParameters certParams = keymanagerUtil.getCertificateParameters(signerPrincipal, - generationDateTime, expiryDateTime); - certParams.setCommonName(applicationId + "-" + referenceId); - x509Cert = (X509Certificate) CertificateUtility.generateX509Certificate(signPrivateKey, keypair.getPublic(), - certParams, signerPrincipal, signAlgorithm, keyStore.getKeystoreProviderName(), KeymanagerConstant.ENCRYPTION_KEY); - String certificateData = keymanagerUtil.getPEMFormatedData(x509Cert); - dbHelper.storeKeyInDBStore(alias, masterAlias, certificateData, encryptedPrivateKey); - dbHelper.storeKeyInAlias(applicationId, generationDateTime, referenceId, alias, expiryDateTime); - keymanagerUtil.destoryKey(privateKey); - } - return new CertificateInfo<>(alias, x509Cert); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.kernel.keymanager.service.KeymanagerService#decryptSymmetricKey(java - * .lang.String, java.time.LocalDateTime, java.util.Optional, byte[]) - */ - @Override - public SymmetricKeyResponseDto decryptSymmetricKey(SymmetricKeyRequestDto symmetricKeyRequestDto) { - LocalDateTime localDateTimeStamp = DateUtils.getUTCCurrentDateTime(); - String applicationId = symmetricKeyRequestDto.getApplicationId(); - String referenceId = symmetricKeyRequestDto.getReferenceId(); - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.SYMMETRICKEYREQUEST, - symmetricKeyRequestDto.getApplicationId(), "Request Application Id: " + applicationId); - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.SYMMETRICKEYREQUEST, - symmetricKeyRequestDto.getApplicationId(), "Request Reference Id: " + referenceId); - - Boolean reqPrependThumbprint = symmetricKeyRequestDto.getPrependThumbprint(); - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.SYMMETRICKEYREQUEST, - symmetricKeyRequestDto.getApplicationId(), "prependThumbprint Value(Request): " + reqPrependThumbprint); - - boolean prependThumbprint = reqPrependThumbprint == null? false : symmetricKeyRequestDto.getPrependThumbprint(); - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.SYMMETRICKEYREQUEST, - symmetricKeyRequestDto.getApplicationId(), "prependThumbprint Value: " + prependThumbprint); - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.SYMMETRICKEYREQUEST, - symmetricKeyRequestDto.getApplicationId(), "1.1.3 Thumbprint support property flag: " + noThumbprint); - - byte[] encryptedData = CryptoUtil.decodeBase64(symmetricKeyRequestDto.getEncryptedSymmetricKey()); - - if (noThumbprint) { - return decryptSymmetricKeyNoKeyIdentifier(applicationId, referenceId, encryptedData, localDateTimeStamp); - } - return decryptSymmetricKeyWithKeyIdentifier(applicationId, referenceId, encryptedData, localDateTimeStamp); - } - - /* - * To Support only with thumbprint. - * - * @see - * io.mosip.kernel.keymanager.service.KeymanagerService#decryptSymmetricKey(java - * .lang.String, java.time.LocalDateTime, java.util.Optional, byte[]) - */ - private SymmetricKeyResponseDto decryptSymmetricKeyWithKeyIdentifier(String applicationId, String referenceId, - byte[] encryptedData, LocalDateTime localDateTimeStamp) { - - byte[] certThumbprint = Arrays.copyOfRange(encryptedData, 0, CryptomanagerConstant.THUMBPRINT_LENGTH); - byte[] encryptedSymmetricKey = Arrays.copyOfRange(encryptedData, CryptomanagerConstant.THUMBPRINT_LENGTH, - encryptedData.length); - SymmetricKeyResponseDto keyResponseDto = new SymmetricKeyResponseDto(); - byte[] decryptedSymmetricKey = decryptSessionKey(applicationId, referenceId, localDateTimeStamp, - encryptedSymmetricKey, certThumbprint); - keyResponseDto.setSymmetricKey(CryptoUtil.encodeBase64(decryptedSymmetricKey)); - return keyResponseDto; - - } - - private byte[] decryptSessionKey(String applicationId, String referenceId, LocalDateTime localDateTimeStamp, - byte[] encryptedSymmetricKey, byte[] certThumbprint) { - - Map> keyAliasMap; - if (!keymanagerUtil.isValidReferenceId(referenceId)) { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.EMPTY, KeymanagerConstant.EMPTY, - NOT_A_VALID_REFERENCE_ID_GETTING_KEY_ALIAS_WITHOUT_REFERENCE_ID); - keyAliasMap = dbHelper.getKeyAliases(applicationId, KeymanagerConstant.EMPTY, localDateTimeStamp); - } else { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.EMPTY, KeymanagerConstant.EMPTY, - VALID_REFERENCE_ID_GETTING_KEY_ALIAS_WITH_REFERENCE_ID); - keyAliasMap = dbHelper.getKeyAliases(applicationId, referenceId, localDateTimeStamp); - } - - List keyAlias = keyAliasMap.get(KeymanagerConstant.KEYALIAS); - List currentKeyAlias = keyAliasMap.get(KeymanagerConstant.CURRENTKEYALIAS); - if (keyAlias.isEmpty()) { - // Check Master Key exists to perform for decryption. - keyAliasMap = dbHelper.getKeyAliases(applicationId, KeymanagerConstant.EMPTY, localDateTimeStamp); - keyAlias = keyAliasMap.get(KeymanagerConstant.KEYALIAS); - currentKeyAlias = keyAliasMap.get(KeymanagerConstant.CURRENTKEYALIAS); - if (keyAlias.isEmpty()) { - LOGGER.error(KeymanagerConstant.SESSIONID, KeymanagerConstant.KEYALIAS, - String.valueOf(keyAlias.size()), "KeyAlias is empty(with Key Identifier) Throwing exception"); - throw new NoUniqueAliasException(KeymanagerErrorConstant.NO_UNIQUE_ALIAS.getErrorCode(), - KeymanagerErrorConstant.NO_UNIQUE_ALIAS.getErrorMessage()); - } - // resetting the reference id to blank because base key is not generated but data encrypted with master key. - // And to avoid no key alias found exception in getKeyObjects method. - if(keymanagerUtil.isValidReferenceId(referenceId)) - referenceId = KeymanagerConstant.EMPTY; - } - - Object[] keys = getKeyObjects(keyAlias, currentKeyAlias, localDateTimeStamp, referenceId, - certThumbprint, applicationId); - PrivateKey privateKey = (PrivateKey) keys[0]; - PublicKey publicKey = ((Certificate) keys[1]).getPublicKey(); - try { - byte[] decryptedSessionKey = cryptoCore.asymmetricDecrypt(privateKey, publicKey, encryptedSymmetricKey); - if(keymanagerUtil.isValidReferenceId(referenceId)) - keymanagerUtil.destoryKey(privateKey); - return decryptedSessionKey; - } catch(InvalidKeyException keyExp) { - LOGGER.error(KeymanagerConstant.SESSIONID, KeymanagerConstant.APPLICATIONID, KeymanagerConstant.REFERENCEID, - "Error occurred because of mismatch with keys. Try with keys for decryption."); - throw new CryptoException(KeymanagerErrorConstant.SYMMETRIC_KEY_DECRYPTION_FAILED.getErrorCode(), - KeymanagerErrorConstant.SYMMETRIC_KEY_DECRYPTION_FAILED.getErrorMessage() + keyExp.getMessage(), keyExp); - } - } - - /* - * To Support 1.1.3 decryption & after thumbprint addition. - * - * @see - * io.mosip.kernel.keymanager.service.KeymanagerService#decryptSymmetricKey(java - * .lang.String, java.time.LocalDateTime, java.util.Optional, byte[]) - */ - private SymmetricKeyResponseDto decryptSymmetricKeyNoKeyIdentifier(String applicationId, String referenceId, - byte[] encryptedData, LocalDateTime localDateTimeStamp) { - - byte[] certThumbprint = null; - byte[] encryptedSymmetricKey = null; - boolean prependThumbprint = false; - // Thumbprint flag is false in both encryption & decryption, then consider the latest - // current key for decryption instead of taking the first generated key. - // to Support packet encryption done in 1.1.3(flag: flase) and packet decryption is performed in 1.1.4 (flag: true). - if(encryptedData.length == (CryptomanagerConstant.ENCRYPTED_SESSION_KEY_LENGTH - + CryptomanagerConstant.THUMBPRINT_LENGTH)) { - certThumbprint = Arrays.copyOfRange(encryptedData, 0, CryptomanagerConstant.THUMBPRINT_LENGTH); - encryptedSymmetricKey = Arrays.copyOfRange(encryptedData, CryptomanagerConstant.THUMBPRINT_LENGTH, - encryptedData.length); - prependThumbprint = true; - } else { - encryptedSymmetricKey = encryptedData; - } - SymmetricKeyResponseDto keyResponseDto = new SymmetricKeyResponseDto(); - byte[] decryptedSymmetricKey = decryptSessionKey(applicationId, referenceId, localDateTimeStamp, - encryptedSymmetricKey, certThumbprint, prependThumbprint); - keyResponseDto.setSymmetricKey(CryptoUtil.encodeBase64(decryptedSymmetricKey)); - return keyResponseDto; - - } - - private byte[] decryptSessionKey(String applicationId, String referenceId, LocalDateTime localDateTimeStamp, - byte[] encryptedSymmetricKey, byte[] certThumbprint, boolean packetTPFlag) { - - Map> keyAliasMap; - if (!keymanagerUtil.isValidReferenceId(referenceId)) { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.EMPTY, KeymanagerConstant.EMPTY, - NOT_A_VALID_REFERENCE_ID_GETTING_KEY_ALIAS_WITHOUT_REFERENCE_ID); - keyAliasMap = dbHelper.getKeyAliases(applicationId, KeymanagerConstant.EMPTY, localDateTimeStamp); - } else { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.EMPTY, KeymanagerConstant.EMPTY, - VALID_REFERENCE_ID_GETTING_KEY_ALIAS_WITH_REFERENCE_ID); - keyAliasMap = dbHelper.getKeyAliases(applicationId, referenceId, localDateTimeStamp); - } - - List keyAlias = keyAliasMap.get(KeymanagerConstant.KEYALIAS); - List currentKeyAlias = keyAliasMap.get(KeymanagerConstant.CURRENTKEYALIAS); - InvalidKeyException keyException = null; - InvalidDataException dataException = null; - Object[] keys = getPrivateKeyNoKeyIdentifier(keyAlias, currentKeyAlias, localDateTimeStamp, referenceId, - certThumbprint, packetTPFlag, applicationId); - PrivateKey privateKey = (PrivateKey) keys[0]; - PublicKey publicKey = ((Certificate) keys[1]).getPublicKey(); - try { - byte[] decryptedSessionKey = cryptoCore.asymmetricDecrypt(privateKey, publicKey, encryptedSymmetricKey); - if(keymanagerUtil.isValidReferenceId(referenceId)) - keymanagerUtil.destoryKey(privateKey); - return decryptedSessionKey; - } catch(InvalidKeyException keyExp) { - LOGGER.error(KeymanagerConstant.SESSIONID, KeymanagerConstant.APPLICATIONID, KeymanagerConstant.REFERENCEID, - "Error occurred because of mismatch with keys. Try with keys for decryption."); - keyException = keyExp; - } catch (InvalidDataException dataExp) { - LOGGER.error(KeymanagerConstant.SESSIONID, KeymanagerConstant.APPLICATIONID, KeymanagerConstant.REFERENCEID, - "Error occurred because of mismatch with keys. Try with other current key for decryption."); - dataException = dataExp; - } - // Taking the all DB keys for decryption to handle scenario - - // Current key got rotated and there are more than 1 keys in DB. Packet encrypted with thumbprint flag as false - // and used the latest key for encryption. Finally trying with all keys for decryption. - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.APPLICATIONID, KeymanagerConstant.REFERENCEID, - "Unable to decrypt session key with all the other validations, " + - "trying the keys available for provided AppId & RefId."); - try { - return decryptWithKeyAlias(keyAlias, referenceId, encryptedSymmetricKey); - } catch (InvalidKeyException keyExp) { - keyException = keyExp; - } catch (InvalidDataException dataExp) { - dataException = dataExp; - } - - // Check whether data is decrypting with the master key(s). - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.APPLICATIONID, KeymanagerConstant.REFERENCEID, - "Unable to decrypt session key with all the base keys, " + - "trying with master keys available for provided AppId."); - Map> masterKeyAliasMap = dbHelper.getKeyAliases(applicationId, KeymanagerConstant.EMPTY, localDateTimeStamp); - List masterKeyAlias = masterKeyAliasMap.get(KeymanagerConstant.KEYALIAS); - try { - return decryptWithKeyAlias(masterKeyAlias, KeymanagerConstant.EMPTY, encryptedSymmetricKey); - } catch (InvalidKeyException keyExp) { - keyException = keyExp; - } catch (InvalidDataException dataExp) { - dataException = dataExp; - } - - if(keyException == null) - throw dataException; - - throw keyException; - } - - private byte[] decryptWithKeyAlias(List keyAlias, String referenceId, byte[] encryptedSymmetricKey) { - InvalidKeyException keyException = null; - InvalidDataException dataException = null; - for (KeyAlias alias : keyAlias){ - Object[] dbKeys = getPrivateKey(referenceId, alias); - PrivateKey dbPrivateKey = (PrivateKey) dbKeys[0]; - PublicKey dbPublicKey = ((Certificate) dbKeys[1]).getPublicKey(); - try { - byte[] decryptedSessionKey = cryptoCore.asymmetricDecrypt(dbPrivateKey, dbPublicKey, encryptedSymmetricKey); - if(keymanagerUtil.isValidReferenceId(referenceId)) - keymanagerUtil.destoryKey(dbPrivateKey); - return decryptedSessionKey; - } catch (InvalidKeyException keyExp) { - LOGGER.error(KeymanagerConstant.SESSIONID, KeymanagerConstant.APPLICATIONID, KeymanagerConstant.REFERENCEID, - "Error occurred because of mismatch with keys. Try with other current key for decryption. key Alias: " + alias); - keyException = keyExp; - } catch (InvalidDataException dataExp) { - LOGGER.error(KeymanagerConstant.SESSIONID, KeymanagerConstant.APPLICATIONID, KeymanagerConstant.REFERENCEID, - "Error occurred because of mismatch with keys. Try with other current key for decryption. key Alias: " + alias); - dataException = dataExp; - } - } - if(keyException == null) - throw dataException; - - throw keyException; - } - /** - * get private key base - * - */ - private Object[] getPrivateKeyNoKeyIdentifier(List keyAlias, List currentKeyAlias, - LocalDateTime timeStamp, String referenceId, - byte[] reqCertThumbprint, boolean packetTPFlag, String applicationId) { - - if (keyAlias.isEmpty()) { - // Check Master Key exists to perform for decryption. - Map> keyAliasMap = dbHelper.getKeyAliases(applicationId, KeymanagerConstant.EMPTY, timeStamp); - keyAlias = keyAliasMap.get(KeymanagerConstant.KEYALIAS); - currentKeyAlias = keyAliasMap.get(KeymanagerConstant.CURRENTKEYALIAS); - if (keyAlias.isEmpty()) { - LOGGER.error(KeymanagerConstant.SESSIONID, KeymanagerConstant.KEYALIAS, - String.valueOf(keyAlias.size()), "KeyAlias is empty(no Key Identifier) Throwing exception"); - throw new NoUniqueAliasException(KeymanagerErrorConstant.NO_UNIQUE_ALIAS.getErrorCode(), - KeymanagerErrorConstant.NO_UNIQUE_ALIAS.getErrorMessage()); - } - // resetting the reference id to blank because base key is not generated but data encrypted with master key. - // And to avoid no key alias found exception in getKeyObjects method. - if(keymanagerUtil.isValidReferenceId(referenceId)) - referenceId = KeymanagerConstant.EMPTY; - } - - // to Support packet encryption done in 1.1.3(flag: flase) and packet decryption is performed in 1.1.4 (flag: true). - // Considering always the first key generated for the application id & reference id - if (Objects.isNull(reqCertThumbprint) && !packetTPFlag) { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.CURRENTKEYALIAS, keyAlias.get(0).getAlias(), - "Thumbprint is value is null and packet Thumbprint Flag is false."); - KeyAlias fetchedKeyAlias = keyAlias.get(0); - return getPrivateKey(referenceId, fetchedKeyAlias); - } - return getKeyObjects(keyAlias, currentKeyAlias, timeStamp, referenceId, reqCertThumbprint, applicationId); - } - - private Object[] getKeyObjects(List keyAlias, List currentKeyAlias, LocalDateTime timeStamp, - String referenceId, byte[] reqCertThumbprint, String applicationId) { - if (currentKeyAlias.size() == 1) { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.CURRENTKEYALIAS, currentKeyAlias.get(0).getAlias(), - "CurrentKeyAlias size is one. Will decrypt symmetric key with this alias after thumbprint matches."); - KeyAlias fetchedKeyAlias = currentKeyAlias.get(0); - Object[] keys = getPrivateKey(referenceId, fetchedKeyAlias); - if (reqCertThumbprint == null){ - return keys; - } - Certificate certificate = (Certificate) keys[1]; - byte[] certThumbprint = cryptomanagerUtil.getCertificateThumbprint(certificate); - if (Arrays.equals(reqCertThumbprint, certThumbprint)) - return keys; - } - - if ((currentKeyAlias.isEmpty() || currentKeyAlias.size() > 1) && reqCertThumbprint == null) { - LOGGER.error(KeymanagerConstant.SESSIONID, KeymanagerConstant.CURRENTKEYALIAS, - String.valueOf(currentKeyAlias.size()), "CurrentKeyAlias is empty or not unique & certificate thumbprint is null. " + - "Throwing exception"); - throw new NoUniqueAliasException(KeymanagerErrorConstant.NO_UNIQUE_ALIAS.getErrorCode(), - KeymanagerErrorConstant.NO_UNIQUE_ALIAS.getErrorMessage()); - } - - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.KEYALIAS, "", - "CurrentKeyAlias size is zero or thumbprint not matched now checking " + - "other expired key aliases to compare thumbprint."); - for (KeyAlias otherAlias : keyAlias) { - Object[] keys = getPrivateKey(referenceId, otherAlias); - Certificate certificate = (Certificate) keys[1]; - byte[] certThumbprint = cryptomanagerUtil.getCertificateThumbprint(certificate); - if (Arrays.equals(reqCertThumbprint, certThumbprint)) - return keys; - } - // Check whether Thumbprint is matching with the master key(s). - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.KEYALIAS, "", - "Base key certificate thumbprint did not matched with thumbprint in encrypted data, " + - "Checking thumbprint match with master key."); - Map> keyAliasMap = dbHelper.getKeyAliases(applicationId, KeymanagerConstant.EMPTY, timeStamp); - List masterKeyAlias = keyAliasMap.get(KeymanagerConstant.KEYALIAS); - for (KeyAlias masterAlias : masterKeyAlias) { - Object[] keys = getPrivateKey(KeymanagerConstant.EMPTY, masterAlias); - Certificate certificate = (Certificate) keys[1]; - byte[] certThumbprint = cryptomanagerUtil.getCertificateThumbprint(certificate); - if (Arrays.equals(reqCertThumbprint, certThumbprint)) - return keys; - } - - LOGGER.error(KeymanagerConstant.SESSIONID, KeymanagerConstant.KEYALIAS, "", - "No Key Alias for the thumbprint provided (After comparing all thumbprints), Throwing exception"); - throw new NoUniqueAliasException(KeymanagerErrorConstant.NO_UNIQUE_ALIAS.getErrorCode(), - KeymanagerErrorConstant.NO_UNIQUE_ALIAS.getErrorMessage()); - } - - /** - * Function to get Private Key which will be used to decrypt symmetric key. - * - * @param referenceId referenceId - * @param fetchedKeyAlias fetchedKeyAlias - * @return Private key - */ - private Object[] getPrivateKey(String referenceId, KeyAlias fetchedKeyAlias) { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.REFERENCEID, referenceId, - KeymanagerConstant.GETPRIVATEKEY); - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.FETCHEDKEYALIAS, fetchedKeyAlias.getAlias(), - KeymanagerConstant.GETPRIVATEKEY); - - if (!keymanagerUtil.isValidReferenceId(referenceId)) { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.EMPTY, KeymanagerConstant.EMPTY, - "Not valid reference Id. Getting private key from HSM."); - PrivateKeyEntry masterKeyEntry = keyStore.getAsymmetricKey(fetchedKeyAlias.getAlias()); - PrivateKey masterPrivateKey = masterKeyEntry.getPrivateKey(); - Certificate masterCert = masterKeyEntry.getCertificate(); - return new Object[] {masterPrivateKey, masterCert}; - } else { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.EMPTY, KeymanagerConstant.EMPTY, - "Valid reference Id. Getting private key from DB Store"); - String ksAlias = fetchedKeyAlias.getAlias(); - Optional dbKeyStore = dbHelper.getKeyStoreFromDB(ksAlias); - if (!dbKeyStore.isPresent()) { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.KEYFROMDB, dbKeyStore.toString(), - "Key in DBStore does not exist for this alias. Throwing exception"); - throw new NoUniqueAliasException(KeymanagerErrorConstant.NO_UNIQUE_ALIAS.getErrorCode(), - KeymanagerErrorConstant.NO_UNIQUE_ALIAS.getErrorMessage()); - } - String masterKeyAlias = dbKeyStore.get().getMasterAlias(); - String privateKeyObj = dbKeyStore.get().getPrivateKey(); - - if (ksAlias.equals(masterKeyAlias) || privateKeyObj.equals(KeymanagerConstant.KS_PK_NA)) { - LOGGER.error(KeymanagerConstant.SESSIONID, KeymanagerConstant.APPLICATIONID, null, - "Not Allowed to perform decryption with other domain key."); - throw new KeymanagerServiceException(KeymanagerErrorConstant.DECRYPTION_NOT_ALLOWED.getErrorCode(), - KeymanagerErrorConstant.DECRYPTION_NOT_ALLOWED.getErrorMessage()); - } - - PrivateKeyEntry masterKeyEntry = keyStore.getAsymmetricKey(dbKeyStore.get().getMasterAlias()); - PrivateKey masterPrivateKey = masterKeyEntry.getPrivateKey(); - PublicKey masterPublicKey = masterKeyEntry.getCertificate().getPublicKey(); - /** - * If the private key is in dbstore, then it will be first decrypted with - * application's master private key from softhsm's/HSM's keystore - */ - try { - byte[] decryptedPrivateKey = keymanagerUtil.decryptKey(CryptoUtil.decodeBase64(dbKeyStore.get().getPrivateKey()), - masterPrivateKey, masterPublicKey, keyStore.getKeystoreProviderName()); - KeyFactory keyFactory = KeyFactory.getInstance(KeymanagerConstant.RSA); - PrivateKey privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(decryptedPrivateKey)); - Certificate certificate = keymanagerUtil.convertToCertificate(dbKeyStore.get().getCertificateData()); - return new Object[] {privateKey, certificate}; - } catch (InvalidDataException | InvalidKeyException | NullDataException | NullKeyException - | NullMethodException | InvalidKeySpecException | NoSuchAlgorithmException e) { - throw new CryptoException(KeymanagerErrorConstant.CRYPTO_EXCEPTION.getErrorCode(), - KeymanagerErrorConstant.CRYPTO_EXCEPTION.getErrorMessage() + e.getMessage(), e); - } - } - } - - - @Override - public SignatureCertificate getSignatureCertificate(String applicationId, Optional referenceId, - String timestamp){ - return getSigningCertificate(applicationId, referenceId, timestamp, true); - } - - private SignatureCertificate getSigningCertificate(String applicationId, Optional referenceId, - String timestamp, boolean isPrivateRequired) { - String alias = null; - List currentKeyAlias = null; - Map> keyAliasMap = null; - LocalDateTime generationDateTime = null; - LocalDateTime expiryDateTime = null; - CertificateEntry certificateEntry = null; - LocalDateTime localDateTimeStamp = DateUtils.getUTCCurrentDateTime(); - String refId = null; - if (!referenceId.isPresent() || referenceId.get().trim().isEmpty()) { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.EMPTY, KeymanagerConstant.EMPTY, - NOT_A_VALID_REFERENCE_ID_GETTING_KEY_ALIAS_WITHOUT_REFERENCE_ID); - keyAliasMap = dbHelper.getKeyAliases(applicationId, KeymanagerConstant.EMPTY, localDateTimeStamp); - refId = KeymanagerConstant.EMPTY; - } else if (applicationId.equalsIgnoreCase(signApplicationid) && referenceId.isPresent() - && referenceId.get().equals(certificateSignRefID)){ - LOGGER.info(KeymanagerConstant.SESSIONID, applicationId, referenceId.get(), - VALID_REFERENCE_ID_GETTING_KEY_ALIAS_WITH_REFERENCE_ID); - keyAliasMap = dbHelper.getKeyAliases(applicationId, referenceId.get(), localDateTimeStamp); - refId = referenceId.get(); - } else { - LOGGER.error(KeymanagerConstant.SESSIONID, applicationId, referenceId.get(), - "Signing operation not allowed for the provided application Id & reference Id."); - throw new KeymanagerServiceException(KeymanagerErrorConstant.NOT_VALID_SIGNATURE_KEY.getErrorCode(), - KeymanagerErrorConstant.NOT_VALID_SIGNATURE_KEY.getErrorMessage()); - } - List keyAlias = keyAliasMap.get(KeymanagerConstant.KEYALIAS); - currentKeyAlias = keyAliasMap.get(KeymanagerConstant.CURRENTKEYALIAS); - - if (currentKeyAlias.size() > 1) { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.CURRENTKEYALIAS, - String.valueOf(currentKeyAlias.size()), "CurrentKeyAlias size more than one. Throwing exception"); - throw new NoUniqueAliasException(KeymanagerErrorConstant.NO_UNIQUE_ALIAS.getErrorCode(), - KeymanagerErrorConstant.NO_UNIQUE_ALIAS.getErrorMessage()); - } else if (currentKeyAlias.size() == 1) { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.CURRENTKEYALIAS, - currentKeyAlias.get(0).getAlias(), - "CurrentKeyAlias size is one. Will fetch keypair using this alias"); - KeyAlias fetchedKeyAlias = currentKeyAlias.get(0); - alias = fetchedKeyAlias.getAlias(); - // @TODO Not Sure why always check the existing HSM only. We need to get more details from team. - // Expecting the signature key to be always in HSM. - certificateEntry = getCertificateEntry(alias, isPrivateRequired); - generationDateTime = fetchedKeyAlias.getKeyGenerationTime(); - expiryDateTime = fetchedKeyAlias.getKeyExpiryTime(); - } else if (currentKeyAlias.isEmpty() && keyAlias.size() > 0) { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.KEYALIAS, - keyAlias.get(0).getAlias(), - "CurrentKeyAlias size is zero. Key got expired, generating new keypair using this App Id & Ref Id"); - // This will generate the new key in HSM. - alias = UUID.randomUUID().toString(); - generateKeyPairInHSM(alias, applicationId, refId, localDateTimeStamp, keyAlias); - certificateEntry = getCertificateEntry(alias, isPrivateRequired); - generationDateTime = localDateTimeStamp; - expiryDateTime = dbHelper.getExpiryPolicy(applicationId, generationDateTime, keyAlias); - } else { - LOGGER.error(KeymanagerConstant.SESSIONID, KeymanagerConstant.KEYALIAS, String.valueOf(keyAlias.size()), - "Initial Key generation process not completed."); - throw new KeymanagerServiceException(KeymanagerErrorConstant.KEY_GENERATION_NOT_DONE.getErrorCode(), - KeymanagerErrorConstant.KEY_GENERATION_NOT_DONE.getErrorMessage()); - } - String providerName = keyStore.getKeystoreProviderName(); - return new SignatureCertificate(alias, certificateEntry, generationDateTime, expiryDateTime, providerName); - } - - private CertificateEntry getCertificateEntry(String alias, boolean isPrivateRequired) { - BaseUncheckedException exception = null; - try { - PrivateKeyEntry privateKeyEntry = keyStore.getAsymmetricKey(alias); - return new CertificateEntry<>((X509Certificate[]) privateKeyEntry.getCertificateChain(), - privateKeyEntry.getPrivateKey()); - } catch(KeystoreProcessingException | NoSuchSecurityProviderException kpe) { - LOGGER.error(KeymanagerConstant.SESSIONID, KeymanagerConstant.CURRENTKEYALIAS, "Error", - "Key Not found in HSM, keystore might have loaded as offline." + kpe.getMessage()); - exception = kpe; - } - if (!isPrivateRequired) { - Optional keyFromDBStore = dbHelper.getKeyStoreFromDB(alias); - if (!keyFromDBStore.isPresent()) { - LOGGER.error(KeymanagerConstant.SESSIONID, KeymanagerConstant.CURRENTKEYALIAS, KeymanagerConstant.EMPTY, - "Certificate Not found in keystore table."); - throw new KeymanagerServiceException(KeymanagerErrorConstant.CERTIFICATE_NOT_FOUND.getErrorCode(), - KeymanagerErrorConstant.CERTIFICATE_NOT_FOUND.getErrorMessage()); - } - String certificateData = keyFromDBStore.get().getCertificateData(); - X509Certificate reqX509Cert = (X509Certificate) keymanagerUtil.convertToCertificate(certificateData); - return new CertificateEntry<>( new X509Certificate[] {reqX509Cert}, null); - } - throw exception; - } - - @Override - public PublicKeyResponse getSignPublicKey(String applicationId, String timestamp, - Optional referenceId) { - // Ignoring the inputted timestamp and considering current system time to check the key expiry. - String localDateTimeStamp = DateUtils.getUTCCurrentDateTimeString(); //keymanagerUtil.parseToLocalDateTime(timeStamp); - - SignatureCertificate certificateResponse = getSigningCertificate(applicationId, referenceId, localDateTimeStamp, false); - return new PublicKeyResponse<>(certificateResponse.getAlias(), - CryptoUtil.encodeBase64(certificateResponse.getCertificateEntry().getChain()[0].getPublicKey().getEncoded()), - certificateResponse.getIssuedAt(), certificateResponse.getExpiryAt()); - } - - @Override - public KeyPairGenerateResponseDto generateMasterKey(String responseObjectType, KeyPairGenerateRequestDto request) { - - String applicationId = request.getApplicationId(); - String refId = request.getReferenceId() == null ? KeymanagerConstant.EMPTY : request.getReferenceId(); - Boolean forceFlag = request.getForce() == null ? Boolean.FALSE : request.getForce(); - - Optional keyPolicy = dbHelper.getKeyPolicy(applicationId); - // Need to check with Team whether we need to check this condition.. - if (keymanagerUtil.isValidReferenceId(refId) && - ((refId.equals(certificateSignRefID) && !applicationId.equals(signApplicationid)) || - (!refId.equals(certificateSignRefID)))) { - LOGGER.error(KeymanagerConstant.SESSIONID, KeymanagerConstant.KEYPOLICY, keyPolicy.toString(), - "Reference Id not supported for the provided application Id."); - throw new KeymanagerServiceException(KeymanagerErrorConstant.REFERENCE_ID_NOT_SUPPORTED.getErrorCode(), - KeymanagerErrorConstant.REFERENCE_ID_NOT_SUPPORTED.getErrorMessage()); - } - - if (!keymanagerUtil.isValidResponseType(responseObjectType)) { - LOGGER.error(KeymanagerConstant.SESSIONID, "Response Object Type", null, - "Invalid Response Object type provided for the key generation request."); - throw new KeymanagerServiceException(KeymanagerErrorConstant.INVALID_REQUEST.getErrorCode(), - KeymanagerErrorConstant.INVALID_REQUEST.getErrorMessage()); - } - - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.APPLICATIONID, KeymanagerConstant.EMPTY, - KeymanagerConstant.REQUEST_FOR_MASTER_KEY_GENERATION); - return generateKey(responseObjectType, applicationId, refId, forceFlag, request); - } - - private KeyPairGenerateResponseDto generateKey(String responseObjectType, String appId, String refId, - Boolean forceFlag, KeyPairGenerateRequestDto request) { - - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.APPLICATIONID, appId, - "Generate Key for application ID: " + appId + ", RefId: " + refId + ", force flag: " + forceFlag.toString()); - LocalDateTime timestamp = DateUtils.getUTCCurrentDateTime(); - Map> keyAliasMap = dbHelper.getKeyAliases(appId, refId, timestamp); - List currentKeyAlias = keyAliasMap.get(KeymanagerConstant.CURRENTKEYALIAS); - if (forceFlag) { - LOGGER.debug(KeymanagerConstant.SESSIONID, KeymanagerConstant.APPLICATIONID, appId, - "Force Flag is True, invalidating all the existing keys and generating new key pair."); - LocalDateTime expireTime = timestamp.minusMinutes(1L); - currentKeyAlias.forEach(alias -> { - dbHelper.storeKeyInAlias(appId, alias.getKeyGenerationTime(), refId, alias.getAlias(), expireTime); - }); - return generateAndBuildResponse(responseObjectType, appId, refId, timestamp, keyAliasMap, request); - } - - if (currentKeyAlias.size() > 1) { - LOGGER.error(KeymanagerConstant.SESSIONID, KeymanagerConstant.CURRENTKEYALIAS, - String.valueOf(currentKeyAlias.size()), "CurrentKeyAlias size more than one"); - throw new NoUniqueAliasException(KeymanagerErrorConstant.NO_UNIQUE_ALIAS.getErrorCode(), - KeymanagerErrorConstant.NO_UNIQUE_ALIAS.getErrorMessage()); - } else if (currentKeyAlias.isEmpty()) { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.CURRENTKEYALIAS, - String.valueOf(currentKeyAlias.size()), - "CurrentKeyAlias size is zero. Will create new Keypair for this applicationId and timestamp"); - return generateAndBuildResponse(responseObjectType, appId, refId, timestamp, keyAliasMap, request); - } - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.CURRENTKEYALIAS, - String.valueOf(currentKeyAlias.size()), - "key details present in DB" + currentKeyAlias.get(0)); - KeyAlias fetchedKeyAlias = currentKeyAlias.get(0); - return buildResponseObject(responseObjectType, appId, refId, timestamp, fetchedKeyAlias.getAlias(), - fetchedKeyAlias.getKeyGenerationTime(), fetchedKeyAlias.getKeyExpiryTime(), request); - } - - private KeyPairGenerateResponseDto generateAndBuildResponse(String responseObjectType, String appId, String refId, - LocalDateTime timestamp, Map> keyAliasMap, KeyPairGenerateRequestDto request) { - - String alias = UUID.randomUUID().toString(); - LocalDateTime generationDateTime = timestamp; - LocalDateTime expiryDateTime = dbHelper.getExpiryPolicy(appId, generationDateTime, keyAliasMap.get(KeymanagerConstant.KEYALIAS)); - String rootKeyAlias = getRootKeyAlias(appId, timestamp); - CertificateParameters certParams = keymanagerUtil.getCertificateParameters(request, generationDateTime, expiryDateTime, appId); - keyStore.generateAndStoreAsymmetricKey(alias, rootKeyAlias, certParams); - dbHelper.storeKeyInAlias(appId, generationDateTime, refId, alias, expiryDateTime); - return buildResponseObject(responseObjectType, appId, refId, timestamp, alias, generationDateTime, expiryDateTime, request); - } - - - private String getRootKeyAlias(String appId, LocalDateTime timestamp) { - Map> rootKeyAliasMap = dbHelper.getKeyAliases(rootKeyApplicationId, KeymanagerConstant.EMPTY, timestamp); - List rootCurrentKeyAlias = rootKeyAliasMap.get(KeymanagerConstant.CURRENTKEYALIAS); - String rootKeyAlias = null; - if (rootCurrentKeyAlias.size() > 1) { - LOGGER.error(KeymanagerConstant.SESSIONID, KeymanagerConstant.CURRENTKEYALIAS, - String.valueOf(rootCurrentKeyAlias.size()), "CurrentKeyAlias size more than one for ROOT Key"); - throw new NoUniqueAliasException(KeymanagerErrorConstant.NO_UNIQUE_ALIAS.getErrorCode(), - KeymanagerErrorConstant.NO_UNIQUE_ALIAS.getErrorMessage()); - } else if (rootCurrentKeyAlias.size() == 1) { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.CURRENTKEYALIAS, - String.valueOf(rootCurrentKeyAlias.size()), - "CurrentKeyAlias size is one. Use the current root key alias as key to sign the key."); - rootKeyAlias = rootCurrentKeyAlias.get(0).getAlias(); - } - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.ROOT_KEY, "Found Root Key.", - "Root Key for signing the new generated key: " + rootKeyAlias); - if (Objects.isNull(rootKeyAlias) && !appId.equals(rootKeyApplicationId)) { - LOGGER.error(KeymanagerConstant.SESSIONID, KeymanagerConstant.ROOT_KEY, - "Root Key Error", "ROOT Key not available to sign the new generated key."); - throw new KeymanagerServiceException(KeymanagerErrorConstant.ROOT_KEY_NOT_FOUND.getErrorCode(), - KeymanagerErrorConstant.ROOT_KEY_NOT_FOUND.getErrorMessage()); - } - return rootKeyAlias; - } - - private KeyPairGenerateResponseDto buildResponseObject(String responseObjectType, String appId, String refId, - LocalDateTime timestamp, String keyAlias, LocalDateTime generationDateTime, LocalDateTime expiryDateTime, - KeyPairGenerateRequestDto request) { - - if (responseObjectType.toUpperCase().equals(KeymanagerConstant.REQUEST_TYPE_CERTIFICATE)) { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.APPLICATIONID, appId, - "Getting Key Certificate for application ID: " + appId + ", RefId: " + refId); - - X509Certificate x509Cert = (X509Certificate) keyStore.getCertificate(keyAlias); - KeyPairGenerateResponseDto responseDto = new KeyPairGenerateResponseDto(); - responseDto.setCertificate(keymanagerUtil.getPEMFormatedData(x509Cert)); - responseDto.setExpiryAt(DateUtils.parseDateToLocalDateTime(x509Cert.getNotAfter())); - responseDto.setIssuedAt(DateUtils.parseDateToLocalDateTime(x509Cert.getNotBefore())); - responseDto.setTimestamp(timestamp); - return responseDto; - } - - if (responseObjectType.toUpperCase().equals(KeymanagerConstant.REQUEST_TYPE_CSR)) { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.APPLICATIONID, appId, - "Getting Key CSR for application ID: " + appId + ", RefId: " + refId); - - PublicKey publicKey = ((X509Certificate) keyStore.getCertificate(keyAlias)).getPublicKey(); - PrivateKey privateKey = keyStore.getPrivateKey(keyAlias); - KeyPairGenerateResponseDto responseDto = new KeyPairGenerateResponseDto(); - CertificateParameters certParams = keymanagerUtil.getCertificateParameters(request, generationDateTime, expiryDateTime, appId); - responseDto.setCertSignRequest(keymanagerUtil.getCSR(privateKey, publicKey, certParams)); - responseDto.setExpiryAt(expiryDateTime); - responseDto.setIssuedAt(generationDateTime); - responseDto.setTimestamp(timestamp); - return responseDto; - } - LOGGER.error(KeymanagerConstant.SESSIONID, "Response Object Type", null, - "Invalid Response Object type provided for the key pair"); - throw new InvalidResponseObjectTypeException(KeymanagerErrorConstant.INVALID_RESPONSE_TYPE.getErrorCode(), - KeymanagerErrorConstant.INVALID_RESPONSE_TYPE.getErrorMessage()); - } - - @Override - public KeyPairGenerateResponseDto getCertificate(String appId, Optional refId) { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.APPLICATIONID, appId, - KeymanagerConstant.GET_CERTIFICATE); - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.REFERENCEID, refId.toString(), - KeymanagerConstant.GET_CERTIFICATE); - - LocalDateTime localDateTimeStamp = DateUtils.getUTCCurrentDateTime(); - CertificateInfo certificateData = null; - if (!refId.isPresent() || refId.get().trim().isEmpty()) { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.EMPTY, KeymanagerConstant.EMPTY, - "Reference Id is not present. Will get Certificate from HSM"); - certificateData = getCertificateFromHSM(appId, localDateTimeStamp, KeymanagerConstant.EMPTY); - } else if (appId.equalsIgnoreCase(signApplicationid) && refId.isPresent() - && refId.get().equals(certificateSignRefID)) { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.EMPTY, KeymanagerConstant.EMPTY, - "Reference Id is present and it is SIGN reference. Will get Certificate from HSM"); - certificateData = getCertificateFromHSM(appId, localDateTimeStamp, refId.get()); - } else { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.EMPTY, KeymanagerConstant.EMPTY, - "Reference Id is present. Will get Certificate from DB store"); - certificateData = getCertificateFromDBStore(appId, localDateTimeStamp, refId.get()); - } - - X509Certificate x509Cert = certificateData.getCertificate(); - KeyPairGenerateResponseDto responseDto = new KeyPairGenerateResponseDto(); - responseDto.setCertificate(keymanagerUtil.getPEMFormatedData(x509Cert)); - responseDto.setExpiryAt(DateUtils.parseDateToLocalDateTime(x509Cert.getNotAfter())); - responseDto.setIssuedAt(DateUtils.parseDateToLocalDateTime(x509Cert.getNotBefore())); - responseDto.setTimestamp(localDateTimeStamp); - return responseDto; - } - - @Override - public KeyPairGenerateResponseDto generateCSR(CSRGenerateRequestDto csrGenRequestDto) { - - String appId = csrGenRequestDto.getApplicationId(); - Optional refId = Optional.ofNullable(csrGenRequestDto.getReferenceId()); - LocalDateTime localDateTimeStamp = DateUtils.getUTCCurrentDateTime(); - - CertificateInfo certificateData = null; - if (!refId.isPresent() || refId.get().trim().isEmpty()) { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.EMPTY, KeymanagerConstant.EMPTY, - "Reference Id is not present. Will get Certificate from HSM"); - certificateData = getCertificateFromHSM(appId, localDateTimeStamp, KeymanagerConstant.EMPTY); - } else if (appId.equalsIgnoreCase(signApplicationid) && refId.isPresent() - && refId.get().equals(certificateSignRefID)) { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.EMPTY, KeymanagerConstant.EMPTY, - "Reference Id is present and it is SIGN reference. Will get Certificate from HSM"); - certificateData = getCertificateFromHSM(appId, localDateTimeStamp, refId.get()); - } else { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.EMPTY, KeymanagerConstant.EMPTY, - "Reference Id is present. Will get Certificate from DB store"); - certificateData = getCertificateFromDBStore(appId, localDateTimeStamp, refId.get()); - } - - String keyAlias = certificateData.getAlias(); - Optional keyFromDBStore = dbHelper.getKeyStoreFromDB(keyAlias); - - Object[] keyDetailsArr = getKeyDetails(keyFromDBStore, keyAlias); - PrivateKey signPrivateKey = (PrivateKey) keyDetailsArr[0]; - X509Certificate x509Cert = (X509Certificate) keyDetailsArr[1]; - - LocalDateTime generationDateTime = DateUtils.parseDateToLocalDateTime(x509Cert.getNotBefore()); - LocalDateTime expiryDateTime = DateUtils.parseDateToLocalDateTime(x509Cert.getNotAfter()); - CertificateParameters certParams = keymanagerUtil.getCertificateParameters(csrGenRequestDto, generationDateTime, expiryDateTime); - KeyPairGenerateResponseDto responseDto = new KeyPairGenerateResponseDto(); - responseDto.setCertSignRequest(keymanagerUtil.getCSR(signPrivateKey, x509Cert.getPublicKey(), certParams)); - responseDto.setExpiryAt(expiryDateTime); - responseDto.setIssuedAt(generationDateTime); - responseDto.setTimestamp(localDateTimeStamp); - if ((refId.isPresent() || !refId.get().trim().isEmpty()) && (!appId.equalsIgnoreCase(signApplicationid) && - !refId.get().equals(certificateSignRefID))) { - keymanagerUtil.destoryKey(signPrivateKey); - } - return responseDto; - } - - private KeyAlias getKeyAlias(String appId, String refId){ - - if (!keymanagerUtil.isValidApplicationId(appId)) { - LOGGER.error(KeymanagerConstant.SESSIONID, KeymanagerConstant.APPLICATIONID, null, - "Invalid application ID provided to get Object details."); - throw new KeymanagerServiceException(KeymanagerErrorConstant.INVALID_REQUEST.getErrorCode(), - KeymanagerErrorConstant.INVALID_REQUEST.getErrorMessage()); - } - - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.APPLICATIONID, appId, - "to get KeyInfo for application ID: " + appId + ", RefId: " + refId); - Optional keyPolicy = dbHelper.getKeyPolicy(appId); - LocalDateTime timestamp = DateUtils.getUTCCurrentDateTime(); - Map> keyAliasMap = dbHelper.getKeyAliases(appId, refId, timestamp); - List currentKeyAlias = keyAliasMap.get(KeymanagerConstant.CURRENTKEYALIAS); - - if (currentKeyAlias.size() > 1) { - LOGGER.error(KeymanagerConstant.SESSIONID, KeymanagerConstant.CURRENTKEYALIAS, - String.valueOf(currentKeyAlias.size()), "CurrentKeyAlias size more than one"); - throw new NoUniqueAliasException(KeymanagerErrorConstant.NO_UNIQUE_ALIAS.getErrorCode(), - KeymanagerErrorConstant.NO_UNIQUE_ALIAS.getErrorMessage()); - } else if (currentKeyAlias.isEmpty()) { - // checking empty because after certificate expiry new CSR request should be called to generate new key pair. - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.CURRENTKEYALIAS, - String.valueOf(currentKeyAlias.size()), - "CurrentKeyAlias size is zero for this applicationId and timestamp"); - throw new NoUniqueAliasException(KeymanagerErrorConstant.NO_UNIQUE_ALIAS.getErrorCode(), - KeymanagerErrorConstant.NO_UNIQUE_ALIAS.getErrorMessage()); - } - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.CURRENTKEYALIAS, - String.valueOf(currentKeyAlias.size()), - "key details present in DB: " + currentKeyAlias.get(0)); - KeyAlias fetchedKeyAlias = currentKeyAlias.get(0); - return fetchedKeyAlias; - } - - private Object[] getKeyDetails(Optional keyFromDBStore, String keyAlias) { - - if (!keyFromDBStore.isPresent()) { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.KEYFROMDB, keyFromDBStore.toString(), - "Key in DBStore does not exist for this alias. So fetching the certificate from HSM."); - PrivateKeyEntry signKeyEntry = keyStore.getAsymmetricKey(keyAlias); - PrivateKey signPrivateKey = signKeyEntry.getPrivateKey(); - X509Certificate x509Cert = (X509Certificate) signKeyEntry.getCertificate(); - return new Object[] {signPrivateKey, x509Cert}; - } - PrivateKeyEntry masterKeyEntry = keyStore.getAsymmetricKey(keyFromDBStore.get().getMasterAlias()); - PrivateKey masterPrivateKey = masterKeyEntry.getPrivateKey(); - PublicKey masterPublicKey = masterKeyEntry.getCertificate().getPublicKey(); - try { - byte[] decryptedPrivateKey = keymanagerUtil.decryptKey(CryptoUtil.decodeBase64(keyFromDBStore.get().getPrivateKey()), - masterPrivateKey, masterPublicKey, keyStore.getKeystoreProviderName()); - PrivateKey signPrivateKey = KeyFactory.getInstance(KeymanagerConstant.RSA).generatePrivate(new PKCS8EncodedKeySpec(decryptedPrivateKey)); - X509Certificate x509Cert = (X509Certificate) keymanagerUtil.convertToCertificate(keyFromDBStore.get().getCertificateData()); - return new Object[] {signPrivateKey, x509Cert}; - } catch (InvalidDataException | InvalidKeyException | NullDataException | NullKeyException - | NullMethodException | InvalidKeySpecException | NoSuchAlgorithmException e) { - throw new CryptoException(KeymanagerErrorConstant.CRYPTO_EXCEPTION.getErrorCode(), - KeymanagerErrorConstant.CRYPTO_EXCEPTION.getErrorMessage() + e.getMessage(), e); - } - } - - @Override - public UploadCertificateResponseDto uploadCertificate(UploadCertificateRequestDto uploadCertRequestDto){ - String appId = uploadCertRequestDto.getApplicationId(); - String refId = uploadCertRequestDto.getReferenceId(); - String certificateData = uploadCertRequestDto.getCertificateData(); - - if (!keymanagerUtil.isValidCertificateData(certificateData)) { - LOGGER.error(KeymanagerConstant.SESSIONID, KeymanagerConstant.APPLICATIONID, null, - "Invalid Certificate Data provided to upload the certificate."); - throw new KeymanagerServiceException(KeymanagerErrorConstant.INVALID_REQUEST.getErrorCode(), - KeymanagerErrorConstant.INVALID_REQUEST.getErrorMessage()); - } - - LocalDateTime timestamp = DateUtils.getUTCCurrentDateTime(); - KeyAlias currentKeyAlias = getKeyAlias(appId, refId); - String keyAlias = currentKeyAlias.getAlias(); - Optional keyFromDBStore = dbHelper.getKeyStoreFromDB(keyAlias); - - Object[] keyDetailsArr = getKeyDetails(keyFromDBStore, keyAlias); - PrivateKey privateKey = (PrivateKey) keyDetailsArr[0]; - X509Certificate x509Cert = (X509Certificate) keyDetailsArr[1]; - - X509Certificate reqX509Cert = (X509Certificate) keymanagerUtil.convertToCertificate(certificateData); - if (!Arrays.equals(x509Cert.getPublicKey().getEncoded(), reqX509Cert.getPublicKey().getEncoded())) { - LOGGER.error(KeymanagerConstant.SESSIONID, KeymanagerConstant.APPLICATIONID, null, - "Certificate Key is not matching with the available key."); - throw new KeymanagerServiceException(KeymanagerErrorConstant.KEY_NOT_MATCHING.getErrorCode(), - KeymanagerErrorConstant.KEY_NOT_MATCHING.getErrorMessage()); - } - LocalDateTime notBeforeDate = keymanagerUtil.convertToUTC(reqX509Cert.getNotBefore()); - LocalDateTime notAfterDate = keymanagerUtil.convertToUTC(reqX509Cert.getNotAfter()); - if (!keyFromDBStore.isPresent()){ - keyStore.storeCertificate(keyAlias, privateKey, reqX509Cert); - } else { - dbHelper.storeKeyInDBStore(keyAlias, keyFromDBStore.get().getMasterAlias(), keymanagerUtil.getPEMFormatedData(reqX509Cert), - keyFromDBStore.get().getPrivateKey()); - } - dbHelper.storeKeyInAlias(appId, notBeforeDate, refId, keyAlias, notAfterDate); - UploadCertificateResponseDto responseDto = new UploadCertificateResponseDto(); - responseDto.setStatus(KeymanagerConstant.UPLOAD_SUCCESS); - responseDto.setTimestamp(timestamp); - return responseDto; - } - - @Override - public UploadCertificateResponseDto uploadOtherDomainCertificate(UploadCertificateRequestDto uploadCertRequestDto) { - - String appId = uploadCertRequestDto.getApplicationId(); - String refId = uploadCertRequestDto.getReferenceId(); - String certificateData = uploadCertRequestDto.getCertificateData(); - - if (!keymanagerUtil.isValidCertificateData(certificateData) || !keymanagerUtil.isValidReferenceId(refId) || - !keymanagerUtil.isValidApplicationId(appId)) { - LOGGER.error(KeymanagerConstant.SESSIONID, KeymanagerConstant.APPLICATIONID, null, - "Invalid Data provided to upload other domain certificate."); - throw new KeymanagerServiceException(KeymanagerErrorConstant.INVALID_REQUEST.getErrorCode(), - KeymanagerErrorConstant.INVALID_REQUEST.getErrorMessage()); - } - - if (appId.equalsIgnoreCase(signApplicationid) && refId.equalsIgnoreCase(certificateSignRefID)) { - LOGGER.error(KeymanagerConstant.SESSIONID, KeymanagerConstant.APPLICATIONID, null, - "Not allowed to uploaded AppId: KERNEL & RefId: SIGN."); - throw new KeymanagerServiceException(KeymanagerErrorConstant.UPLOAD_NOT_ALLOWED.getErrorCode(), - KeymanagerErrorConstant.UPLOAD_NOT_ALLOWED.getErrorMessage()); - } - - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.APPLICATIONID, appId, - "to get KeyInfo for application ID: " + appId + ", RefId: " + refId); - LocalDateTime timestamp = DateUtils.getUTCCurrentDateTime(); - Map> keyAliasMap = dbHelper.getKeyAliases(appId, refId, timestamp); - List currentKeyAlias = keyAliasMap.get(KeymanagerConstant.CURRENTKEYALIAS); - - if (currentKeyAlias.size() > 1) { - LOGGER.error(KeymanagerConstant.SESSIONID, KeymanagerConstant.CURRENTKEYALIAS, - String.valueOf(currentKeyAlias.size()), "CurrentKeyAlias size more than one"); - throw new NoUniqueAliasException(KeymanagerErrorConstant.NO_UNIQUE_ALIAS.getErrorCode(), - KeymanagerErrorConstant.NO_UNIQUE_ALIAS.getErrorMessage()); - } - - List keyAliasList = keyAliasMap.get(KeymanagerConstant.KEYALIAS); - X509Certificate reqX509Cert = (X509Certificate) keymanagerUtil.convertToCertificate(certificateData); - LocalDateTime notBeforeDate = keymanagerUtil.convertToUTC(reqX509Cert.getNotBefore()); - LocalDateTime notAfterDate = keymanagerUtil.convertToUTC(reqX509Cert.getNotAfter()); - if (currentKeyAlias.isEmpty() && keyAliasList.isEmpty()) { - return storeAndBuildResponse(appId, refId, reqX509Cert, notBeforeDate, notAfterDate); - } - - // Current valid key is not available and expired key is available in key_alias, but not certificate available in key_store - if (currentKeyAlias.isEmpty() && keyAliasList.size() > 0) { - String keyAlias = keyAliasList.get(0).getAlias(); - Optional keyFromDBStore = dbHelper.getKeyStoreFromDB(keyAlias); - if (!keyFromDBStore.isPresent()) { - LOGGER.error(KeymanagerConstant.SESSIONID, KeymanagerConstant.EMPTY, KeymanagerConstant.EMPTY, - "Other valid key is available, so not allowed to upload certificate."); - throw new KeymanagerServiceException(KeymanagerErrorConstant.UPLOAD_NOT_ALLOWED.getErrorCode(), - KeymanagerErrorConstant.UPLOAD_NOT_ALLOWED.getErrorMessage()); - } - return storeAndBuildResponse(appId, refId, reqX509Cert, notBeforeDate, notAfterDate); - } - - // Current valid key is available in key_alias, but not certificate available in key_store - String keyAlias = currentKeyAlias.get(0).getAlias(); - Optional keyFromDBStore = dbHelper.getKeyStoreFromDB(keyAlias); - if (!keyFromDBStore.isPresent() && currentKeyAlias.size() == 1) { - LOGGER.error(KeymanagerConstant.SESSIONID, KeymanagerConstant.EMPTY, KeymanagerConstant.EMPTY, - "Other valid key is available, so not allowed to upload certificate."); - throw new KeymanagerServiceException(KeymanagerErrorConstant.UPLOAD_NOT_ALLOWED.getErrorCode(), - KeymanagerErrorConstant.UPLOAD_NOT_ALLOWED.getErrorMessage()); - } - - // master key alias & key alias should be same & private key should not available for other domain certificates. - String masterKeyAlias = keyFromDBStore.get().getMasterAlias(); - String privateKeyObj = keyFromDBStore.get().getPrivateKey(); - if (!keyAlias.equals(masterKeyAlias) || !privateKeyObj.equals(KeymanagerConstant.KS_PK_NA)) { - LOGGER.error(KeymanagerConstant.SESSIONID, KeymanagerConstant.APPLICATIONID, null, - "Not Allowed to update certificate for other domains."); - throw new KeymanagerServiceException(KeymanagerErrorConstant.UPLOAD_NOT_ALLOWED.getErrorCode(), - KeymanagerErrorConstant.UPLOAD_NOT_ALLOWED.getErrorMessage()); - } - - LocalDateTime expireTime = timestamp.minusMinutes(1L); - dbHelper.storeKeyInAlias(appId, currentKeyAlias.get(0).getKeyGenerationTime(), refId, keyAlias, expireTime); - return storeAndBuildResponse(appId, refId, reqX509Cert, notBeforeDate, notAfterDate); - } - - private UploadCertificateResponseDto storeAndBuildResponse(String appId, String refId, X509Certificate reqX509Cert, - LocalDateTime notBeforeDate, LocalDateTime notAfterDate) { - String alias = UUID.randomUUID().toString(); - dbHelper.storeKeyInDBStore(alias, alias, keymanagerUtil.getPEMFormatedData(reqX509Cert), KeymanagerConstant.KS_PK_NA); - dbHelper.storeKeyInAlias(appId, notBeforeDate, refId, alias, notAfterDate); - UploadCertificateResponseDto responseDto = new UploadCertificateResponseDto(); - responseDto.setStatus(KeymanagerConstant.UPLOAD_SUCCESS); - responseDto.setTimestamp(DateUtils.getUTCCurrentDateTime()); - return responseDto; - } - - @Override - public SymmetricKeyGenerateResponseDto generateSymmetricKey(SymmetricKeyGenerateRequestDto symGenRequestDto) { - - String appId = symGenRequestDto.getApplicationId(); - String refId = symGenRequestDto.getReferenceId(); - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.APPLICATIONID, appId, - KeymanagerConstant.REQ_SYM_KEY_GEN); - - if (!keymanagerUtil.isValidReferenceId(refId) || - !keymanagerUtil.isValidApplicationId(appId)) { - LOGGER.error(KeymanagerConstant.SESSIONID, KeymanagerConstant.APPLICATIONID, null, - "Invalid Data provided to generate symmetric key."); - throw new KeymanagerServiceException(KeymanagerErrorConstant.INVALID_REQUEST.getErrorCode(), - KeymanagerErrorConstant.INVALID_REQUEST.getErrorMessage()); - } - - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.APPLICATIONID, appId, - "to get KeyInfo for application ID: " + appId + ", RefId: " + refId); - LocalDateTime timestamp = DateUtils.getUTCCurrentDateTime(); - Map> keyAliasMap = dbHelper.getKeyAliases(appId, refId, timestamp); - List currentKeyAlias = keyAliasMap.get(KeymanagerConstant.CURRENTKEYALIAS); - - if (currentKeyAlias.size() > 1) { - LOGGER.error(KeymanagerConstant.SESSIONID, KeymanagerConstant.CURRENTKEYALIAS, - String.valueOf(currentKeyAlias.size()), "CurrentKeyAlias size more than one"); - throw new NoUniqueAliasException(KeymanagerErrorConstant.NO_UNIQUE_ALIAS.getErrorCode(), - KeymanagerErrorConstant.NO_UNIQUE_ALIAS.getErrorMessage()); - } - - Boolean forceFlag = symGenRequestDto.getForce(); - if (forceFlag) { - LOGGER.debug(KeymanagerConstant.SESSIONID, KeymanagerConstant.APPLICATIONID, appId, - "Force Flag is True, Invalidating the existing key and generating new key."); - LocalDateTime expireTime = timestamp.minusMinutes(1L); - currentKeyAlias.forEach(alias -> { - dbHelper.storeKeyInAlias(appId, alias.getKeyGenerationTime(), refId, alias.getAlias(), expireTime); - }); - return generateAndBuildResponse(appId, refId, timestamp); - } - - if (currentKeyAlias.size() == 1){ - return buildSymGenKeyRespObject(timestamp, KeymanagerConstant.SYMM_KEY_EXISTS); - } - - return generateAndBuildResponse(appId, refId, timestamp); - } - - private SymmetricKeyGenerateResponseDto generateAndBuildResponse(String appId, String refId, LocalDateTime timestamp) { - - String alias = UUID.randomUUID().toString(); - LocalDateTime expiryDateTime = timestamp.plusDays(KeymanagerConstant.SYMMETRIC_KEY_VALIDITY); - keyStore.generateAndStoreSymmetricKey(alias); - dbHelper.storeKeyInAlias(appId, timestamp, refId, alias, expiryDateTime); - return buildSymGenKeyRespObject(timestamp, KeymanagerConstant.GENERATE_SUCCESS); - } - - private SymmetricKeyGenerateResponseDto buildSymGenKeyRespObject(LocalDateTime timestamp, String status){ - SymmetricKeyGenerateResponseDto responseDto = new SymmetricKeyGenerateResponseDto(); - responseDto.setStatus(status); - responseDto.setTimestamp(timestamp); - return responseDto; - } - - @Override - public RevokeKeyResponseDto revokeKey(RevokeKeyRequestDto revokeKeyRequest) { - - String appId = revokeKeyRequest.getApplicationId(); - String refId = revokeKeyRequest.getReferenceId(); - // Disable Auto Generation of functionality not implemented yet. - Boolean disableAutoGen = revokeKeyRequest.getDisableAutoGen() == null ? Boolean.FALSE : revokeKeyRequest.getDisableAutoGen(); - - LOGGER.info(KeymanagerConstant.SESSIONID, appId, refId, KeymanagerConstant.REQ_REV_KEY); - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.APPLICATIONID, appId, - KeymanagerConstant.REQ_REV_KEY + disableAutoGen); - - if (!keymanagerUtil.isValidReferenceId(refId) || - !keymanagerUtil.isValidApplicationId(appId)) { - LOGGER.error(KeymanagerConstant.SESSIONID, KeymanagerConstant.APPLICATIONID, null, - "Invalid Data provided to revoke key."); - throw new KeymanagerServiceException(KeymanagerErrorConstant.INVALID_REQUEST.getErrorCode(), - KeymanagerErrorConstant.INVALID_REQUEST.getErrorMessage()); - } - - if (appId.equalsIgnoreCase(signApplicationid) && refId.equalsIgnoreCase(certificateSignRefID)) { - LOGGER.error(KeymanagerConstant.SESSIONID, KeymanagerConstant.APPLICATIONID, null, - "Not allowed to revoke key. AppId: KERNEL & RefId: SIGN."); - throw new KeymanagerServiceException(KeymanagerErrorConstant.REVOKE_NOT_ALLOWED.getErrorCode(), - KeymanagerErrorConstant.REVOKE_NOT_ALLOWED.getErrorMessage()); - } - - LocalDateTime timestamp = DateUtils.getUTCCurrentDateTime(); - Map> keyAliasMap = dbHelper.getKeyAliases(appId, refId, timestamp); - List currentKeyAlias = keyAliasMap.get(KeymanagerConstant.CURRENTKEYALIAS); - - if (currentKeyAlias.isEmpty() || currentKeyAlias.size() > 1) { - LOGGER.error(KeymanagerConstant.SESSIONID, KeymanagerConstant.CURRENTKEYALIAS, - String.valueOf(currentKeyAlias.size()), "CurrentKeyAlias size more than one"); - throw new NoUniqueAliasException(KeymanagerErrorConstant.NO_UNIQUE_ALIAS.getErrorCode(), - KeymanagerErrorConstant.NO_UNIQUE_ALIAS.getErrorMessage()); - } - - LOGGER.debug(KeymanagerConstant.SESSIONID, appId, refId, "Invalidating the current valid key."); - - LocalDateTime expireTime = timestamp.minusMinutes(1L); - KeyAlias currentAlias = currentKeyAlias.get(0); - dbHelper.storeKeyInAlias(appId, currentAlias.getKeyGenerationTime(), refId, currentAlias.getAlias(), expireTime); - RevokeKeyResponseDto responseDto = new RevokeKeyResponseDto(); - responseDto.setStatus(KeymanagerConstant.KEY_REVOKED); - responseDto.setTimestamp(timestamp); - return responseDto; - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/util/KeymanagerUtil.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/util/KeymanagerUtil.java deleted file mode 100644 index 50622c361b8..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/util/KeymanagerUtil.java +++ /dev/null @@ -1,466 +0,0 @@ -package io.mosip.kernel.keymanagerservice.util; - -import static java.util.Arrays.copyOfRange; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.StringReader; -import java.io.StringWriter; -import java.nio.charset.StandardCharsets; -import java.security.KeyFactory; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.cert.Certificate; -import java.security.cert.CertificateException; -import java.security.cert.CertificateExpiredException; -import java.security.cert.CertificateFactory; -import java.security.cert.CertificateNotYetValidException; -import java.security.cert.X509Certificate; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.PKCS8EncodedKeySpec; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.time.ZoneOffset; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; -import java.util.Date; -import java.util.List; -import java.util.Objects; - -import javax.crypto.SecretKey; -import javax.crypto.spec.SecretKeySpec; -import javax.security.auth.DestroyFailedException; -import javax.security.auth.x500.X500Principal; - -import org.apache.commons.codec.binary.Base64; -import org.apache.commons.io.IOUtils; -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.x500.RDN; -import org.bouncycastle.asn1.x500.X500Name; -import org.bouncycastle.asn1.x500.style.BCStyle; -import org.bouncycastle.asn1.x500.style.IETFUtils; -import org.bouncycastle.openssl.jcajce.JcaPEMWriter; -import org.bouncycastle.util.io.pem.PemObject; -import org.bouncycastle.util.io.pem.PemReader; -import org.bouncycastle.operator.ContentSigner; -import org.bouncycastle.operator.OperatorCreationException; -import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; -import org.bouncycastle.pkcs.PKCS10CertificationRequest; -import org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder; -import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; - -import io.mosip.kernel.core.crypto.spi.CryptoCoreSpec; -import io.mosip.kernel.core.keymanager.exception.KeystoreProcessingException; -import io.mosip.kernel.core.keymanager.model.CertificateEntry; -import io.mosip.kernel.core.keymanager.model.CertificateParameters; -import io.mosip.kernel.core.util.CryptoUtil; -import io.mosip.kernel.core.util.DateUtils; -import io.mosip.kernel.keygenerator.bouncycastle.KeyGenerator; -import io.mosip.kernel.keymanager.hsm.constant.KeymanagerErrorCode; -import io.mosip.kernel.keymanagerservice.constant.KeymanagerConstant; -import io.mosip.kernel.keymanagerservice.constant.KeymanagerErrorConstant; -import io.mosip.kernel.keymanagerservice.dto.CSRGenerateRequestDto; -import io.mosip.kernel.keymanagerservice.dto.KeyPairGenerateRequestDto; -import io.mosip.kernel.keymanagerservice.entity.BaseEntity; -import io.mosip.kernel.keymanagerservice.entity.KeyAlias; -import io.mosip.kernel.keymanagerservice.exception.KeymanagerServiceException; -import io.mosip.kernel.keymanagerservice.logger.KeymanagerLogger; -import io.mosip.kernel.core.logger.spi.Logger; -/** - * Utility class for Keymanager - * - * @author Dharmesh Khandelwal - * @author Urvil Joshi - * @since 1.0.0 - * - */ - -@Component -public class KeymanagerUtil { - - private static final Logger LOGGER = KeymanagerLogger.getLogger(KeymanagerUtil.class); - - private static final String UTC_DATETIME_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; - - @Value("${mosip.kernel.keygenerator.asymmetric-algorithm-name}") - private String asymmetricAlgorithmName; - - /** - * KeySplitter for splitting key and data - */ - @Value("${mosip.kernel.data-key-splitter}") - private String keySplitter; - - /** - * Common Name for generating certificate - */ - @Value("${mosip.kernel.keymanager.certificate.default.common-name}") - private String commonName; - - /** - * Organizational Unit for generating certificate - */ - @Value("${mosip.kernel.keymanager.certificate.default.organizational-unit}") - private String organizationUnit; - - /** - * Organization for generating certificate - */ - @Value("${mosip.kernel.keymanager.certificate.default.organization}") - private String organization; - - /** - * Location for generating certificate - */ - @Value("${mosip.kernel.keymanager.certificate.default.location}") - private String location; - - /** - * State for generating certificate - */ - @Value("${mosip.kernel.keymanager.certificate.default.state}") - private String state; - - /** - * Country for generating certificate - */ - @Value("${mosip.kernel.keymanager.certificate.default.country}") - private String country; - - /** - * Field for symmetric Algorithm Name - */ - @Value("${mosip.kernel.crypto.symmetric-algorithm-name}") - private String symmetricAlgorithmName; - - /** - * Certificate Signing Algorithm - * - */ - @Value("${mosip.kernel.certificate.sign.algorithm:SHA256withRSA}") - private String signAlgorithm; - - /** - * KeyGenerator instance to generate asymmetric key pairs - */ - @Autowired - KeyGenerator keyGenerator; - - /** - * {@link CryptoCoreSpec} instance for cryptographic functionalities. - */ - @Autowired - private CryptoCoreSpec cryptoCore; - - /** - * Function to check valid timestamp - * - * @param timeStamp timeStamp - * @param keyAlias keyAlias - * @return true if timestamp is valid, else false - */ - public boolean isValidTimestamp(LocalDateTime timeStamp, KeyAlias keyAlias) { - return timeStamp.isEqual(keyAlias.getKeyGenerationTime()) || timeStamp.isEqual(keyAlias.getKeyExpiryTime()) - || (timeStamp.isAfter(keyAlias.getKeyGenerationTime()) - && timeStamp.isBefore(keyAlias.getKeyExpiryTime())); - } - - /** - * Function to check if timestamp is overlapping - * - * @param timeStamp timeStamp - * @param policyExpiryTime policyExpiryTime - * @param keyGenerationTime keyGenerationTime - * @param keyExpiryTime keyExpiryTime - * @return true if timestamp is overlapping, else false - */ - public boolean isOverlapping(LocalDateTime timeStamp, LocalDateTime policyExpiryTime, - LocalDateTime keyGenerationTime, LocalDateTime keyExpiryTime) { - return !timeStamp.isAfter(keyExpiryTime) && !keyGenerationTime.isAfter(policyExpiryTime); - } - - /** - * Function to check is reference id is valid - * - * @param referenceId referenceId - * @return true if referenceId is valid, else false - */ - public boolean isValidReferenceId(String referenceId) { - return referenceId != null && !referenceId.trim().isEmpty(); - } - - /** - * Function to set metadata - * - * @param is a type parameter - * @param entity entity of T type - * @return Entity with metadata - */ - public T setMetaData(T entity) { - String contextUser = "SYSTEM"; - LocalDateTime time = LocalDateTime.now(ZoneId.of("UTC")); - entity.setCreatedBy(contextUser); - entity.setCreatedtimes(time); - entity.setIsDeleted(false); - return entity; - } - - /** - * Function to encrypt key - * - * @param privateKey privateKey - * @param masterKey masterKey - * @return encrypted key - */ - public byte[] encryptKey(PrivateKey privateKey, PublicKey masterKey) { - SecretKey symmetricKey = keyGenerator.getSymmetricKey(); - byte[] encryptedPrivateKey = cryptoCore.symmetricEncrypt(symmetricKey, privateKey.getEncoded(), null); - byte[] encryptedSymmetricKey = cryptoCore.asymmetricEncrypt(masterKey, symmetricKey.getEncoded()); - return CryptoUtil.combineByteArray(encryptedPrivateKey, encryptedSymmetricKey, keySplitter); - } - - /** - * Function to decrypt key - * - * @param key key - * @param privateKey privateKey - * @return decrypted key - */ - public byte[] decryptKey(byte[] key, PrivateKey privateKey, PublicKey publicKey) { - return decryptKey(key, privateKey, publicKey, null); - } - - public byte[] decryptKey(byte[] key, PrivateKey privateKey, PublicKey publicKey, String keystoreType) { - - int keyDemiliterIndex = 0; - final int cipherKeyandDataLength = key.length; - final int keySplitterLength = keySplitter.length(); - keyDemiliterIndex = CryptoUtil.getSplitterIndex(key, keyDemiliterIndex, keySplitter); - byte[] encryptedKey = copyOfRange(key, 0, keyDemiliterIndex); - byte[] encryptedData = copyOfRange(key, keyDemiliterIndex + keySplitterLength, cipherKeyandDataLength); - byte[] decryptedSymmetricKey = cryptoCore.asymmetricDecrypt(privateKey, publicKey, encryptedKey, keystoreType); - SecretKey symmetricKey = new SecretKeySpec(decryptedSymmetricKey, 0, decryptedSymmetricKey.length, - symmetricAlgorithmName); - return cryptoCore.symmetricDecrypt(symmetricKey, encryptedData, null); - } - - /** - * Parse a date string of pattern UTC_DATETIME_PATTERN into - * {@link LocalDateTime} - * - * @param dateTime of type {@link String} of pattern UTC_DATETIME_PATTERN - * @return a {@link LocalDateTime} of given pattern - */ - public LocalDateTime parseToLocalDateTime(String dateTime) { - return LocalDateTime.parse(dateTime, DateTimeFormatter.ofPattern(UTC_DATETIME_PATTERN)); - } - - public void isCertificateValid(CertificateEntry certificateEntry, Date inputDate) { - try { - certificateEntry.getChain()[0].checkValidity(inputDate); - } catch (CertificateExpiredException | CertificateNotYetValidException e) { - throw new KeystoreProcessingException(KeymanagerErrorCode.CERTIFICATE_PROCESSING_ERROR.getErrorCode(), - KeymanagerErrorCode.CERTIFICATE_PROCESSING_ERROR.getErrorMessage() + e.getMessage()); - } - } - - public PrivateKey privateKeyExtractor(InputStream privateKeyInputStream) { - - KeyFactory kf = null; - PKCS8EncodedKeySpec keySpec = null; - PrivateKey privateKey = null; - try { - StringWriter stringWriter = new StringWriter(); - IOUtils.copy(privateKeyInputStream, stringWriter, StandardCharsets.UTF_8); - String privateKeyPEMString = stringWriter.toString(); - byte[] decodedKey = Base64.decodeBase64(privateKeyPEMString); - kf = KeyFactory.getInstance(asymmetricAlgorithmName); - keySpec = new PKCS8EncodedKeySpec(decodedKey); - privateKey = kf.generatePrivate(keySpec); - - } catch (NoSuchAlgorithmException | InvalidKeySpecException | IOException e) { - throw new KeystoreProcessingException(KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorCode(), - KeymanagerErrorCode.KEYSTORE_PROCESSING_ERROR.getErrorMessage() + e.getMessage()); - } - - return privateKey; - } - - public boolean isValidResponseType(String responseType) { - return responseType != null && !responseType.trim().isEmpty(); - } - - public boolean isValidApplicationId(String appId) { - return appId != null && !appId.trim().isEmpty(); - } - - public boolean isValidCertificateData(String certData) { - return certData != null && !certData.trim().isEmpty(); - } - - public Certificate convertToCertificate(String certData) { - try { - StringReader strReader = new StringReader(certData); - PemReader pemReader = new PemReader(strReader); - PemObject pemObject = pemReader.readPemObject(); - if (Objects.isNull(pemObject)) { - LOGGER.error(KeymanagerConstant.SESSIONID, KeymanagerConstant.CERTIFICATE_PARSE, - KeymanagerConstant.CERTIFICATE_PARSE, "Error Parsing Certificate."); - throw new KeymanagerServiceException(io.mosip.kernel.keymanagerservice.constant.KeymanagerErrorConstant.CERTIFICATE_PARSING_ERROR.getErrorCode(), - KeymanagerErrorConstant.CERTIFICATE_PARSING_ERROR.getErrorMessage()); - } - byte[] certBytes = pemObject.getContent(); - CertificateFactory certFactory = CertificateFactory.getInstance(KeymanagerConstant.CERTIFICATE_TYPE); - return certFactory.generateCertificate(new ByteArrayInputStream(certBytes)); - } catch(IOException | CertificateException e) { - throw new KeymanagerServiceException(KeymanagerErrorConstant.CERTIFICATE_PARSING_ERROR.getErrorCode(), - KeymanagerErrorConstant.CERTIFICATE_PARSING_ERROR.getErrorMessage() + e.getMessage()); - } - } - - public Certificate convertToCertificate(byte[] certDataBytes) { - try { - CertificateFactory certFactory = CertificateFactory.getInstance(KeymanagerConstant.CERTIFICATE_TYPE); - return certFactory.generateCertificate(new ByteArrayInputStream(certDataBytes)); - } catch(CertificateException e) { - throw new KeymanagerServiceException(KeymanagerErrorConstant.CERTIFICATE_PARSING_ERROR.getErrorCode(), - KeymanagerErrorConstant.CERTIFICATE_PARSING_ERROR.getErrorMessage() + e.getMessage()); - } - } - - public String getPEMFormatedData(Object anyObject){ - - StringWriter stringWriter = new StringWriter(); - try (JcaPEMWriter pemWriter = new JcaPEMWriter(stringWriter)) { - pemWriter.writeObject(anyObject); - pemWriter.flush(); - return stringWriter.toString(); - } catch (IOException ioExp) { - throw new KeymanagerServiceException(KeymanagerErrorConstant.INTERNAL_SERVER_ERROR.getErrorCode(), - KeymanagerErrorConstant.INTERNAL_SERVER_ERROR.getErrorMessage(), ioExp); - } - } - - public CertificateParameters getCertificateParameters(X500Principal latestCertPrincipal, LocalDateTime notBefore, LocalDateTime notAfter) { - - CertificateParameters certParams = new CertificateParameters(); - X500Name x500Name = new X500Name(latestCertPrincipal.getName()); - - certParams.setCommonName(IETFUtils.valueToString((x500Name.getRDNs(BCStyle.CN)[0]).getFirst().getValue())); - certParams.setOrganizationUnit(getParamValue(getAttributeIfExist(x500Name, BCStyle.OU), organizationUnit)); - certParams.setOrganization(getParamValue(getAttributeIfExist(x500Name, BCStyle.O), organization)); - certParams.setLocation(getParamValue(getAttributeIfExist(x500Name, BCStyle.L), location)); - certParams.setState(getParamValue(getAttributeIfExist(x500Name, BCStyle.ST), state)); - certParams.setCountry(getParamValue(getAttributeIfExist(x500Name, BCStyle.C), country)); - certParams.setNotBefore(notBefore); - certParams.setNotAfter(notAfter); - return certParams; - } - - private static String getAttributeIfExist(X500Name x500Name, ASN1ObjectIdentifier identifier) { - RDN[] rdns = x500Name.getRDNs(identifier); - if (rdns.length == 0) { - return KeymanagerConstant.EMPTY; - } - return IETFUtils.valueToString((rdns[0]).getFirst().getValue()); - } - - public CertificateParameters getCertificateParameters(KeyPairGenerateRequestDto request, LocalDateTime notBefore, LocalDateTime notAfter, - String appId) { - - CertificateParameters certParams = new CertificateParameters(); - String appIdCommonName = commonName + " (" + appId.toUpperCase() + ")"; - certParams.setCommonName(getParamValue(request.getCommonName(), appIdCommonName)); - certParams.setOrganizationUnit(getParamValue(request.getOrganizationUnit(), organizationUnit)); - certParams.setOrganization(getParamValue(request.getOrganization(), organization)); - certParams.setLocation(getParamValue(request.getLocation(), location)); - certParams.setState(getParamValue(request.getState(), state)); - certParams.setCountry(getParamValue(request.getCountry(), country)); - certParams.setNotBefore(notBefore); - certParams.setNotAfter(notAfter); - return certParams; - } - - public CertificateParameters getCertificateParameters(CSRGenerateRequestDto request, LocalDateTime notBefore, LocalDateTime notAfter) { - - CertificateParameters certParams = new CertificateParameters(); - certParams.setCommonName(getParamValue(request.getCommonName(), commonName)); - certParams.setOrganizationUnit(getParamValue(request.getOrganizationUnit(), organizationUnit)); - certParams.setOrganization(getParamValue(request.getOrganization(), organization)); - certParams.setLocation(getParamValue(request.getLocation(), location)); - certParams.setState(getParamValue(request.getState(), state)); - certParams.setCountry(getParamValue(request.getCountry(), country)); - certParams.setNotBefore(notBefore); - certParams.setNotAfter(notAfter); - return certParams; - } - - public CertificateParameters getCertificateParameters(String cName, LocalDateTime notBefore, LocalDateTime notAfter) { - - CertificateParameters certParams = new CertificateParameters(); - certParams.setCommonName(getParamValue(cName, commonName)); - certParams.setOrganizationUnit(getParamValue(KeymanagerConstant.EMPTY, organizationUnit)); - certParams.setOrganization(getParamValue(KeymanagerConstant.EMPTY, organization)); - certParams.setLocation(getParamValue(KeymanagerConstant.EMPTY, location)); - certParams.setState(getParamValue(KeymanagerConstant.EMPTY, state)); - certParams.setCountry(getParamValue(KeymanagerConstant.EMPTY, country)); - certParams.setNotBefore(notBefore); - certParams.setNotAfter(notAfter); - return certParams; - } - - private String getParamValue(String value, String defaultValue){ - if (Objects.nonNull(value) && !value.trim().isEmpty()) - return value; - - return defaultValue; - } - - public String getCSR(PrivateKey privateKey, PublicKey publicKey, CertificateParameters certParams) { - - try { - X500Principal csrSubject = new X500Principal("CN=" + certParams.getCommonName() + ", OU=" + certParams.getOrganizationUnit() + - ", O=" + certParams.getOrganization() + ", L=" + certParams.getLocation() + - ", S=" + certParams.getState() + ", C=" + certParams.getCountry()); - ContentSigner contentSigner = new JcaContentSignerBuilder(signAlgorithm).build(privateKey); - PKCS10CertificationRequestBuilder pcks10Builder = new JcaPKCS10CertificationRequestBuilder(csrSubject, publicKey); - PKCS10CertificationRequest csrObject = pcks10Builder.build(contentSigner); - return getPEMFormatedData(csrObject); - } catch (OperatorCreationException exp) { - throw new KeymanagerServiceException(KeymanagerErrorConstant.INTERNAL_SERVER_ERROR.getErrorCode(), - KeymanagerErrorConstant.INTERNAL_SERVER_ERROR.getErrorMessage(), exp); - } - } - - public void destoryKey(PrivateKey privateKey) { - try { - privateKey.destroy(); - } catch (DestroyFailedException e) { - LOGGER.warn(KeymanagerConstant.SESSIONID, KeymanagerConstant.EMPTY, KeymanagerConstant.EMPTY, - "Warning - while destorying Private Key Object."); - } - privateKey = null; - } - - public void destoryKey(SecretKey secretKey) { - try { - secretKey.destroy(); - } catch (DestroyFailedException e) { - LOGGER.warn(KeymanagerConstant.SESSIONID, KeymanagerConstant.EMPTY, KeymanagerConstant.EMPTY, - "Warning - while destorying Secret Key Object."); - } - secretKey = null; - } - - public LocalDateTime convertToUTC(Date anyDate) { - LocalDateTime ldTime = DateUtils.parseDateToLocalDateTime(anyDate); - ZonedDateTime zonedtime = ldTime.atZone(ZoneId.systemDefault()); - ZonedDateTime converted = zonedtime.withZoneSameInstant(ZoneOffset.UTC); - return converted.toLocalDateTime(); - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/constant/KeyMigratorConstants.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/constant/KeyMigratorConstants.java deleted file mode 100644 index 96eda68397f..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/constant/KeyMigratorConstants.java +++ /dev/null @@ -1,28 +0,0 @@ -package io.mosip.kernel.keymigrate.constant; - -public interface KeyMigratorConstants { - - String SESSIONID = "keyMigrateSessionID"; - - String BASE_KEY = "BASE_KEY"; - - String EMPTY = ""; - - String PARTNER_APPID = "PARTNER"; - - String MIGRAION_SUCCESS = "Migration Success"; - - String MIGRAION_FAILED = "Error in Migration"; - - String MIGRAION_NOT_ALLOWED = "Migration Not Allowed. Valid Key Exists."; - - String ZK_KEYS = "ZK_KEYS"; - - String ZK_TEMP_KEY_APP_ID = "KEY_MIGRATE"; - - String ZK_TEMP_KEY_REF_ID = "ZK_TEMP_KEY"; - - String ZK_CERT_COMMON_NAME = "ZKKeysSelfSignedKey"; - - String ACTIVE_STATUS = "Active"; -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/controller/KeyMigratorController.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/controller/KeyMigratorController.java deleted file mode 100644 index d55c2583061..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/controller/KeyMigratorController.java +++ /dev/null @@ -1,95 +0,0 @@ -package io.mosip.kernel.keymigrate.controller; - -import javax.validation.Valid; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Lazy; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.CrossOrigin; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RestController; - -import io.mosip.kernel.keymigrate.dto.KeyMigrateBaseKeyRequestDto; -import io.mosip.kernel.keymigrate.dto.KeyMigrateBaseKeyResponseDto; -import io.mosip.kernel.keymigrate.dto.ZKKeyMigrateCertficateResponseDto; -import io.mosip.kernel.keymigrate.dto.ZKKeyMigrateRequestDto; -import io.mosip.kernel.keymigrate.dto.ZKKeyMigrateResponseDto; -import io.mosip.kernel.keymigrate.service.spi.KeyMigratorService; -import io.swagger.annotations.Api; -import io.mosip.kernel.core.http.RequestWrapper; -import io.mosip.kernel.core.http.ResponseFilter; -import io.mosip.kernel.core.http.ResponseWrapper; -import io.swagger.annotations.ApiParam; - -/** - * Rest Controller for Key Migration from one HSM to another HSM. - * - * @author Mahammed Taheer - * - * @since 1.1.6 - */ - -@Lazy -@CrossOrigin -@RestController -@Api(value = "Operation related to Key Migration from one HSM to another HSM.", tags = { "keymigrator" }) -public class KeyMigratorController { - - /** - * Instance for KeyMigratorService - */ - @Autowired - KeyMigratorService keyMigratorService; - - /** - * Controller for migrating base key. - * - * @param migrateBaseKeyRequestDto {@link KeyMigrateBaseKeyRequestDto} request - * @return {@link KeyMigrateBaseKeyAddResponseDto} migrate response - */ - @PreAuthorize("hasAnyRole('KEY_MIGRATION_ADMIN')") - @ResponseFilter - @PostMapping(value = "/migrateBaseKey", produces = "application/json") - public ResponseWrapper migrateBaseKey( - @ApiParam("Base Key Migrate Attributes.") @RequestBody @Valid RequestWrapper migrateBaseKeyRequestDto) { - - ResponseWrapper response = new ResponseWrapper<>(); - response.setResponse(keyMigratorService.migrateBaseKey(migrateBaseKeyRequestDto.getRequest())); - return response; - } - - /** - * Controller to get the certificate for migrating ZK keys. - * - * @param migrateBaseKeyRequestDto {@link KeyMigrateBaseKeyRequestDto} request - * @return {@link KeyMigrateBaseKeyAddResponseDto} migrate response - */ - @PreAuthorize("hasAnyRole('KEY_MIGRATION_ADMIN')") - @ResponseFilter - @GetMapping(value = "/getZKTempCertificate", produces = "application/json") - public ResponseWrapper getZKTempCertificate() { - - ResponseWrapper response = new ResponseWrapper<>(); - response.setResponse(keyMigratorService.getZKTempCertificate()); - return response; - } - - /** - * Controller for migrating ZK keys. - * - * @param migrateZKKeysRequestDto {@link ZKKeyMigrateRequestDto} request - * @return {@link ZKKeyMigrateResponseDto} migrate response - */ - @PreAuthorize("hasAnyRole('KEY_MIGRATION_ADMIN')") - @ResponseFilter - @PostMapping(value = "/migrateZKKeys", produces = "application/json") - public ResponseWrapper migrateZKKeys( - @ApiParam("ZK Keys Migrate Attributes.") @RequestBody @Valid RequestWrapper migrateZKKeysRequestDto) { - - ResponseWrapper response = new ResponseWrapper<>(); - response.setResponse(keyMigratorService.migrateZKKeys(migrateZKKeysRequestDto.getRequest())); - return response; - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/dto/KeyMigrateBaseKeyRequestDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/dto/KeyMigrateBaseKeyRequestDto.java deleted file mode 100644 index e440a142c6b..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/dto/KeyMigrateBaseKeyRequestDto.java +++ /dev/null @@ -1,70 +0,0 @@ -package io.mosip.kernel.keymigrate.dto; - -import java.time.LocalDateTime; - -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.NotNull; - -import com.fasterxml.jackson.annotation.JsonFormat; - -import io.mosip.kernel.keymanagerservice.constant.KeymanagerConstant; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * To insert Base Key in Key Manager using Key Migration. - * - * @author Mahammed Taheer - * @since 1.1.5 - */ -@Data -@AllArgsConstructor -@NoArgsConstructor -@ApiModel(description = "Model representing a base key migration from one HSM to another") -public class KeyMigrateBaseKeyRequestDto { - - /** - * Application Id For Migrating KeyPair - */ - @ApiModelProperty(notes = "Application ID", example = "REGISTRATION", required = true) - @NotBlank(message = KeymanagerConstant.INVALID_REQUEST) - private String applicationId; - - /** - * Reference Id For Migrating KeyPair - */ - @ApiModelProperty(notes = "Reference ID", example = "", required = true) - @NotBlank(message = KeymanagerConstant.INVALID_REQUEST) - private String referenceId; - - /** - * Encrypted Private Key data For Migrating KeyPair - */ - @ApiModelProperty(notes = "Encrypted Private Key Data", example = " ", required = true) - @NotBlank(message = KeymanagerConstant.INVALID_REQUEST) - private String encryptedKeyData; - - /** - * Certificate For Migrating KeyPair - */ - @ApiModelProperty(notes = "Certificate Data", example = "", required = true) - @NotBlank(message = KeymanagerConstant.INVALID_REQUEST) - private String certificateData; - - /** - * Start key validity of the migrating key - */ - @ApiModelProperty(notes = "Timestamp of start key validity", example = "2021-01-01T00:00:00.000Z", required = true) - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") - private LocalDateTime notBefore; - - /** - * End key validity of the migrating key - */ - @ApiModelProperty(notes = "Timestamp of end key validity", example = "2023-01-01T00:00:00.000Z", required = true) - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") - private LocalDateTime notAfter; -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/dto/KeyMigrateBaseKeyResponseDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/dto/KeyMigrateBaseKeyResponseDto.java deleted file mode 100644 index 05540cb3c3d..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/dto/KeyMigrateBaseKeyResponseDto.java +++ /dev/null @@ -1,32 +0,0 @@ -package io.mosip.kernel.keymigrate.dto; - -import java.time.LocalDateTime; - -import io.swagger.annotations.ApiModel; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * Response class for Key Pair Migration. - * - * @author Mahammed Taheer - * @since 1.1.15 - * - */ -@Data -@AllArgsConstructor -@NoArgsConstructor -@ApiModel(description = "Class representing a Migration of KeyPair Response") -public class KeyMigrateBaseKeyResponseDto { - - /** - * Status of key migration. - */ - private String status; - - /** - * Timestamp. - */ - private LocalDateTime timestamp; -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/dto/ZKKeyDataDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/dto/ZKKeyDataDto.java deleted file mode 100644 index f267af26e01..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/dto/ZKKeyDataDto.java +++ /dev/null @@ -1,37 +0,0 @@ -package io.mosip.kernel.keymigrate.dto; -import javax.validation.constraints.NotBlank; - -import io.mosip.kernel.keymanagerservice.constant.KeymanagerConstant; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * ZK Encrypted Key Data for migration. - * - * @author Mahammed Taheer - * @since 1.1.6 - */ -@Data -@AllArgsConstructor -@NoArgsConstructor -@ApiModel(description = "ZK Encrypted Key Data for migration") -public class ZKKeyDataDto { - - - /** - * Key Index for the encrypted key data. - */ - @ApiModelProperty(notes = "Key Index", example = "index", required = true) - @NotBlank(message = KeymanagerConstant.INVALID_REQUEST) - private int keyIndex; - - /** - * ZK Encrypted Key data. - */ - @ApiModelProperty(notes = "Encrypted Key Data for ZK.", example = "Encrypted String", required = true) - @NotBlank(message = KeymanagerConstant.INVALID_REQUEST) - private String encryptedKeyData; -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/dto/ZKKeyMigrateCertficateResponseDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/dto/ZKKeyMigrateCertficateResponseDto.java deleted file mode 100644 index 5a031f02fbd..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/dto/ZKKeyMigrateCertficateResponseDto.java +++ /dev/null @@ -1,39 +0,0 @@ -package io.mosip.kernel.keymigrate.dto; - -import java.time.LocalDateTime; - -import com.fasterxml.jackson.annotation.JsonFormat; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * Response class for ZK temporary key. - * - * @author Mahammed Taheer - * @since 1.1.6 - * - */ -@Data -@AllArgsConstructor -@NoArgsConstructor -@ApiModel(description = "Class representing a Certificate Response for ZK migration.") -public class ZKKeyMigrateCertficateResponseDto { - - /** - * Field for certificate - */ - @ApiModelProperty(notes = "X509 self-signed certificate", required = false) - private String certificate; - - /** - * Key expiry time - */ - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") - @ApiModelProperty(notes = "Timestamp of public key", required = true) - private LocalDateTime timestamp; - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/dto/ZKKeyMigrateRequestDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/dto/ZKKeyMigrateRequestDto.java deleted file mode 100644 index a5cb2649dd6..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/dto/ZKKeyMigrateRequestDto.java +++ /dev/null @@ -1,34 +0,0 @@ -package io.mosip.kernel.keymigrate.dto; -import java.util.List; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * Zero Knowledge Migrate Keys Request DTO. - * - * @author Mahammed Taheer - * @since 1.1.6 -*/ - -@Data -@AllArgsConstructor -@NoArgsConstructor -@ApiModel(description = "Model representing request for Zero Knowledge Keys Migration.") -public class ZKKeyMigrateRequestDto { - - /** - * List of ZK key to be migrated. - */ - @ApiModelProperty(notes = "ZK Encrypted Keys List.", required = true) - List zkEncryptedDataList; - - /** - * Flag to purge the temporary generated key. - */ - @ApiModelProperty(notes = "Flag to purge the key.", required = true) - Boolean purgeTempKeyFlag; -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/dto/ZKKeyMigrateResponseDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/dto/ZKKeyMigrateResponseDto.java deleted file mode 100644 index bbae3eb3dc5..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/dto/ZKKeyMigrateResponseDto.java +++ /dev/null @@ -1,28 +0,0 @@ -package io.mosip.kernel.keymigrate.dto; -import java.util.List; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * Zero Knowledge Migrate Keys Response DTO. - * - * @author Mahammed Taheer - * @since 1.1.6 -*/ - -@Data -@AllArgsConstructor -@NoArgsConstructor -@ApiModel(description = "Model representing response for Zero Knowledge Keys Migration.") -public class ZKKeyMigrateResponseDto { - - /** - * List of status message for ZK keys to be migrated. - */ - @ApiModelProperty(notes = "ZK migration response List.", required = true) - List zkEncryptedDataList; -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/dto/ZKKeyResponseDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/dto/ZKKeyResponseDto.java deleted file mode 100644 index 743634b23b2..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/dto/ZKKeyResponseDto.java +++ /dev/null @@ -1,37 +0,0 @@ -package io.mosip.kernel.keymigrate.dto; -import javax.validation.constraints.NotBlank; - -import io.mosip.kernel.keymanagerservice.constant.KeymanagerConstant; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * ZK Encrypted Key Data for migration response message. - * - * @author Mahammed Taheer - * @since 1.1.6 - */ -@Data -@AllArgsConstructor -@NoArgsConstructor -@ApiModel(description = "ZK Encrypted Key Data response") -public class ZKKeyResponseDto { - - - /** - * Key Index for the encrypted key data. - */ - @ApiModelProperty(notes = "Key Index", example = "index") - @NotBlank(message = KeymanagerConstant.INVALID_REQUEST) - private int keyIndex; - - /** - * Migrate response Message. - */ - @ApiModelProperty(notes = "Status of Migrated ZK key.", example = "String") - @NotBlank(message = KeymanagerConstant.INVALID_REQUEST) - private String statusMessage; -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/service/impl/KeyMigratorServiceImpl.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/service/impl/KeyMigratorServiceImpl.java deleted file mode 100644 index be81c303caa..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/service/impl/KeyMigratorServiceImpl.java +++ /dev/null @@ -1,367 +0,0 @@ -package io.mosip.kernel.keymigrate.service.impl; - -import java.security.InvalidKeyException; -import java.security.Key; -import java.security.KeyStore.PrivateKeyEntry; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.Base64; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.UUID; -import java.util.stream.Stream; - -import javax.crypto.BadPaddingException; -import javax.crypto.Cipher; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; -import javax.crypto.SecretKey; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Lazy; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import io.mosip.kernel.core.crypto.exception.InvalidDataException; -import io.mosip.kernel.core.crypto.spi.CryptoCoreSpec; -import io.mosip.kernel.core.keymanager.model.CertificateParameters; -import io.mosip.kernel.core.keymanager.spi.KeyStore; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.CryptoUtil; -import io.mosip.kernel.core.util.DateUtils; -import io.mosip.kernel.keymanagerservice.constant.KeymanagerConstant; -import io.mosip.kernel.keymanagerservice.constant.KeymanagerErrorConstant; -import io.mosip.kernel.keymanagerservice.entity.KeyAlias; -import io.mosip.kernel.keymanagerservice.exception.NoUniqueAliasException; -import io.mosip.kernel.keymanagerservice.helper.KeymanagerDBHelper; -import io.mosip.kernel.keymanagerservice.logger.KeymanagerLogger; -import io.mosip.kernel.keymanagerservice.util.KeymanagerUtil; -import io.mosip.kernel.keymigrate.constant.KeyMigratorConstants; -import io.mosip.kernel.keymigrate.dto.KeyMigrateBaseKeyRequestDto; -import io.mosip.kernel.keymigrate.dto.KeyMigrateBaseKeyResponseDto; -import io.mosip.kernel.keymigrate.dto.ZKKeyDataDto; -import io.mosip.kernel.keymigrate.dto.ZKKeyMigrateCertficateResponseDto; -import io.mosip.kernel.keymigrate.dto.ZKKeyMigrateRequestDto; -import io.mosip.kernel.keymigrate.dto.ZKKeyMigrateResponseDto; -import io.mosip.kernel.keymigrate.dto.ZKKeyResponseDto; -import io.mosip.kernel.keymigrate.service.spi.KeyMigratorService; -import io.mosip.kernel.keymanagerservice.entity.DataEncryptKeystore; -import io.mosip.kernel.keymanagerservice.repository.DataEncryptKeystoreRepository; - - -/** - * Service Implementation for {@link KeyMigratorService} interface - * - * @author Mahammed Taheer - * - * @since 1.1.6 - */ -@Lazy -@Service -@Transactional -public class KeyMigratorServiceImpl implements KeyMigratorService { - - private static final Logger LOGGER = KeymanagerLogger.getLogger(KeyMigratorServiceImpl.class); - - private static final String CREATED_BY = "System-Migrator"; - - @Value("${mosip.kernel.partner.sign.masterkey.application.id:PMS}") - private String pmsSignAppId; - - @Value("${mosip.kernel.certificate.sign.algorithm:SHA256withRSA}") - private String signAlgorithm; - - @Value("${mosip.kernel.zkcrypto.masterkey.application.id:KERNEL}") - private String masterKeyAppId; - - @Value("${mosip.kernel.zkcrypto.masterkey.reference.id:IDENTITY_CACHE}") - private String masterKeyRefId; - - @Value("${mosip.kernel.zkcrypto.wrap.algorithm-name:AES/ECB/NoPadding}") - private String aesECBTransformation; - - /** - * KeymanagerDBHelper instance to handle all DB operations - */ - @Autowired - private KeymanagerDBHelper dbHelper; - - @Autowired - KeymanagerUtil keymanagerUtil; - - /** - * Keystore instance to handles and store cryptographic keys. - */ - @Autowired - private KeyStore keyStore; - - /** - * {@link CryptoCoreSpec} instance for cryptographic functionalities. - */ - @Autowired - private CryptoCoreSpec cryptoCore; - - @Autowired - DataEncryptKeystoreRepository dataEncryptKeystoreRepository; - - @Override - public KeyMigrateBaseKeyResponseDto migrateBaseKey(KeyMigrateBaseKeyRequestDto baseKeyMigrateRequest){ - LOGGER.info(KeyMigratorConstants.SESSIONID, KeyMigratorConstants.BASE_KEY, - KeyMigratorConstants.EMPTY, "Base Key Migration Migration."); - - String appId = baseKeyMigrateRequest.getApplicationId(); - String refId = baseKeyMigrateRequest.getReferenceId(); - String encryptedPrivateKey = baseKeyMigrateRequest.getEncryptedKeyData(); - String certificateData = baseKeyMigrateRequest.getCertificateData(); - LocalDateTime notBefore = baseKeyMigrateRequest.getNotBefore(); - LocalDateTime notAfter = baseKeyMigrateRequest.getNotAfter(); - LocalDateTime localDateTimeStamp = DateUtils.getUTCCurrentDateTime(); - - Map> keyAliasMap = dbHelper.getKeyAliases(appId, KeyMigratorConstants.EMPTY, localDateTimeStamp); - List currentKeyAlias = keyAliasMap.get(KeymanagerConstant.CURRENTKEYALIAS); - - if (currentKeyAlias.isEmpty() && !appId.equals(KeyMigratorConstants.PARTNER_APPID)) { - LOGGER.error(KeyMigratorConstants.SESSIONID, KeymanagerConstant.CURRENTKEYALIAS, - String.valueOf(currentKeyAlias.size()), "No CurrentKeyAlias found Throwing exception"); - throw new NoUniqueAliasException(KeymanagerErrorConstant.NO_UNIQUE_ALIAS.getErrorCode(), - KeymanagerErrorConstant.NO_UNIQUE_ALIAS.getErrorMessage()); - } - - if (isValidKeyExists(appId, refId, notBefore, notAfter, localDateTimeStamp)) { - LOGGER.error(KeyMigratorConstants.SESSIONID, KeyMigratorConstants.EMPTY, - KeyMigratorConstants.EMPTY, "Valid Key Already exists, not allowed to migrate."); - KeyMigrateBaseKeyResponseDto responseDto = new KeyMigrateBaseKeyResponseDto(); - responseDto.setStatus(KeyMigratorConstants.MIGRAION_NOT_ALLOWED); - responseDto.setTimestamp(localDateTimeStamp); - return responseDto; - } - String baseKeyAlias = UUID.randomUUID().toString(); - String masterKeyAlias = currentKeyAlias.isEmpty() ? baseKeyAlias : currentKeyAlias.get(0).getAlias(); - - // Re-Signing any base key Certificate is not possible because thumbprint will not match with the prepended thumbprint in encrypted data. - // Re-signing of partner certificate is not required because existing trust certificates (MOSIP_ROOT & PMS) from old KM might - // have got synced with other components performing trust validation. New KM certificates (MOSIP_ROOT & PMS) will get synced - // with other components and both will be used to validate the trust. - //String reSignedCert = reSignCertificate(appId, masterKeyAlias, certificateData, localDateTimeStamp, notBefore, notAfter); - dbHelper.storeKeyInDBStore(baseKeyAlias, masterKeyAlias, certificateData, encryptedPrivateKey); - dbHelper.storeKeyInAlias(appId, notBefore, refId, baseKeyAlias, notAfter); - - LOGGER.info(KeyMigratorConstants.SESSIONID, KeyMigratorConstants.BASE_KEY, - KeyMigratorConstants.EMPTY, "Migration Completed for App Id:" + appId + ", Ref Id: " + refId - + ", Inserted UUID: " + baseKeyAlias); - - KeyMigrateBaseKeyResponseDto responseDto = new KeyMigrateBaseKeyResponseDto(); - responseDto.setStatus(KeyMigratorConstants.MIGRAION_SUCCESS); - responseDto.setTimestamp(localDateTimeStamp); - return responseDto; - } - - private boolean isValidKeyExists(String applicationId, String referenceId, LocalDateTime notBefore, - LocalDateTime notAfter, LocalDateTime localDateTimeStamp) { - Map> keyAliasMap = dbHelper.getKeyAliases(applicationId, referenceId, localDateTimeStamp); - List currentKeyAlias = keyAliasMap.get(KeymanagerConstant.CURRENTKEYALIAS); - // Current key alias is empty, no need to check whether migrated key is valid or expired. Simply migrate it. - if (currentKeyAlias.isEmpty()) { - return false; - } - - // Current key alias is not empty, check whether migrated key is also valid. - // Both valid, do not allowed to migrate the key. - if (localDateTimeStamp.isEqual(notBefore) || localDateTimeStamp.isEqual(notAfter) - || (localDateTimeStamp.isAfter(notBefore) && localDateTimeStamp.isBefore(notAfter))) { - return true; - } - return false; - } - - /* private String reSignCertificate(String appId, String masterKeyAlias, String oldCertData, LocalDateTime localDateTimeStamp, - LocalDateTime notBefore, LocalDateTime notAfter) { - - String keyAlias = masterKeyAlias; - if (appId.equals(KeyMigratorConstants.PARTNER_APPID)){ - Map> keyAliasMap = dbHelper.getKeyAliases(pmsSignAppId, KeyMigratorConstants.EMPTY, localDateTimeStamp); - List currentKeyAlias = keyAliasMap.get(KeymanagerConstant.CURRENTKEYALIAS); - if (currentKeyAlias.isEmpty()) { - LOGGER.info(KeyMigratorConstants.SESSIONID, KeymanagerConstant.CURRENTKEYALIAS, - String.valueOf(currentKeyAlias.size()), "No CurrentKeyAlias found for PMS Sign Key. Throwing exception"); - throw new NoUniqueAliasException(KeymanagerErrorConstant.NO_UNIQUE_ALIAS.getErrorCode(), - KeymanagerErrorConstant.NO_UNIQUE_ALIAS.getErrorMessage()); - } - keyAlias = currentKeyAlias.get(0).getAlias(); - } - PrivateKeyEntry masterKeyEntry = keyStore.getAsymmetricKey(keyAlias); - PrivateKey masterPrivateKey = masterKeyEntry.getPrivateKey(); - X509Certificate signerCert = masterKeyEntry.getCertificate(); - X500Principal signerPrincipal = signerCert.getSubjectX500Principal(); - - X509Certificate oldCert = (X509Certificate) keymanagerUtil.convertToCertificate(oldCertData); - X500Principal oldCertPrincipal = oldCert.getSubjectX500Principal(); - CertificateParameters certParams = keymanagerUtil.getCertificateParameters(oldCertPrincipal, - notBefore, notAfter); - - X509Certificate x509Cert = (X509Certificate) CertificateUtility.generateX509Certificate(masterPrivateKey, oldCert.getPublicKey(), - certParams, signerPrincipal, signAlgorithm, keyStore.getKeystoreProviderName()); - return keymanagerUtil.getPEMFormatedData(x509Cert); - } */ - - @Override - public ZKKeyMigrateCertficateResponseDto getZKTempCertificate() { - - LOGGER.info(KeyMigratorConstants.SESSIONID, KeyMigratorConstants.ZK_KEYS, - KeyMigratorConstants.EMPTY, "Get Temporary Certificate for ZK keys migration."); - - LocalDateTime localDateTimeStamp = DateUtils.getUTCCurrentDateTime(); - - Map> keyAliasMap = dbHelper.getKeyAliases(KeyMigratorConstants.ZK_TEMP_KEY_APP_ID, - KeyMigratorConstants.ZK_TEMP_KEY_REF_ID, localDateTimeStamp); - List KeyAlias = keyAliasMap.get(KeymanagerConstant.KEYALIAS); - List currentKeyAlias = keyAliasMap.get(KeymanagerConstant.CURRENTKEYALIAS); - - ZKKeyMigrateCertficateResponseDto responseDto = new ZKKeyMigrateCertficateResponseDto(); - if (currentKeyAlias.isEmpty() && KeyAlias.size() > 0) { - LOGGER.info(KeyMigratorConstants.SESSIONID, KeyMigratorConstants.ZK_KEYS, - String.valueOf(KeyAlias.size()), "Key Exists but expired, so removing the key and generating new key."); - String alias = KeyAlias.get((KeyAlias.size() -1)).getAlias(); - LOGGER.info(KeyMigratorConstants.SESSIONID, KeyMigratorConstants.ZK_KEYS, - KeyMigratorConstants.EMPTY, "Found Alias to delete key. Alias: " + alias); - keyStore.deleteKey(alias); - dbHelper.storeKeyInAlias(KeyMigratorConstants.ZK_TEMP_KEY_APP_ID, localDateTimeStamp, KeyMigratorConstants.ZK_TEMP_KEY_REF_ID, - alias, localDateTimeStamp); - } else if (currentKeyAlias.size() == 1) { - LOGGER.info(KeyMigratorConstants.SESSIONID, KeyMigratorConstants.ZK_KEYS, - String.valueOf(currentKeyAlias.size()), "currentKeyAlias size is one, returning the certificate."); - String alias = currentKeyAlias.get(0).getAlias(); - String certificateData = keymanagerUtil.getPEMFormatedData(keyStore.getCertificate(alias)); - responseDto.setCertificate(certificateData); - responseDto.setTimestamp(localDateTimeStamp); - return responseDto; - } else if (currentKeyAlias.size() > 1) { - LOGGER.error(KeyMigratorConstants.SESSIONID, KeyMigratorConstants.ZK_KEYS, - String.valueOf(currentKeyAlias.size()), "No CurrentKeyAlias found Throwing exception"); - throw new NoUniqueAliasException(KeymanagerErrorConstant.NO_UNIQUE_ALIAS.getErrorCode(), - KeymanagerErrorConstant.NO_UNIQUE_ALIAS.getErrorMessage()); - } - - String alias = UUID.randomUUID().toString(); - LocalDateTime expiryDateTime = localDateTimeStamp.plusDays(1); - CertificateParameters certParams = keymanagerUtil.getCertificateParameters(KeyMigratorConstants.ZK_CERT_COMMON_NAME, - localDateTimeStamp, expiryDateTime); - keyStore.generateAndStoreAsymmetricKey(alias, null, certParams); - dbHelper.storeKeyInAlias(KeyMigratorConstants.ZK_TEMP_KEY_APP_ID, localDateTimeStamp, KeyMigratorConstants.ZK_TEMP_KEY_REF_ID, - alias, expiryDateTime); - - String certificateData = keymanagerUtil.getPEMFormatedData(keyStore.getCertificate(alias)); - responseDto.setCertificate(certificateData); - responseDto.setTimestamp(localDateTimeStamp); - return responseDto; - } - - @Override - public ZKKeyMigrateResponseDto migrateZKKeys(ZKKeyMigrateRequestDto migrateZKKeysRequestDto) { - LOGGER.info(KeyMigratorConstants.SESSIONID, KeyMigratorConstants.ZK_KEYS, - KeyMigratorConstants.EMPTY, "ZK keys migration request."); - - LocalDateTime localDateTimeStamp = DateUtils.getUTCCurrentDateTime(); - Stream encryptedKeyList = migrateZKKeysRequestDto.getZkEncryptedDataList().stream(); - boolean purgeKeyFlag = migrateZKKeysRequestDto.getPurgeTempKeyFlag() == null ? false: migrateZKKeysRequestDto.getPurgeTempKeyFlag(); - - LOGGER.info(KeyMigratorConstants.SESSIONID, KeyMigratorConstants.ZK_KEYS, - KeyMigratorConstants.EMPTY, "ZK migration keys list size: " + migrateZKKeysRequestDto.getZkEncryptedDataList().size()); - - String tempKeyAlias = getKeyAlias(KeyMigratorConstants.ZK_TEMP_KEY_APP_ID, KeyMigratorConstants.ZK_TEMP_KEY_REF_ID, localDateTimeStamp); - String zkMasterKeyAlias = getKeyAlias(masterKeyAppId, masterKeyRefId, localDateTimeStamp); - PrivateKeyEntry keyEntry= keyStore.getAsymmetricKey(tempKeyAlias); - PrivateKey tempPrivateKey = keyEntry.getPrivateKey(); - PublicKey tempPublicKey = keyEntry.getCertificate().getPublicKey(); - Key zkMasterKey = keyStore.getSymmetricKey(zkMasterKeyAlias); - - List keyResponseList = new ArrayList<>(); - encryptedKeyList.forEach(encryptedKey -> { - byte[] encryptedKeyBytes = CryptoUtil.decodeBase64(encryptedKey.getEncryptedKeyData()); - int keyIndex = encryptedKey.getKeyIndex(); - ZKKeyResponseDto keyResponseDto = new ZKKeyResponseDto(); - keyResponseDto.setKeyIndex(keyIndex); - if (!isKeyIndexExist(keyIndex)) { - - byte[] encryptedSessionKey = encryptRandomKey(encryptedKeyBytes, zkMasterKey, tempPrivateKey, tempPublicKey ); - if (encryptedSessionKey != null) { - String encodedKey = Base64.getEncoder().encodeToString(encryptedSessionKey); - insertKey(keyIndex, encodedKey, KeyMigratorConstants.ACTIVE_STATUS); - keyResponseDto.setStatusMessage(KeyMigratorConstants.MIGRAION_SUCCESS); - } else { - keyResponseDto.setStatusMessage(KeyMigratorConstants.MIGRAION_FAILED); - } - } else { - keyResponseDto.setStatusMessage(KeyMigratorConstants.MIGRAION_NOT_ALLOWED); - } - keyResponseList.add(keyResponseDto); - }); - LOGGER.info(KeyMigratorConstants.SESSIONID, KeyMigratorConstants.ZK_KEYS, - KeyMigratorConstants.EMPTY, "Purge Flag Value: " + purgeKeyFlag); - if (purgeKeyFlag) { - keyStore.deleteKey(tempKeyAlias); - LOGGER.info(KeyMigratorConstants.SESSIONID, KeyMigratorConstants.ZK_KEYS, - KeyMigratorConstants.EMPTY, "Key Purged from Store. Key Alias: " + tempKeyAlias); - dbHelper.storeKeyInAlias(KeyMigratorConstants.ZK_TEMP_KEY_APP_ID, localDateTimeStamp, KeyMigratorConstants.ZK_TEMP_KEY_REF_ID, - tempKeyAlias, localDateTimeStamp); - } - ZKKeyMigrateResponseDto responseDto = new ZKKeyMigrateResponseDto(); - responseDto.setZkEncryptedDataList(keyResponseList); - return responseDto; - } - - private String getKeyAlias(String keyAppId, String keyRefId, LocalDateTime localDateTimeStamp) { - LOGGER.info(KeyMigratorConstants.SESSIONID, KeyMigratorConstants.ZK_KEYS, - KeyMigratorConstants.EMPTY, "Retrieve Master Key Alias from DB. AppId: " + keyAppId); - - Map> keyAliasMap = dbHelper.getKeyAliases(keyAppId, keyRefId, localDateTimeStamp); - - List currentKeyAliases = keyAliasMap.get(KeymanagerConstant.CURRENTKEYALIAS); - - if (!currentKeyAliases.isEmpty() && currentKeyAliases.size() == 1) { - LOGGER.info(KeyMigratorConstants.SESSIONID, KeyMigratorConstants.ZK_KEYS, "getKeyAlias", - "CurrentKeyAlias size is one. return the current key alias."); - return currentKeyAliases.get(0).getAlias(); - } - - LOGGER.error(KeyMigratorConstants.SESSIONID, KeyMigratorConstants.ZK_KEYS, - KeyMigratorConstants.EMPTY, "CurrentKeyAlias is not unique. KeyAlias count: " + currentKeyAliases.size()); - throw new NoUniqueAliasException(KeymanagerErrorConstant.NO_UNIQUE_ALIAS.getErrorCode(), - KeymanagerErrorConstant.NO_UNIQUE_ALIAS.getErrorMessage()); - } - - private byte[] encryptRandomKey(byte[] encryptedKeyBytes, Key zkMasterKey, PrivateKey tempPrivateKey, PublicKey tempPublicKey) { - try { - byte[] secretDataBytes = cryptoCore.asymmetricDecrypt(tempPrivateKey, tempPublicKey, encryptedKeyBytes); - Cipher cipher = Cipher.getInstance(aesECBTransformation); - - cipher.init(Cipher.ENCRYPT_MODE, zkMasterKey); - return cipher.doFinal(secretDataBytes, 0, secretDataBytes.length); - } catch(NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException - | IllegalBlockSizeException | BadPaddingException | IllegalArgumentException - | InvalidDataException | io.mosip.kernel.core.crypto.exception.InvalidKeyException e) { - LOGGER.error(KeyMigratorConstants.SESSIONID, KeyMigratorConstants.ZK_KEYS, - KeyMigratorConstants.EMPTY, "Error in encrypting random Key in key migration process.", e); - } - return null; - } - - private boolean isKeyIndexExist(int keyIdx) { - return Objects.nonNull(dataEncryptKeystoreRepository.findKeyById(keyIdx)); - } - - private void insertKey(int id, String secretData, String status) { - DataEncryptKeystore data = new DataEncryptKeystore(); - data.setId(id); - data.setKey(secretData); - data.setKeyStatus(status); - data.setCrBy(CREATED_BY); - data.setCrDTimes(LocalDateTime.now()); - dataEncryptKeystoreRepository.save(data); - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/service/spi/KeyMigratorService.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/service/spi/KeyMigratorService.java deleted file mode 100644 index bdcba888c32..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymigrate/service/spi/KeyMigratorService.java +++ /dev/null @@ -1,41 +0,0 @@ -package io.mosip.kernel.keymigrate.service.spi; - -import io.mosip.kernel.keymigrate.dto.KeyMigrateBaseKeyRequestDto; -import io.mosip.kernel.keymigrate.dto.KeyMigrateBaseKeyResponseDto; -import io.mosip.kernel.keymigrate.dto.ZKKeyMigrateCertficateResponseDto; -import io.mosip.kernel.keymigrate.dto.ZKKeyMigrateRequestDto; -import io.mosip.kernel.keymigrate.dto.ZKKeyMigrateResponseDto; - -/** - * This interface provides the methods which can be used for Key Migration from source HSM to - * destination HSM. - * - * @author Mahammed Taheer - * @since 1.1.6 - */ -public interface KeyMigratorService { - - /** - * Key Migrate request with key data. - * - * @param keyMigrateRequest {@link KeyMigrateBaseKeyRequestDto} instance - * @return {@link KeyMigrateBaseKeyResponseDto} migrate status - */ - public KeyMigrateBaseKeyResponseDto migrateBaseKey(KeyMigrateBaseKeyRequestDto keyMigrateRequest); - - /** - * ZK Keys Migrate request for temporary certificate. - * - * - * @return {@link ZKKeyMigrateCertficateResponseDto} certificate response - */ - public ZKKeyMigrateCertficateResponseDto getZKTempCertificate(); - - /** - * ZK Keys Migrate request to migrate keys. - * - * @param migrateZKKeysRequestDto {@link ZKKeyMigrateRequestDto} instance - * @return {@link ZKKeyMigrateResponseDto} migrate status - */ - public ZKKeyMigrateResponseDto migrateZKKeys(ZKKeyMigrateRequestDto migrateZKKeysRequestDto); -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/constant/LicenseKeyManagerErrorCodes.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/constant/LicenseKeyManagerErrorCodes.java deleted file mode 100644 index a56b51fab9f..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/constant/LicenseKeyManagerErrorCodes.java +++ /dev/null @@ -1,35 +0,0 @@ -package io.mosip.kernel.lkeymanager.constant; - -/** - * ENUM to manage error codes of exceptions handled in the service. - * - * @author Sagar Mahapatra - * @since 1.0.0 - * - */ -public enum LicenseKeyManagerErrorCodes { - HTTP_MESSAGE_NOT_READABLE("KER-LKM-999"), RUNTIME_EXCEPTION("KER-LKM-500"); - - /** - * The error code. - */ - private String errorCode; - - /** - * Constructor with error code as the argument. - * - * @param errorCode the error code. - */ - private LicenseKeyManagerErrorCodes(String errorCode) { - this.errorCode = errorCode; - } - - /** - * Getter for error code. - * - * @return the error code. - */ - public String getErrorCode() { - return errorCode; - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/constant/LicenseKeyManagerExceptionConstants.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/constant/LicenseKeyManagerExceptionConstants.java deleted file mode 100644 index 2862d31498f..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/constant/LicenseKeyManagerExceptionConstants.java +++ /dev/null @@ -1,59 +0,0 @@ -package io.mosip.kernel.lkeymanager.constant; - -/** - * ENUM to manage constants of exceptions handled in the service. - * - * @author Sagar Mahapatra - * @since 1.0.0 - * - */ -public enum LicenseKeyManagerExceptionConstants { - ILLEGAL_TSP("KER-LKM-001", "TSP entered is null or empty."), - INVALID_GENERATED_LICENSEKEY("KER-LKM-002", "The length of license key generated was not of the specified length."), - NOT_ACCEPTABLE_PERMISSION("KER-LKM-003", "Permission value entered is not accepted."), - LICENSEKEY_NOT_FOUND("KER-LKM-004", "LicenseKey Not Found."), - LICENSEKEY_EXPIRED("KER-LKM-005", "LicenseKey Expired."), - ILLEGAL_LICENSE_KEY("KER-LKM-006", "License Key entered is null or empty."), - ILLEGAL_PERMISSION("KER-LKM-007", "Permission entered is an empty string."), - DATE_EXPIRED("KER-LKM-008", "Expiry DateTime should be ahead of current DateTime."), - NO_PERMISSIONS_MAPPED("KER-LKM-009", "No Permissions has been mapped to the entered TSP-LicenseKey Pair."); - - /** - * The error code. - */ - private final String errorCode; - - /** - * The error message. - */ - private final String errorMessage; - - /** - * Constructor with error code and error message as the arguments. - * - * @param errorCode the error code. - * @param errorMessage the error message. - */ - private LicenseKeyManagerExceptionConstants(String errorCode, String errorMessage) { - this.errorCode = errorCode; - this.errorMessage = errorMessage; - } - - /** - * Getter for error code. - * - * @return The error code. - */ - public String getErrorCode() { - return errorCode; - } - - /** - * Getter for error message. - * - * @return The error message. - */ - public String getErrorMessage() { - return errorMessage; - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/constant/LicenseKeyManagerPropertyConstants.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/constant/LicenseKeyManagerPropertyConstants.java deleted file mode 100644 index 08091016ac8..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/constant/LicenseKeyManagerPropertyConstants.java +++ /dev/null @@ -1,35 +0,0 @@ -package io.mosip.kernel.lkeymanager.constant; - -/** - * ENUM to manage constant values defined in the service. - * - * @author Sagar Mahapatra - * @since 1.0.0 - * - */ -public enum LicenseKeyManagerPropertyConstants { - TIME_ZONE("UTC"), DEFAULT_CREATED_BY("defaultadmin@mosip.io"), MAPPED_STATUS("Mapped License with the permissions"); - - /** - * The value. - */ - private String value; - - /** - * Constructor with value as the argument. - * - * @param value the value. - */ - private LicenseKeyManagerPropertyConstants(String value) { - this.value = value; - } - - /** - * Getter for value. - * - * @return the value. - */ - public String getValue() { - return this.value; - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/controller/LicenseKeyController.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/controller/LicenseKeyController.java deleted file mode 100644 index 9f957040eb4..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/controller/LicenseKeyController.java +++ /dev/null @@ -1,95 +0,0 @@ -package io.mosip.kernel.lkeymanager.controller; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -import io.mosip.kernel.core.http.RequestWrapper; -import io.mosip.kernel.core.http.ResponseFilter; -import io.mosip.kernel.core.http.ResponseWrapper; -import io.mosip.kernel.core.licensekeymanager.spi.LicenseKeyManagerService; -import io.mosip.kernel.lkeymanager.dto.LicenseKeyFetchResponseDto; -import io.mosip.kernel.lkeymanager.dto.LicenseKeyGenerationDto; -import io.mosip.kernel.lkeymanager.dto.LicenseKeyGenerationResponseDto; -import io.mosip.kernel.lkeymanager.dto.LicenseKeyMappingDto; -import io.mosip.kernel.lkeymanager.dto.LicenseKeyMappingResponseDto; - -/** - * Controller class that provides various methods for license key management - * such as to generate license key for a specified TSP ID, mapping several - * permissions to a generated license key, fetching the specified permissions - * for a license key. - * - * @author Sagar Mahapatra - * @since 1.0.0 - * - */ -@RestController -public class LicenseKeyController { - /** - * Autowired reference for {@link LicenseKeyManagerService}. - */ - @Autowired - LicenseKeyManagerService licenseKeyManagerService; - - /** - * This method will generate license key against a certain TSP ID. - * - * @param licenseKeyGenerationDto the LicenseKeyGenerationResponseDto request - * object wrapped in {@link RequestWrapper}. - * @return the response entity. - */ - @ResponseFilter - @PostMapping(value = "/license/generate") - public ResponseWrapper generateLicenseKey( - @RequestBody RequestWrapper licenseKeyGenerationDto) { - LicenseKeyGenerationResponseDto licenseKeyGenerationResponseDto = new LicenseKeyGenerationResponseDto(); - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - licenseKeyGenerationResponseDto - .setLicenseKey(licenseKeyManagerService.generateLicenseKey(licenseKeyGenerationDto.getRequest())); - responseWrapper.setResponse(licenseKeyGenerationResponseDto); - return responseWrapper; - } - - /** - * This method will map license key to several permissions. The permissions - * provided must be present in the master list. - * - * @param licenseKeyMappingDto the {@link LicenseKeyMappingDto}. - * @return the response entity. - */ - @ResponseFilter - @PostMapping(value = "/license/permission") - public ResponseWrapper mapLicenseKey( - @RequestBody RequestWrapper licenseKeyMappingDto) { - LicenseKeyMappingResponseDto licenseKeyMappingResponseDto = new LicenseKeyMappingResponseDto(); - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - licenseKeyMappingResponseDto - .setStatus(licenseKeyManagerService.mapLicenseKey(licenseKeyMappingDto.getRequest())); - responseWrapper.setResponse(licenseKeyMappingResponseDto); - return responseWrapper; - } - - /** - * This method will fetch the mapped permissions for a license key. - * - * @param tspId tsp id - * @param licenseKey the license key of which the permissions need to be - * fetched. - * @return the permissions fetched. - */ - @ResponseFilter - @GetMapping(value = "/license/permission") - public ResponseWrapper fetchLicenseKeyPermissions(@RequestParam("tspId") String tspId, - @RequestParam("licenseKey") String licenseKey) { - LicenseKeyFetchResponseDto licenseKeyFetchResponseDto = new LicenseKeyFetchResponseDto(); - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - licenseKeyFetchResponseDto - .setPermissions(licenseKeyManagerService.fetchLicenseKeyPermissions(tspId, licenseKey)); - responseWrapper.setResponse(licenseKeyFetchResponseDto); - return responseWrapper; - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/dto/LicenseKeyFetchResponseDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/dto/LicenseKeyFetchResponseDto.java deleted file mode 100644 index 3f95553e9fb..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/dto/LicenseKeyFetchResponseDto.java +++ /dev/null @@ -1,20 +0,0 @@ -package io.mosip.kernel.lkeymanager.dto; - -import java.util.List; - -import lombok.Data; - -/** - * DTO class for license key fetch response. - * - * @author Sagar Mahapatra - * @since 1.0.0 - * - */ -@Data -public class LicenseKeyFetchResponseDto { - /** - * List of mapped permissions. - */ - private List permissions; -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/dto/LicenseKeyGenerationDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/dto/LicenseKeyGenerationDto.java deleted file mode 100644 index 174ff5bbb69..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/dto/LicenseKeyGenerationDto.java +++ /dev/null @@ -1,27 +0,0 @@ -package io.mosip.kernel.lkeymanager.dto; - -import java.time.LocalDateTime; - -import com.fasterxml.jackson.annotation.JsonFormat; - -import lombok.Data; - -/** - * DTO class to provide input request for generation of license key. - * - * @author Sagar Mahapatra - * @since 1.0 - * - */ -@Data -public class LicenseKeyGenerationDto { - /** - * The TSP ID against which the license key is to be generated. - */ - private String tspId; - /** - * The time at which the license key will expire. - */ - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") - private LocalDateTime licenseExpiryTime; -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/dto/LicenseKeyGenerationResponseDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/dto/LicenseKeyGenerationResponseDto.java deleted file mode 100644 index c524897d615..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/dto/LicenseKeyGenerationResponseDto.java +++ /dev/null @@ -1,18 +0,0 @@ -package io.mosip.kernel.lkeymanager.dto; - -import lombok.Data; - -/** - * DTO class for license key generation response. - * - * @author Sagar Mahapatra - * @since 1.0.0 - * - */ -@Data -public class LicenseKeyGenerationResponseDto { - /** - * The license key. - */ - private String licenseKey; -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/dto/LicenseKeyMappingDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/dto/LicenseKeyMappingDto.java deleted file mode 100644 index 9303a65e053..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/dto/LicenseKeyMappingDto.java +++ /dev/null @@ -1,28 +0,0 @@ -package io.mosip.kernel.lkeymanager.dto; - -import java.util.List; - -import lombok.Data; - -/** - * DTO class to map license key to a set of permissions. - * - * @author Sagar Mahapatra - * @since 1.0.0 - * - */ -@Data -public class LicenseKeyMappingDto { - /** - * The TSP ID to which the set of permissions will be granted. - */ - private String tspId; - /** - * The License Key for that TSP ID. - */ - private String licenseKey; - /** - * The list of permissions to be given. - */ - private List permissions; -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/dto/LicenseKeyMappingResponseDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/dto/LicenseKeyMappingResponseDto.java deleted file mode 100644 index 61c9f9619f0..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/dto/LicenseKeyMappingResponseDto.java +++ /dev/null @@ -1,18 +0,0 @@ -package io.mosip.kernel.lkeymanager.dto; - -import lombok.Data; - -/** - * DTO class for licensekey-permission mapping response. - * - * @author Sagar Mahapatra - * @since 1.0.0 - * - */ -@Data -public class LicenseKeyMappingResponseDto { - /** - * The status of the licensekey-permission mapping. - */ - private String status; -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/entity/LicenseKeyList.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/entity/LicenseKeyList.java deleted file mode 100644 index 376111f2ff3..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/entity/LicenseKeyList.java +++ /dev/null @@ -1,91 +0,0 @@ -package io.mosip.kernel.lkeymanager.entity; - -import java.time.LocalDateTime; -import java.util.List; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.Id; -import javax.persistence.OneToMany; -import javax.persistence.OneToOne; -import javax.persistence.Table; - -import lombok.Data; - -/** - * Entity class to represent the license key list table. - * - * @author Sagar Mahapatra - * @since 1.0.0 - * - */ -@Data -@Entity -@Table(name = "licensekey_list") -public class LicenseKeyList { - /** - * The generated unique license key. - */ - @Id - @Column(name = "license_key", nullable = false, length = 255) - private String licenseKey; - /** - * The active state of license key. - */ - @Column(name = "is_active", nullable = false) - private boolean isActive; - /** - * The license key expires at. - */ - @Column(name = "expiry_dtime") - private LocalDateTime expiryDateTimes; - - /** - * The license key created at. - */ - @Column(name = "cr_dtimes") - private LocalDateTime createdAt; - /** - * The license key created by. - */ - @Column(name = "cr_by", nullable = false, length = 256) - private String createdBy; - /** - * The license key created at. - */ - @Column(name = "created_dtime") - private LocalDateTime createdDateTimes; - /** - * The license key updated by. - */ - @Column(name = "upd_by", length = 256) - private String updatedBy; - /** - * The license key updated at. - */ - @Column(name = "upd_dtimes") - private LocalDateTime updatedDateTimes; - /** - * The deletion state of license key. - */ - @Column(name = "is_deleted") - private boolean isDeleted; - /** - * The license key deleted at. - */ - @Column(name = "del_dtimes") - private LocalDateTime deletedDateTimes; - - /** - * LicenseKeyList-LicenseKeyPermission Mapping. - */ - @OneToMany(mappedBy = "licenseKeyListReference", fetch = FetchType.LAZY) - private List licenseKeyPermissions; - - /** - * LicenseKeyList-LicenseKeyTestMap Mapping. - */ - @OneToOne(mappedBy = "licenseKeyList", fetch = FetchType.LAZY) - private LicenseKeyTspMap licenseKeyTspMap; -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/entity/LicenseKeyPermission.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/entity/LicenseKeyPermission.java deleted file mode 100644 index f2e5e4610ec..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/entity/LicenseKeyPermission.java +++ /dev/null @@ -1,84 +0,0 @@ -package io.mosip.kernel.lkeymanager.entity; - -import java.time.LocalDateTime; - -import javax.persistence.AttributeOverride; -import javax.persistence.AttributeOverrides; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.Id; -import javax.persistence.IdClass; -import javax.persistence.JoinColumn; -import javax.persistence.JoinColumns; -import javax.persistence.ManyToOne; -import javax.persistence.Table; - -import io.mosip.kernel.lkeymanager.entity.id.LicenseKeyPermissionID; -import lombok.Data; - -/** - * Entity class for License key permissions. - * - * @author Sagar Mahapatra - * @since 1.0.0 - * - */ -@Data -@Entity -@IdClass(LicenseKeyPermissionID.class) -@Table(name = "licensekey_permission") -public class LicenseKeyPermission { - /** - * Composite Primary ID : License Key & Permission. - */ - @Id - @AttributeOverrides({ - @AttributeOverride(name = "license_key", column = @Column(name = "license_key", nullable = false, length = 255)), - @AttributeOverride(name = "permission", column = @Column(name = "permission", nullable = false, length = 512)) }) - private String lKey; - private String permission; - /** - * The active state of permission. - */ - @Column(name = "is_active", nullable = false) - private boolean isActive; - /** - * The permission created by. - */ - @Column(name = "cr_by", nullable = false, length = 256) - private String createdBy; - /** - * The permission created at. - */ - @Column(name = "cr_dtimes", nullable = false) - private LocalDateTime createdDateTimes; - /** - * The permission updated by. - */ - @Column(name = "upd_by", length = 256) - private String updatedBy; - /** - * The permission updated at. - */ - @Column(name = "upd_dtimes") - private LocalDateTime updatedDateTimes; - /** - * The deletion state of permission. - */ - @Column(name = "is_deleted") - private boolean isDeleted; - /** - * The permission deleted at. - */ - @Column(name = "del_dtimes") - private LocalDateTime deletedDateTimes; - - /** - * Many to One mapping. - */ - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumns({ - @JoinColumn(name = "license_key", referencedColumnName = "license_key", insertable = false, updatable = false), }) - private LicenseKeyList licenseKeyListReference; -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/entity/LicenseKeyTspMap.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/entity/LicenseKeyTspMap.java deleted file mode 100644 index c3a554ee647..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/entity/LicenseKeyTspMap.java +++ /dev/null @@ -1,82 +0,0 @@ -package io.mosip.kernel.lkeymanager.entity; - -import java.time.LocalDateTime; - -import javax.persistence.AttributeOverride; -import javax.persistence.AttributeOverrides; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.Id; -import javax.persistence.IdClass; -import javax.persistence.JoinColumn; -import javax.persistence.JoinColumns; -import javax.persistence.OneToOne; -import javax.persistence.Table; - -import io.mosip.kernel.lkeymanager.entity.id.LicenseKeyTspMapID; -import lombok.Data; - -/** - * Entity class for License key and TSP ID mapping. - * - * @author Sagar Mahapatra - * @since 1.0.0 - * - */ -@Data -@Entity -@IdClass(LicenseKeyTspMapID.class) -@Table(name = "tsp_licensekey_map") -public class LicenseKeyTspMap { - /** - * Attributes of the primary key : TSP ID, License Key. - */ - @Id - @AttributeOverrides({ - @AttributeOverride(name = "tsp_id", column = @Column(name = "tsp_id", nullable = false, length = 36)), - @AttributeOverride(name = "license_key", column = @Column(name = "license_key", nullable = false, length = 255)) }) - private String tspId; - private String lKey; - /** - * The active state of licensekey-tsp mapping. - */ - @Column(name = "is_active", nullable = false) - private boolean isActive; - /** - * The map created by. - */ - @Column(name = "cr_by", nullable = false, length = 256) - private String createdBy; - /** - * The map created at. - */ - @Column(name = "cr_dtimes", nullable = false) - private LocalDateTime createdDateTimes; - /** - * The map updated by. - */ - @Column(name = "upd_by", length = 256) - private String updatedBy; - /** - * The map updated at. - */ - @Column(name = "upd_dtimes") - private LocalDateTime updatedDTimes; - /** - * The deletion state of map. - */ - @Column(name = "is_deleted") - private boolean isDeleted; - /** - * The deletion time of map. - */ - @Column(name = "del_dtimes") - private LocalDateTime deletedDateTimes; - /** - * One To One mapping. - */ - @OneToOne(fetch = FetchType.LAZY) - @JoinColumns({ @JoinColumn(name = "license_key", insertable = false, updatable = false) }) - private LicenseKeyList licenseKeyList; -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/entity/id/LicenseKeyPermissionID.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/entity/id/LicenseKeyPermissionID.java deleted file mode 100644 index 58b0f1de6e1..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/entity/id/LicenseKeyPermissionID.java +++ /dev/null @@ -1,35 +0,0 @@ -package io.mosip.kernel.lkeymanager.entity.id; - -import java.io.Serializable; - -import javax.persistence.Column; -import javax.persistence.Embeddable; - -import io.mosip.kernel.lkeymanager.entity.LicenseKeyPermission; -import lombok.Data; - -/** - * ID class for {@link LicenseKeyPermission}. - * - * @author Sagar Mahapatra - * @since 1.0.0 - * - */ -@Embeddable -@Data -public class LicenseKeyPermissionID implements Serializable { - /** - * Serializable version ID. - */ - private static final long serialVersionUID = -2416988903449810629L; - /** - * The License key. - */ - @Column(name = "license_key", nullable = false, length = 255) - private String lKey; - /** - * The permission for the license key. - */ - @Column(name = "permission", nullable = false, length = 255) - private String permission; -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/entity/id/LicenseKeyTspMapID.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/entity/id/LicenseKeyTspMapID.java deleted file mode 100644 index cda67ae7e30..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/entity/id/LicenseKeyTspMapID.java +++ /dev/null @@ -1,35 +0,0 @@ -package io.mosip.kernel.lkeymanager.entity.id; - -import java.io.Serializable; - -import javax.persistence.Column; -import javax.persistence.Embeddable; - -import io.mosip.kernel.lkeymanager.entity.LicenseKeyTspMap; -import lombok.Data; - -/** - * ID class for {@link LicenseKeyTspMap}. - * - * @author Sagar Mahapatra - * @since 1.0.0 - * - */ -@Embeddable -@Data -public class LicenseKeyTspMapID implements Serializable { - /** - * Serializable version ID. - */ - private static final long serialVersionUID = 3013351043966901511L; - /** - * The TSP ID. - */ - @Column(name = "tsp_id", length = 36, nullable = false) - private String tspId; - /** - * The License key. - */ - @Column(name = "license_key", length = 255, nullable = false) - private String lKey; -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/exception/InvalidArgumentsException.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/exception/InvalidArgumentsException.java deleted file mode 100644 index 1b7c755d4da..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/exception/InvalidArgumentsException.java +++ /dev/null @@ -1,43 +0,0 @@ -package io.mosip.kernel.lkeymanager.exception; - -import java.util.List; - -import io.mosip.kernel.core.exception.BaseUncheckedException; -import io.mosip.kernel.core.exception.ServiceError; - -/** - * Class to handle invalid arguments exception. - * - * @author Sagar Mahapatra - * @since 1.0.0 - * - */ -public class InvalidArgumentsException extends BaseUncheckedException { - /** - * Serializable version ID.. - */ - private static final long serialVersionUID = -7670097659608957076L; - - /** - * The error list. - */ - private final List list; - - /** - * Constructor with list as the argument. - * - * @param list the error list. - */ - public InvalidArgumentsException(List list) { - this.list = list; - } - - /** - * Getter for error list. - * - * @return The error list. - */ - public List getList() { - return list; - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/exception/LicenseKeyServiceException.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/exception/LicenseKeyServiceException.java deleted file mode 100644 index b1d8c8a37eb..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/exception/LicenseKeyServiceException.java +++ /dev/null @@ -1,39 +0,0 @@ -package io.mosip.kernel.lkeymanager.exception; - -import java.util.List; - -import io.mosip.kernel.core.exception.BaseUncheckedException; -import io.mosip.kernel.core.exception.ServiceError; - -/** - * Exception class for License Key Manager service. - * - * @author Sagar Mahapatra - * @since 1.0.0 - * - */ -public class LicenseKeyServiceException extends BaseUncheckedException { - - /** - * Serializable version ID. - */ - private static final long serialVersionUID = 2506481216920647423L; - - private final List list; - - /** - * @param list The error list. - */ - public LicenseKeyServiceException(List list) { - this.list = list; - } - - /** - * Getter for error list. - * - * @return The error list. - */ - public List getList() { - return list; - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/repository/LicenseKeyListRepository.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/repository/LicenseKeyListRepository.java deleted file mode 100644 index 2177dcce85a..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/repository/LicenseKeyListRepository.java +++ /dev/null @@ -1,24 +0,0 @@ -package io.mosip.kernel.lkeymanager.repository; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import io.mosip.kernel.lkeymanager.entity.LicenseKeyList; - -/** - * Repository class for {@link LicenseKeyList}. - * - * @author Sagar Mahapatra - * @since 1.0.0 - * - */ -@Repository -public interface LicenseKeyListRepository extends JpaRepository { - /** - * Method to extract licensekey list details by license key. - * - * @param licenseKey the license key. - * @return the entity response. - */ - public LicenseKeyList findByLicenseKey(String licenseKey); -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/repository/LicenseKeyPermissionRepository.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/repository/LicenseKeyPermissionRepository.java deleted file mode 100644 index 68a31b96482..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/repository/LicenseKeyPermissionRepository.java +++ /dev/null @@ -1,44 +0,0 @@ -package io.mosip.kernel.lkeymanager.repository; - -import java.time.LocalDateTime; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Modifying; -import org.springframework.data.jpa.repository.Query; -import org.springframework.stereotype.Repository; -import org.springframework.transaction.annotation.Transactional; - -import io.mosip.kernel.lkeymanager.entity.LicenseKeyPermission; -import io.mosip.kernel.lkeymanager.entity.id.LicenseKeyPermissionID; - -/** - * Repository class for {@link LicenseKeyPermission}. - * - * @author Sagar Mahapatra - * @since 1.0.0 - * - */ -@Repository -public interface LicenseKeyPermissionRepository extends JpaRepository { - /** - * Method to find license key permissions by license key. - * - * @param licenseKey the license key for which permission needs to be fetched. - * @return the license key entity. - */ - public LicenseKeyPermission findByLKey(String licenseKey); - - /** - * Method to update license key permissions. - * - * @param updatedPermissionString the updated permission list. - * @param licenseKey the license key. - * @param updationTime the time at which the list is updated. - * @param updatedBy the list updated by. - * @return the permission entity response. - */ - @Modifying - @Query("UPDATE LicenseKeyPermission p SET p.permission =?1, p.updatedDateTimes =?3, p.updatedBy=?4 WHERE p.lKey =?2") - public int updatePermissionList(String updatedPermissionString, String licenseKey, LocalDateTime updationTime, - String updatedBy); -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/repository/LicenseKeyTspMapRepository.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/repository/LicenseKeyTspMapRepository.java deleted file mode 100644 index 9143d5ee85e..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/repository/LicenseKeyTspMapRepository.java +++ /dev/null @@ -1,27 +0,0 @@ -package io.mosip.kernel.lkeymanager.repository; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; -import org.springframework.transaction.annotation.Transactional; - -import io.mosip.kernel.lkeymanager.entity.LicenseKeyTspMap; -import io.mosip.kernel.lkeymanager.entity.id.LicenseKeyTspMapID; - -/** - * Repository class for {@link LicenseKeyTspMap}. - * - * @author Sagar Mahapatra - * @since 1.0.0 - * - */ -@Repository -public interface LicenseKeyTspMapRepository extends JpaRepository { - /** - * Method to extract LicenseKeyTspMap entity based on license key and TSP ID. - * - * @param licenseKey the license key. - * @param tspID the TSP ID. - * @return the entity response. - */ - public LicenseKeyTspMap findByLKeyAndTspId(String licenseKey, String tspID); -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/service/impl/LicenseKeyManagerServiceImpl.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/service/impl/LicenseKeyManagerServiceImpl.java deleted file mode 100644 index 4bfc0e47e40..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/service/impl/LicenseKeyManagerServiceImpl.java +++ /dev/null @@ -1,185 +0,0 @@ -package io.mosip.kernel.lkeymanager.service.impl; - -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import io.mosip.kernel.core.exception.ServiceError; -import io.mosip.kernel.core.licensekeymanager.spi.LicenseKeyManagerService; -import io.mosip.kernel.lkeymanager.constant.LicenseKeyManagerExceptionConstants; -import io.mosip.kernel.lkeymanager.constant.LicenseKeyManagerPropertyConstants; -import io.mosip.kernel.lkeymanager.dto.LicenseKeyGenerationDto; -import io.mosip.kernel.lkeymanager.dto.LicenseKeyMappingDto; -import io.mosip.kernel.lkeymanager.entity.LicenseKeyList; -import io.mosip.kernel.lkeymanager.entity.LicenseKeyPermission; -import io.mosip.kernel.lkeymanager.entity.LicenseKeyTspMap; -import io.mosip.kernel.lkeymanager.exception.InvalidArgumentsException; -import io.mosip.kernel.lkeymanager.exception.LicenseKeyServiceException; -import io.mosip.kernel.lkeymanager.repository.LicenseKeyListRepository; -import io.mosip.kernel.lkeymanager.repository.LicenseKeyPermissionRepository; -import io.mosip.kernel.lkeymanager.repository.LicenseKeyTspMapRepository; -import io.mosip.kernel.lkeymanager.util.LicenseKeyManagerUtil; - -/** - * Implementation class for {@link LicenseKeyManagerService}. - * - * @author Sagar Mahapatra - * @since 1.0.0 - * - */ -@Service -@Transactional -public class LicenseKeyManagerServiceImpl - implements LicenseKeyManagerService { - /** - * Autowired reference for {@link LicenseKeyManagerUtil}. - */ - @Autowired - LicenseKeyManagerUtil licenseKeyManagerUtil; - /** - * Autowired reference for {@link LicenseKeyListRepository} - */ - @Autowired - LicenseKeyListRepository licenseKeyListRepository; - - /** - * Autowired reference for {@link LicenseKeyPermissionRepository}. - */ - @Autowired - LicenseKeyPermissionRepository licenseKeyPermissionsRepository; - - /** - * Autowired reference for {@link LicenseKeyTspMapRepository}. - */ - @Autowired - LicenseKeyTspMapRepository licenseKeyTspMapRepository; - - /* - * (non-Javadoc) - * - * @see io.mosip.kernel.core.licensekeymanager.spi.LicenseKeyManagerService# - * generateLicenseKey(java.lang.Object) - */ - @Override - public String generateLicenseKey(LicenseKeyGenerationDto licenseKeyGenerationDto) { - - licenseKeyManagerUtil.validateTSP(licenseKeyGenerationDto.getTspId()); - - if (licenseKeyGenerationDto.getLicenseExpiryTime().isBefore(LocalDateTime.now(ZoneId.of("UTC")))) { - List errorList = new ArrayList<>(); - errorList.add(new ServiceError(LicenseKeyManagerExceptionConstants.DATE_EXPIRED.getErrorCode(), - LicenseKeyManagerExceptionConstants.DATE_EXPIRED.getErrorMessage())); - throw new InvalidArgumentsException(errorList); - } - - String generatedLicense = licenseKeyManagerUtil.generateLicense(); - - LicenseKeyList licenseKeyListEntity = new LicenseKeyList(); - LicenseKeyTspMap licenseKeyTspMapEntity = new LicenseKeyTspMap(); - - licenseKeyListEntity.setLicenseKey(generatedLicense); - licenseKeyListEntity.setActive(true); - licenseKeyListEntity.setCreatedAt(licenseKeyManagerUtil.getCurrentTimeInUTCTimeZone()); - licenseKeyListEntity.setExpiryDateTimes(licenseKeyGenerationDto.getLicenseExpiryTime()); - licenseKeyListEntity.setCreatedBy(LicenseKeyManagerPropertyConstants.DEFAULT_CREATED_BY.getValue()); - licenseKeyListEntity.setCreatedDateTimes(licenseKeyManagerUtil.getCurrentTimeInUTCTimeZone()); - - licenseKeyTspMapEntity.setTspId(licenseKeyGenerationDto.getTspId()); - licenseKeyTspMapEntity.setLKey(generatedLicense); - licenseKeyTspMapEntity.setActive(true); - licenseKeyTspMapEntity.setCreatedDateTimes(licenseKeyManagerUtil.getCurrentTimeInUTCTimeZone()); - licenseKeyTspMapEntity.setCreatedBy("SYSTEM"); - - licenseKeyListRepository.saveAndFlush(licenseKeyListEntity); - licenseKeyTspMapRepository.saveAndFlush(licenseKeyTspMapEntity); - - return generatedLicense; - } - - /* - * (non-Javadoc) - * - * @see io.mosip.kernel.core.licensekeymanager.spi.LicenseKeyManagerService# - * mapLicenseKey(java.lang.Object) - */ - @Transactional - @Override - public String mapLicenseKey(LicenseKeyMappingDto licenseKeyMappingDto) { - licenseKeyManagerUtil.validateRequestParameters(licenseKeyMappingDto.getTspId(), - licenseKeyMappingDto.getLicenseKey(), licenseKeyMappingDto.getPermissions()); - if (licenseKeyTspMapRepository.findByLKeyAndTspId(licenseKeyMappingDto.getLicenseKey(), - licenseKeyMappingDto.getTspId()) == null) { - List errorList = new ArrayList<>(); - errorList.add(new ServiceError(LicenseKeyManagerExceptionConstants.LICENSEKEY_NOT_FOUND.getErrorCode(), - LicenseKeyManagerExceptionConstants.LICENSEKEY_NOT_FOUND.getErrorMessage())); - throw new LicenseKeyServiceException(errorList); - } - - licenseKeyManagerUtil.areValidPermissions(licenseKeyMappingDto.getPermissions()); - - LicenseKeyPermission licenseKeyPermissionEntity = new LicenseKeyPermission(); - licenseKeyPermissionEntity.setLKey(licenseKeyMappingDto.getLicenseKey()); - licenseKeyPermissionEntity.setActive(true); - licenseKeyPermissionEntity.setCreatedDateTimes(licenseKeyManagerUtil.getCurrentTimeInUTCTimeZone()); - licenseKeyPermissionEntity.setCreatedBy(LicenseKeyManagerPropertyConstants.DEFAULT_CREATED_BY.getValue()); - - LicenseKeyPermission licenseKeyPermission = licenseKeyPermissionsRepository - .findByLKey(licenseKeyMappingDto.getLicenseKey()); - - if (licenseKeyPermission == null) { - licenseKeyPermissionEntity.setPermission( - licenseKeyManagerUtil.concatPermissionsIntoASingleRow(licenseKeyMappingDto.getPermissions())); - licenseKeyPermissionsRepository.saveAndFlush(licenseKeyPermissionEntity); - } else { - licenseKeyMappingDto.getPermissions().add(licenseKeyPermission.getPermission()); - licenseKeyPermissionEntity.setPermission( - licenseKeyManagerUtil.concatPermissionsIntoASingleRow(licenseKeyMappingDto.getPermissions())); - licenseKeyPermissionsRepository.updatePermissionList( - licenseKeyManagerUtil.concatPermissionsIntoASingleRow(licenseKeyMappingDto.getPermissions()), - licenseKeyMappingDto.getLicenseKey(), licenseKeyManagerUtil.getCurrentTimeInUTCTimeZone(), - LicenseKeyManagerPropertyConstants.DEFAULT_CREATED_BY.getValue()); - } - - return LicenseKeyManagerPropertyConstants.MAPPED_STATUS.getValue(); - } - - /* - * (non-Javadoc) - * - * @see io.mosip.kernel.core.licensekeymanager.spi.LicenseKeyManagerService# - * fetchLicenseKeyPermissions(java.lang.Object, java.lang.Object) - */ - @Override - public List fetchLicenseKeyPermissions(String tspID, String licenseKey) { - licenseKeyManagerUtil.validateTSPAndLicenseKey(tspID, licenseKey); - if (licenseKeyTspMapRepository.findByLKeyAndTspId(licenseKey, tspID) == null) { - List errorList = new ArrayList<>(); - errorList.add(new ServiceError(LicenseKeyManagerExceptionConstants.LICENSEKEY_NOT_FOUND.getErrorCode(), - LicenseKeyManagerExceptionConstants.LICENSEKEY_NOT_FOUND.getErrorMessage())); - throw new LicenseKeyServiceException(errorList); - } - if (licenseKeyManagerUtil.getCurrentTimeInUTCTimeZone() - .isAfter(licenseKeyListRepository.findByLicenseKey(licenseKey).getExpiryDateTimes())) { - List errorList = new ArrayList<>(); - errorList.add(new ServiceError(LicenseKeyManagerExceptionConstants.LICENSEKEY_EXPIRED.getErrorCode(), - LicenseKeyManagerExceptionConstants.LICENSEKEY_EXPIRED.getErrorMessage())); - throw new LicenseKeyServiceException(errorList); - - } - LicenseKeyPermission licenseKeyPermissions = licenseKeyPermissionsRepository.findByLKey(licenseKey); - if (licenseKeyPermissions == null) { - List errorList = new ArrayList<>(); - errorList.add(new ServiceError(LicenseKeyManagerExceptionConstants.NO_PERMISSIONS_MAPPED.getErrorCode(), - LicenseKeyManagerExceptionConstants.NO_PERMISSIONS_MAPPED.getErrorMessage())); - throw new LicenseKeyServiceException(errorList); - } - return Arrays.asList(licenseKeyPermissions.getPermission().split(",")); - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/util/LicenseKeyManagerUtil.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/util/LicenseKeyManagerUtil.java deleted file mode 100644 index cfef449be44..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/lkeymanager/util/LicenseKeyManagerUtil.java +++ /dev/null @@ -1,170 +0,0 @@ -package io.mosip.kernel.lkeymanager.util; - -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.lang3.RandomStringUtils; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.cloud.context.config.annotation.RefreshScope; -import org.springframework.stereotype.Component; - -import io.mosip.kernel.core.exception.ServiceError; -import io.mosip.kernel.lkeymanager.constant.LicenseKeyManagerExceptionConstants; -import io.mosip.kernel.lkeymanager.constant.LicenseKeyManagerPropertyConstants; -import io.mosip.kernel.lkeymanager.exception.InvalidArgumentsException; -import io.mosip.kernel.lkeymanager.exception.LicenseKeyServiceException; - -/** - * This class provides several utility methods to be used in license key manager - * service. - * - * @author Sagar Mahapatra - * @since 1.0.0 - * - */ -@RefreshScope -@Component -public class LicenseKeyManagerUtil { - /** - * The list of specified permissions by ADMIN. - */ - @Value("#{'${mosip.kernel.licensekey.permissions}'.split(',')}") - private List validPermissions; - - /** - * The length of license key as specified by ADMIN. - */ - @Value("${mosip.kernel.licensekey.length}") - private int licenseKeyLength; - - /** - * This method adds all the permissions into a single row separated by comma. - * - * @param permissionsList the list of permissions. - * @return the resultant string. - */ - public String concatPermissionsIntoASingleRow(List permissionsList) { - StringBuilder permissionString = new StringBuilder(); - int permissionsListCount = 0; - for (String permission : permissionsList) { - if (++permissionsListCount <= permissionsList.size() - 1) { - permissionString.append(permission + ","); - } else { - permissionString.append(permission); - } - } - return permissionString.toString(); - } - - /** - * This method validates whether the input permissions are from the master list - * or not. - * - * @param inputPermissions the list of input permissions. - * @return true if all the input permissions are valid. - */ - public boolean areValidPermissions(List inputPermissions) { - List errorList = new ArrayList<>(); - if (!(inputPermissions.stream() - .allMatch(permission -> validPermissions.stream().anyMatch(permission::contains)))) { - errorList.add(new ServiceError(LicenseKeyManagerExceptionConstants.NOT_ACCEPTABLE_PERMISSION.getErrorCode(), - LicenseKeyManagerExceptionConstants.NOT_ACCEPTABLE_PERMISSION.getErrorMessage())); - throw new LicenseKeyServiceException(errorList); - } - return true; - } - - /** - * Method that returns the current date-time in UTC time zone. - * - * @return the local date time as specified. - */ - public LocalDateTime getCurrentTimeInUTCTimeZone() { - return LocalDateTime.now(ZoneId.of(LicenseKeyManagerPropertyConstants.TIME_ZONE.getValue())); - } - - /** - * Method that generates a random license key of specified length. - * - * @return the generated license key. - */ - public String generateLicense() { - List errorList = new ArrayList<>(); - String licenseKey = RandomStringUtils.randomAlphanumeric(licenseKeyLength); - if (licenseKey.length() != licenseKeyLength) { - errorList.add( - new ServiceError(LicenseKeyManagerExceptionConstants.INVALID_GENERATED_LICENSEKEY.getErrorCode(), - LicenseKeyManagerExceptionConstants.INVALID_GENERATED_LICENSEKEY.getErrorMessage())); - throw new LicenseKeyServiceException(errorList); - } - return licenseKey; - } - - /** - * Method to validate TSP ID. - * - * @param tspID the TSP ID to be validated. - */ - public void validateTSP(String tspID) { - List errorList = new ArrayList<>(); - if (tspID == null || tspID.trim().isEmpty()) { - errorList.add(new ServiceError(LicenseKeyManagerExceptionConstants.ILLEGAL_TSP.getErrorCode(), - LicenseKeyManagerExceptionConstants.ILLEGAL_TSP.getErrorMessage())); - } - if (!errorList.isEmpty()) { - throw new InvalidArgumentsException(errorList); - } - } - - /** - * Method to validate TSP ID and License Key. - * - * @param tspID the TSP ID to be validated. - * @param licenseKey the license key to be validated. - */ - public void validateTSPAndLicenseKey(String tspID, String licenseKey) { - List errorList = new ArrayList<>(); - if (tspID == null || tspID.trim().isEmpty()) { - errorList.add(new ServiceError(LicenseKeyManagerExceptionConstants.ILLEGAL_TSP.getErrorCode(), - LicenseKeyManagerExceptionConstants.ILLEGAL_TSP.getErrorMessage())); - } - if (licenseKey == null || licenseKey.trim().isEmpty()) { - errorList.add(new ServiceError(LicenseKeyManagerExceptionConstants.ILLEGAL_LICENSE_KEY.getErrorCode(), - LicenseKeyManagerExceptionConstants.ILLEGAL_LICENSE_KEY.getErrorMessage())); - } - if (!errorList.isEmpty()) { - throw new InvalidArgumentsException(errorList); - } - } - - /** - * Method to validate TSP ID, License Key, and the list of permissions. - * - * @param tspID the TSP ID. - * @param licenseKey the license Key. - * @param permissions the list of permissions. - */ - public void validateRequestParameters(String tspID, String licenseKey, List permissions) { - List errorList = new ArrayList<>(); - if (tspID == null || tspID.trim().isEmpty()) { - errorList.add(new ServiceError(LicenseKeyManagerExceptionConstants.ILLEGAL_TSP.getErrorCode(), - LicenseKeyManagerExceptionConstants.ILLEGAL_TSP.getErrorMessage())); - } - if (licenseKey == null || licenseKey.trim().isEmpty()) { - errorList.add(new ServiceError(LicenseKeyManagerExceptionConstants.ILLEGAL_LICENSE_KEY.getErrorCode(), - LicenseKeyManagerExceptionConstants.ILLEGAL_LICENSE_KEY.getErrorMessage())); - } - for (String permission : permissions) { - if (permission.trim().isEmpty()) { - errorList.add(new ServiceError(LicenseKeyManagerExceptionConstants.ILLEGAL_PERMISSION.getErrorCode(), - LicenseKeyManagerExceptionConstants.ILLEGAL_PERMISSION.getErrorMessage())); - break; - } - } - if (!errorList.isEmpty()) { - throw new InvalidArgumentsException(errorList); - } - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/constant/PartnerCertManagerConstants.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/constant/PartnerCertManagerConstants.java deleted file mode 100644 index 9b4c49c33b8..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/constant/PartnerCertManagerConstants.java +++ /dev/null @@ -1,99 +0,0 @@ -package io.mosip.kernel.partnercertservice.constant; - -/** - * Constants for Partner Certificate Manager - * - * @author Mahammed Taheer - * @since 1.1.2 - * - */ - -public interface PartnerCertManagerConstants { - - /** - * The constant Session Id. - */ - String SESSIONID = "pcSessionId"; - - /** - * The constant EMPTY - */ - String EMPTY = ""; - - /** - * The constant EQUALS - */ - String EQUALS = "="; - - /** - * The constant COMMA - */ - String COMMA = ","; - - /** - * The constant UPLOAD_CA_CERT - */ - String UPLOAD_CA_CERT = "UploadCACertificate"; - - /** - * The constant PCM_UTIL - */ - String PCM_UTIL = "pcmUtil"; - - /** - * The constant TRUST_ROOT - */ - String TRUST_ROOT = "TrustRoot"; - - /** - * The constant TRUST_INTER - */ - String TRUST_INTER = "TrustInter"; - - /** - * The constant SUCCESS_UPLOAD - */ - String SUCCESS_UPLOAD = "Upload Success."; - - /** - * The constant PARTIAL_SUCCESS_UPLOAD - */ - String PARTIAL_SUCCESS_UPLOAD = "Partial Upload Success."; - - /** - * The constant UPLOAD_FAILED - */ - String UPLOAD_FAILED = "Upload Failed."; - - /** - * The constant UPLOAD_PARTNER_CERT - */ - String UPLOAD_PARTNER_CERT = "UploadPartnerCertificate"; - - /** - * The constant RSA_ALGORITHM - */ - String RSA_ALGORITHM = "RSA"; - - /** - * The constant RSA_MIN_KEY_SIZE - */ - int RSA_MIN_KEY_SIZE = 2048; - - /** - * The constant HASH_SHA2 - */ - String HASH_SHA2 = "SHA2"; - - int YEAR_DAYS = 365; - - String GET_PARTNER_CERT = "GetPartnerCertificate"; - - String CERT_TRUST_VALIDATION = "CertTrustPathValidation"; - - String FTM_PARTNER_DOMAIN = "FTM"; - - String ROOT_APP_ID = "ROOT"; - - String AUTH_DOMAIN = "AUTH"; -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/constant/PartnerCertManagerErrorConstants.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/constant/PartnerCertManagerErrorConstants.java deleted file mode 100644 index 6ca18fb525d..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/constant/PartnerCertManagerErrorConstants.java +++ /dev/null @@ -1,75 +0,0 @@ -package io.mosip.kernel.partnercertservice.constant; - -/** - * This ENUM provides all the constant identified for PartnerCertManager errors. - * - * @author Mahammed Taheer - * @version 1.2.0-SNAPSHOT - * - */ -public enum PartnerCertManagerErrorConstants { - - INVALID_CERTIFICATE("KER-PCM-001", "Invalid Certificate uploaded."), - - CERTIFICATE_THUMBPRINT_ERROR("KER-PCM-002", "Error in generating Certificate Thumbprint."), - - CERTIFICATE_EXIST_ERROR("KER-PCM-003", "Certificate already exists in store."), - - CERTIFICATE_DATES_NOT_VALID("KER-PCM-004", "Certificate Dates are not valid."), - - ROOT_CA_NOT_FOUND("KER-PCM-005", "Root CA Certificate not found."), - - ROOT_INTER_CA_NOT_FOUND("KER-PCM-006", "Root CA/Intermediate CA Certificates not found."), - - INVALID_CERT_VERSION("KER-PCM-007", "Certificate version not supported."), - - PARTNER_ORG_NOT_MATCH("KER-PCM-008", "Partner Organization Name not Matched."), - - NO_UNIQUE_ALIAS("KER-PCM-009", "No Unique Alias found."), - - INVALID_CERTIFICATE_ID("KER-PCM-010", "Invalid Partner Certificate ID."), - - INVALID_PARTNER_DOMAIN("KER-PCM-011", "Invalid Partner Domain."), - - PARTNER_CERT_ID_NOT_FOUND("KER-PCM-012", "Partner Certificate not found for the given ID."), - - CERT_KEY_NOT_ALLOWED("KER-PCM-013", "Partner Certificate Key Size is less than allowed size."), - - CERT_SIGNATURE_ALGO_NOT_ALLOWED("KER-PCM-014", "Partner Certificate Signature algorithm not supported."), - - SELF_SIGNED_CERT_NOT_ALLOWED("KER-PCM-015", "Self Signed Certificate not allowed as partner."), - ; - - /** - * The error code. - */ - private final String errorCode; - - /** - * The error message. - */ - private final String errorMessage; - - /** - * @param errorCode The error code to be set. - * @param errorMessage The error message to be set. - */ - private PartnerCertManagerErrorConstants(String errorCode, String errorMessage) { - this.errorCode = errorCode; - this.errorMessage = errorMessage; - } - - /** - * @return The error code. - */ - public String getErrorCode() { - return errorCode; - } - - /** - * @return The error message. - */ - public String getErrorMessage() { - return errorMessage; - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/controller/PartnerCertManagerController.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/controller/PartnerCertManagerController.java deleted file mode 100644 index 5bda9165444..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/controller/PartnerCertManagerController.java +++ /dev/null @@ -1,125 +0,0 @@ -package io.mosip.kernel.partnercertservice.controller; - -import javax.validation.Valid; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.CrossOrigin; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RestController; - -import io.mosip.kernel.core.http.RequestWrapper; -import io.mosip.kernel.core.http.ResponseFilter; -import io.mosip.kernel.core.http.ResponseWrapper; -import io.mosip.kernel.partnercertservice.dto.CACertificateRequestDto; -import io.mosip.kernel.partnercertservice.dto.CACertificateResponseDto; -import io.mosip.kernel.partnercertservice.dto.CertificateTrustRequestDto; -import io.mosip.kernel.partnercertservice.dto.CertificateTrustResponeDto; -import io.mosip.kernel.partnercertservice.dto.PartnerCertDownloadRequestDto; -import io.mosip.kernel.partnercertservice.dto.PartnerCertDownloadResponeDto; -import io.mosip.kernel.partnercertservice.dto.PartnerCertificateRequestDto; -import io.mosip.kernel.partnercertservice.dto.PartnerCertificateResponseDto; -import io.mosip.kernel.partnercertservice.service.spi.PartnerCertificateManagerService; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiParam; - -/** - * Rest Controller for Partner Certificate Management includes certificate Validation and certificate Storage. - * - * @author Mahammed Taheer - * - * @since 1.1.2 - */ - -@CrossOrigin -@RestController -@Api(value = "Operation related to partner certificate management.", tags = { "partnercertmanager" }) -public class PartnerCertManagerController { - - /** - * Instance for PartnerCertificateManagerService - */ - @Autowired - PartnerCertificateManagerService partnerCertManagerService; - - /** - * To Upload CA/Sub-CA certificates - * - * @param caCertRequestDto {@link CACertificateRequestDto} request - * @return {@link CACertficateResponseDto} Upload Success - */ - // @PreAuthorize("hasAnyRole('ZONAL_ADMIN','GLOBAL_ADMIN','INDIVIDUAL', - // 'PMS_ADMIN')") - @PreAuthorize("hasAnyRole('ZONAL_ADMIN','GLOBAL_ADMIN','PMS_ADMIN')") - @ResponseFilter - @PostMapping(value = "/uploadCACertificate", produces = "application/json") - public ResponseWrapper uploadCACertificate( - @ApiParam("Upload CA/Sub-CA certificates.") @RequestBody @Valid RequestWrapper caCertRequestDto) { - - ResponseWrapper response = new ResponseWrapper<>(); - response.setResponse(partnerCertManagerService.uploadCACertificate(caCertRequestDto.getRequest())); - return response; - } - - /** - * To Upload Partner Certificate. - * - * @param partnerCertRequestDto {@link PartnerCertificateRequestDto} request - * @return {@link PartnerCertificateResponseDto} signed certificate response - */ - // @PreAuthorize("hasAnyRole('ZONAL_ADMIN','GLOBAL_ADMIN','INDIVIDUAL', - // 'ID_AUTHENTICATION', 'PMS_USER')") - @PreAuthorize("hasAnyRole('ZONAL_ADMIN','GLOBAL_ADMIN','PMS_ADMIN','PMS_USER')") - @ResponseFilter - @PostMapping(value = "/uploadPartnerCertificate", produces = "application/json") - public ResponseWrapper uploadPartnerCertificate( - @ApiParam("Upload Partner Certificates.") @RequestBody @Valid RequestWrapper partnerCertRequestDto) { - - ResponseWrapper response = new ResponseWrapper<>(); - response.setResponse(partnerCertManagerService.uploadPartnerCertificate(partnerCertRequestDto.getRequest())); - return response; - } - - /** - * To Download Partner Certificate. - * - * @param certDownloadRequestDto {@link PartnerCertDownloadRequestDto} request - * @return {@link PartnerCertDownloadResponeDto} encrypted Data - */ - // @PreAuthorize("hasAnyRole('ZONAL_ADMIN','GLOBAL_ADMIN','INDIVIDUAL', - // 'ID_AUTHENTICATION', 'PMS_USER')") - @PreAuthorize("hasAnyRole('ZONAL_ADMIN','GLOBAL_ADMIN','PMS_ADMIN','PMS_USER')") - @ResponseFilter - @GetMapping(value = "/getPartnerCertificate/{partnerCertId}") - public ResponseWrapper getPartnerCertificate( - @ApiParam("To download re-signed partner certificate.") @PathVariable("partnerCertId") String partnerCertId) { - PartnerCertDownloadRequestDto certDownloadRequestDto = new PartnerCertDownloadRequestDto(); - certDownloadRequestDto.setPartnerCertId(partnerCertId); - ResponseWrapper response = new ResponseWrapper<>(); - response.setResponse(partnerCertManagerService.getPartnerCertificate(certDownloadRequestDto)); - return response; - } - - /** - * To Upload Partner Certificate. - * - * @param certificateTrustRequestDto {@CertificateTrustRequestDto CertificateTrustDto} request - * @return {@link CertificateTrustResponeDto} certificate verify response - */ - // @PreAuthorize("hasAnyRole('ZONAL_ADMIN','GLOBAL_ADMIN','INDIVIDUAL', - // 'ID_AUTHENTICATION', 'PMS_USER')") - @PreAuthorize("hasAnyRole('ZONAL_ADMIN','GLOBAL_ADMIN','PMS_ADMIN','PMS_USER')") - @ResponseFilter - @PostMapping(value = "/verifyCertificateTrust", produces = "application/json") - public ResponseWrapper verifyCertificateTrust( - @ApiParam("Upload Partner Certificates.") @RequestBody @Valid RequestWrapper certificateTrustRequestDto) { - - ResponseWrapper response = new ResponseWrapper<>(); - response.setResponse(partnerCertManagerService.verifyCertificateTrust(certificateTrustRequestDto.getRequest())); - return response; - } - -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/dto/CACertificateRequestDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/dto/CACertificateRequestDto.java deleted file mode 100644 index 7af74c6700f..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/dto/CACertificateRequestDto.java +++ /dev/null @@ -1,38 +0,0 @@ -package io.mosip.kernel.partnercertservice.dto; - -import javax.validation.constraints.NotBlank; - -import io.mosip.kernel.keymanagerservice.constant.KeymanagerConstant; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * CA/Sub-CA Certificate Request DTO. - * - * @author Mahammed Taheer - * @since 1.1.2 -*/ - -@Data -@AllArgsConstructor -@NoArgsConstructor -@ApiModel(description = "Model representing request to upload CA/Sub-CA certificates.") -public class CACertificateRequestDto { - - /** - * Certificate Data of CA or Sub-CA. - */ - @ApiModelProperty(notes = "X509 Certificate Data", required = true) - @NotBlank(message = KeymanagerConstant.INVALID_REQUEST) - String certificateData; - - /** - * Certificate Data of CA or Sub-CA. - */ - @ApiModelProperty(notes = "Partner Domain", required = true) - @NotBlank(message = KeymanagerConstant.INVALID_REQUEST) - String partnerDomain; -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/dto/CACertificateResponseDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/dto/CACertificateResponseDto.java deleted file mode 100644 index bcde3cc8135..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/dto/CACertificateResponseDto.java +++ /dev/null @@ -1,26 +0,0 @@ -package io.mosip.kernel.partnercertservice.dto; - -import java.time.LocalDateTime; - -import lombok.Data; - -/** - * DTO class for upload certificate response. - * - * @author Mahammed Taheer - * @since 1.1.2 - * - */ -@Data -public class CACertificateResponseDto { - - /** - * Status of upload certificate. - */ - private String status; - - /** - * Response timestamp. - */ - private LocalDateTime timestamp; -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/dto/CertificateTrustRequestDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/dto/CertificateTrustRequestDto.java deleted file mode 100644 index c0828af1006..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/dto/CertificateTrustRequestDto.java +++ /dev/null @@ -1,38 +0,0 @@ -package io.mosip.kernel.partnercertservice.dto; - -import javax.validation.constraints.NotBlank; - -import io.mosip.kernel.keymanagerservice.constant.KeymanagerConstant; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * Partner Certificates Verify Trust Request DTO. - * - * @author Mahammed Taheer - * @since 1.1.2 -*/ - -@Data -@AllArgsConstructor -@NoArgsConstructor -@ApiModel(description = "Model representing request to verify Partner certificate trust.") -public class CertificateTrustRequestDto { - - /** - * Certificate Data of Partner. - */ - @ApiModelProperty(notes = "X509 Certificate Data", required = true) - @NotBlank(message = KeymanagerConstant.INVALID_REQUEST) - String certificateData; - - /** - * Partner Type. - */ - @ApiModelProperty(notes = "Partner Domain", required = true) - @NotBlank(message = KeymanagerConstant.INVALID_REQUEST) - String partnerDomain; -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/dto/CertificateTrustResponeDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/dto/CertificateTrustResponeDto.java deleted file mode 100644 index bcbdc6342f1..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/dto/CertificateTrustResponeDto.java +++ /dev/null @@ -1,20 +0,0 @@ -package io.mosip.kernel.partnercertservice.dto; - -import lombok.Data; - -/** - * DTO class for certificate verification response. - * - * @author Mahammed Taheer - * @since 1.1.2 - * - */ -@Data -public class CertificateTrustResponeDto { - - /** - * Status of certificate verification. - */ - private Boolean status; - -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/dto/PartnerCertDownloadRequestDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/dto/PartnerCertDownloadRequestDto.java deleted file mode 100644 index c10855b7f7f..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/dto/PartnerCertDownloadRequestDto.java +++ /dev/null @@ -1,31 +0,0 @@ -package io.mosip.kernel.partnercertservice.dto; - -import javax.validation.constraints.NotBlank; - -import io.mosip.kernel.keymanagerservice.constant.KeymanagerConstant; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * Partner Certificate Download Request DTO. - * - * @author Mahammed Taheer - * @since 1.1.2 -*/ - -@Data -@AllArgsConstructor -@NoArgsConstructor -@ApiModel(description = "Model representing request to download partner certificates.") -public class PartnerCertDownloadRequestDto { - - /** - * Certificate ID of Partner. - */ - @ApiModelProperty(notes = "Partner Certificate ID", required = true) - @NotBlank(message = KeymanagerConstant.INVALID_REQUEST) - String partnerCertId; -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/dto/PartnerCertDownloadResponeDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/dto/PartnerCertDownloadResponeDto.java deleted file mode 100644 index dd9b1646f51..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/dto/PartnerCertDownloadResponeDto.java +++ /dev/null @@ -1,26 +0,0 @@ -package io.mosip.kernel.partnercertservice.dto; - -import java.time.LocalDateTime; - -import lombok.Data; - -/** - * DTO class for download of partner certificate response. - * - * @author Mahammed Taheer - * @since 1.1.2 - * - */ -@Data -public class PartnerCertDownloadResponeDto { - - /** - * Partner Certificate Data. - */ - private String certificateData; - - /** - * Response timestamp. - */ - private LocalDateTime timestamp; -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/dto/PartnerCertificateRequestDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/dto/PartnerCertificateRequestDto.java deleted file mode 100644 index fac512a6260..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/dto/PartnerCertificateRequestDto.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.mosip.kernel.partnercertservice.dto; - -import javax.validation.constraints.NotBlank; - -import io.mosip.kernel.keymanagerservice.constant.KeymanagerConstant; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * Partner Certificates Request DTO. - * - * @author Mahammed Taheer - * @since 1.1.2 -*/ - -@Data -@AllArgsConstructor -@NoArgsConstructor -@ApiModel(description = "Model representing request to upload Partner certificates.") -public class PartnerCertificateRequestDto { - - /** - * Certificate Data of Partner. - */ - @ApiModelProperty(notes = "X509 Certificate Data", required = true) - @NotBlank(message = KeymanagerConstant.INVALID_REQUEST) - String certificateData; - - /** - * Certificate Data of Partner. - */ - @ApiModelProperty(notes = "Organization Name", required = true) - @NotBlank(message = KeymanagerConstant.INVALID_REQUEST) - String organizationName; - - /** - * Partner Type. - */ - @ApiModelProperty(notes = "Partner Domain", required = true) - @NotBlank(message = KeymanagerConstant.INVALID_REQUEST) - String partnerDomain; -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/dto/PartnerCertificateResponseDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/dto/PartnerCertificateResponseDto.java deleted file mode 100644 index 5aaba728a83..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/dto/PartnerCertificateResponseDto.java +++ /dev/null @@ -1,32 +0,0 @@ -package io.mosip.kernel.partnercertservice.dto; - -import java.time.LocalDateTime; - -import lombok.Data; - -/** - * DTO class for upload certificate response. - * - * @author Mahammed Taheer - * @since 1.1.2 - * - */ -@Data -public class PartnerCertificateResponseDto { - - /** - * Field for certificate - */ - private String signedCertificateData; - - /** - * Field for certificateId - */ - private String certificateId; - - /** - * Field for Response time - */ - private LocalDateTime timestamp; - -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/exception/PartnerCertManagerException.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/exception/PartnerCertManagerException.java deleted file mode 100644 index 6e8130f0827..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/exception/PartnerCertManagerException.java +++ /dev/null @@ -1,38 +0,0 @@ -package io.mosip.kernel.partnercertservice.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; - -/** - * Custom Exception Class in case of PartnerCertManagerException - * - * @author Mahammed Taheer - * @since 1.1.2 - * - */ -public class PartnerCertManagerException extends BaseUncheckedException { - - /** - * Generated serial version id - */ - private static final long serialVersionUID = 8621530697947108810L; - - /** - * Constructor the initialize Handler exception - * - * @param errorCode The errorcode for this exception - * @param errorMessage The error message for this exception - */ - public PartnerCertManagerException(String errorCode, String errorMessage) { - super(errorCode, errorMessage); - } - - /** - * @param errorCode The errorcode for this exception - * @param errorMessage The error message for this exception - * @param rootCause cause of the error occoured - */ - public PartnerCertManagerException(String errorCode, String errorMessage, Throwable rootCause) { - super(errorCode, errorMessage, rootCause); - } - -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/helper/PartnerCertManagerDBHelper.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/helper/PartnerCertManagerDBHelper.java deleted file mode 100644 index 7293beeb2b5..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/helper/PartnerCertManagerDBHelper.java +++ /dev/null @@ -1,164 +0,0 @@ -package io.mosip.kernel.partnercertservice.helper; - -import java.security.cert.TrustAnchor; -import java.security.cert.X509Certificate; -import java.time.LocalDateTime; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.stream.Collectors; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.DateUtils; -import io.mosip.kernel.keymanagerservice.entity.CACertificateStore; -import io.mosip.kernel.keymanagerservice.entity.PartnerCertificateStore; -import io.mosip.kernel.keymanagerservice.logger.KeymanagerLogger; -import io.mosip.kernel.keymanagerservice.repository.CACertificateStoreRepository; -import io.mosip.kernel.keymanagerservice.repository.PartnerCertificateStoreRepository; -import io.mosip.kernel.keymanagerservice.util.KeymanagerUtil; -import io.mosip.kernel.partnercertservice.constant.PartnerCertManagerConstants; -import io.mosip.kernel.partnercertservice.util.PartnerCertificateManagerUtil; - -/** - * DB Helper class for Keymanager - * - * @author Mahammed Taheer - * @since 1.1.2 - * - */ - -@Component -public class PartnerCertManagerDBHelper { - - private static final Logger LOGGER = KeymanagerLogger.getLogger(PartnerCertManagerDBHelper.class); - - /** - * {@link KeyAliasRepository} instance - */ - @Autowired - CACertificateStoreRepository caCertificateStoreRepository; - - /** - * {@link KeyAliasRepository} instance - */ - @Autowired - PartnerCertificateStoreRepository partnerCertificateStoreRepository; - - /** - * Utility to generate Metadata - */ - @Autowired - KeymanagerUtil keymanagerUtil; - - public boolean isCertificateExist(String certThumbprint, String partnerDomain){ - CACertificateStore caCertificate = caCertificateStoreRepository - .findByCertThumbprintAndPartnerDomain(certThumbprint, partnerDomain); - if (Objects.nonNull(caCertificate)) { - return true; - } - return false; - } - - public boolean isPartnerCertificateExist(String certThumbprint, String partnerDomain){ - List partnerCertificateList = partnerCertificateStoreRepository - .findByCertThumbprintAndPartnerDomain(certThumbprint, partnerDomain); - if (partnerCertificateList.size() > 0) { - return true; - } - return false; - } - - public void storeCACertificate(String certId, String certSubject, String certIssuer, String issuerId, - X509Certificate reqX509Cert, String certThumbprint, String partnerDomain) { - - String certSerialNo = reqX509Cert.getSerialNumber().toString(); - LocalDateTime notBeforeDate = DateUtils.parseDateToLocalDateTime(reqX509Cert.getNotBefore()); - LocalDateTime notAfterDate = DateUtils.parseDateToLocalDateTime(reqX509Cert.getNotAfter()); - String certData = keymanagerUtil.getPEMFormatedData(reqX509Cert); - CACertificateStore certStoreObj = new CACertificateStore(); - certStoreObj.setCertId(certId); - certStoreObj.setCertSubject(certSubject); - certStoreObj.setCertIssuer(certIssuer); - certStoreObj.setIssuerId(issuerId); - certStoreObj.setCertNotBefore(notBeforeDate); - certStoreObj.setCertNotAfter(notAfterDate); - certStoreObj.setCertData(certData); - certStoreObj.setCertThumbprint(certThumbprint); - certStoreObj.setCertSerialNo(certSerialNo); - certStoreObj.setPartnerDomain(partnerDomain); - caCertificateStoreRepository.saveAndFlush(keymanagerUtil.setMetaData(certStoreObj)); - } - - public Map> getTrustAnchors(String partnerDomain) { - Set rootTrust = new HashSet<>(); - Set intermediateCerts = new HashSet<>(); - caCertificateStoreRepository.findByPartnerDomain(partnerDomain).stream().forEach( - trustCert -> { - String certificateData = trustCert.getCertData(); - X509Certificate x509Cert = (X509Certificate) keymanagerUtil.convertToCertificate(certificateData); - if (PartnerCertificateManagerUtil.isCertificateDatesValid(x509Cert)) { - if (PartnerCertificateManagerUtil.isSelfSignedCertificate(x509Cert)) { - rootTrust.add(new TrustAnchor(x509Cert, null)); - } else{ - intermediateCerts.add(x509Cert); - } - } - } - ); - Map> hashMap = new HashMap<>(); - hashMap.put(PartnerCertManagerConstants.TRUST_ROOT, rootTrust); - hashMap.put(PartnerCertManagerConstants.TRUST_INTER, intermediateCerts); - return hashMap; - } - - public String getIssuerCertId(String certIssuerDn) { - LocalDateTime currentDateTime = DateUtils.getUTCCurrentDateTime(); - List certificates = caCertificateStoreRepository.findByCertSubject(certIssuerDn) - .stream().filter(cert -> PartnerCertificateManagerUtil.isValidTimestamp(currentDateTime, cert)) - .collect(Collectors.toList()); - - if (certificates.size() == 1) { - return certificates.get(0).getCertId(); - } - List sortedCerts = certificates.stream() - .sorted((cert1, cert2) -> cert1.getCertNotBefore().compareTo(cert2.getCertNotBefore())) - .collect(Collectors.toList()); - return sortedCerts.get(0).getCertId(); - } - - public void storePartnerCertificate(String certId, String certSubject, String certIssuer, String issuerId, - X509Certificate reqX509Cert, String certThumbprint, String orgName, String partnerDomain, - String signedCertData) { - - String certSerialNo = reqX509Cert.getSerialNumber().toString(); - LocalDateTime notBeforeDate = DateUtils.parseDateToLocalDateTime(reqX509Cert.getNotBefore()); - LocalDateTime notAfterDate = DateUtils.parseDateToLocalDateTime(reqX509Cert.getNotAfter()); - String certData = keymanagerUtil.getPEMFormatedData(reqX509Cert); - - PartnerCertificateStore partnerStoreObj = new PartnerCertificateStore(); - partnerStoreObj.setCertId(certId); - partnerStoreObj.setCertSubject(certSubject); - partnerStoreObj.setCertIssuer(certIssuer); - partnerStoreObj.setIssuerId(issuerId); - partnerStoreObj.setCertNotBefore(notBeforeDate); - partnerStoreObj.setCertNotAfter(notAfterDate); - partnerStoreObj.setCertData(certData); - partnerStoreObj.setCertThumbprint(certThumbprint); - partnerStoreObj.setCertSerialNo(certSerialNo); - partnerStoreObj.setOrganizationName(orgName); - partnerStoreObj.setPartnerDomain(partnerDomain); - partnerStoreObj.setKeyUsage(PartnerCertManagerConstants.EMPTY); //TODO update key usage later. - partnerStoreObj.setSignedCertData(signedCertData); - partnerCertificateStoreRepository.saveAndFlush(keymanagerUtil.setMetaData(partnerStoreObj)); - } - - public PartnerCertificateStore getPartnerCert(String certId) { - return partnerCertificateStoreRepository.findByCertId(certId); - } -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/service/impl/PartnerCertificateManagerServiceImpl.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/service/impl/PartnerCertificateManagerServiceImpl.java deleted file mode 100644 index 41f844636ca..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/service/impl/PartnerCertificateManagerServiceImpl.java +++ /dev/null @@ -1,546 +0,0 @@ -package io.mosip.kernel.partnercertservice.service.impl; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.security.InvalidAlgorithmParameterException; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.cert.CertPathBuilder; -import java.security.cert.CertPathBuilderException; -import java.security.cert.CertStore; -import java.security.cert.Certificate; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.CollectionCertStoreParameters; -import java.security.cert.PKIXBuilderParameters; -import java.security.cert.PKIXCertPathBuilderResult; -import java.security.cert.TrustAnchor; -import java.security.cert.X509CertSelector; -import java.security.cert.X509Certificate; -import java.time.LocalDateTime; -import java.time.temporal.ChronoUnit; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.UUID; -import java.util.stream.Stream; - -import javax.security.auth.x500.X500Principal; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import io.mosip.kernel.core.keymanager.model.CertificateParameters; -import io.mosip.kernel.core.keymanager.spi.KeyStore; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.CryptoUtil; -import io.mosip.kernel.core.util.DateUtils; -import io.mosip.kernel.keymanagerservice.exception.KeymanagerServiceException; -import io.mosip.kernel.keymanager.hsm.util.CertificateUtility; -import io.mosip.kernel.keymanagerservice.dto.SignatureCertificate; -import io.mosip.kernel.keymanagerservice.entity.PartnerCertificateStore; -import io.mosip.kernel.keymanagerservice.logger.KeymanagerLogger; -import io.mosip.kernel.keymanagerservice.service.KeymanagerService; -import io.mosip.kernel.keymanagerservice.util.KeymanagerUtil; -import io.mosip.kernel.partnercertservice.constant.PartnerCertManagerConstants; -import io.mosip.kernel.partnercertservice.constant.PartnerCertManagerErrorConstants; -import io.mosip.kernel.partnercertservice.dto.CACertificateRequestDto; -import io.mosip.kernel.partnercertservice.dto.CACertificateResponseDto; -import io.mosip.kernel.partnercertservice.dto.CertificateTrustRequestDto; -import io.mosip.kernel.partnercertservice.dto.CertificateTrustResponeDto; -import io.mosip.kernel.partnercertservice.dto.PartnerCertDownloadRequestDto; -import io.mosip.kernel.partnercertservice.dto.PartnerCertDownloadResponeDto; -import io.mosip.kernel.partnercertservice.dto.PartnerCertificateRequestDto; -import io.mosip.kernel.partnercertservice.dto.PartnerCertificateResponseDto; -import io.mosip.kernel.partnercertservice.exception.PartnerCertManagerException; -import io.mosip.kernel.partnercertservice.helper.PartnerCertManagerDBHelper; -import io.mosip.kernel.partnercertservice.service.spi.PartnerCertificateManagerService; -import io.mosip.kernel.partnercertservice.util.PartnerCertificateManagerUtil; - -/** - * This class provides the implementation for the methods of - * PartnerCertificateManagerService interface. - * - * @author Mahammed Taheer - * @since 1.1.2 - * - */ -@Service -@Transactional -public class PartnerCertificateManagerServiceImpl implements PartnerCertificateManagerService { - - private static final Logger LOGGER = KeymanagerLogger.getLogger(PartnerCertificateManagerServiceImpl.class); - - @Value("${mosip.kernel.partner.sign.masterkey.application.id}") - private String masterSignKeyAppId; - - @Value("${mosip.kernel.partner.allowed.domains}") - private String partnerAllowedDomains; - - @Value("${mosip.kernel.certificate.sign.algorithm:SHA256withRSA}") - private String signAlgorithm; - - @Value("${mosip.kernel.partner.issuer.certificate.duration.years:1}") - private int issuerCertDuration; - - @Value("${mosip.kernel.partner.issuer.certificate.allowed.grace.duration:30}") - private int gracePeriod; - - @Value("${mosip.kernel.partner.resign.ftm.domain.certs:false}") - private boolean resignFTMDomainCerts; - - /** - * Utility to generate Metadata - */ - @Autowired - KeymanagerUtil keymanagerUtil; - - /** - * Utility to generate Metadata - */ - @Autowired - PartnerCertManagerDBHelper certDBHelper; - - /** - * Keystore instance to handles and store cryptographic keys. - */ - @Autowired - private KeyStore keyStore; - - @Autowired - private KeymanagerService keymanagerService; - - @Override - public CACertificateResponseDto uploadCACertificate(CACertificateRequestDto caCertRequestDto) { - LOGGER.info(PartnerCertManagerConstants.SESSIONID, PartnerCertManagerConstants.UPLOAD_CA_CERT, - PartnerCertManagerConstants.EMPTY, "Uploading CA/Sub-CA Certificate."); - - String certificateData = caCertRequestDto.getCertificateData(); - if (!keymanagerUtil.isValidCertificateData(certificateData)) { - LOGGER.error(PartnerCertManagerConstants.SESSIONID, PartnerCertManagerConstants.UPLOAD_CA_CERT, - PartnerCertManagerConstants.EMPTY, - "Invalid Certificate Data provided to upload the ca/sub-ca certificate."); - throw new PartnerCertManagerException(PartnerCertManagerErrorConstants.INVALID_CERTIFICATE.getErrorCode(), - PartnerCertManagerErrorConstants.INVALID_CERTIFICATE.getErrorMessage()); - } - - List certList = parseCertificateData(certificateData); - int certsCount = certList.size(); - LOGGER.info(PartnerCertManagerConstants.SESSIONID, PartnerCertManagerConstants.UPLOAD_CA_CERT, - PartnerCertManagerConstants.EMPTY, "Number of Certificates inputed: " + certsCount); - - String partnerDomain = validateAllowedDomains(caCertRequestDto.getPartnerDomain()); - boolean foundError = false; - boolean uploadedCert = false; - for(Certificate cert : certList) { - X509Certificate reqX509Cert = (X509Certificate) cert; - - String certThumbprint = PartnerCertificateManagerUtil.getCertificateThumbprint(reqX509Cert); - boolean certExist = certDBHelper.isCertificateExist(certThumbprint, partnerDomain); - if (certExist) { - LOGGER.info(PartnerCertManagerConstants.SESSIONID, PartnerCertManagerConstants.UPLOAD_CA_CERT, - PartnerCertManagerConstants.EMPTY, "CA/sub-CA certificate already exists in Store."); - if (certsCount == 1) { - throw new PartnerCertManagerException( - PartnerCertManagerErrorConstants.CERTIFICATE_EXIST_ERROR.getErrorCode(), - PartnerCertManagerErrorConstants.CERTIFICATE_EXIST_ERROR.getErrorMessage()); - } - foundError = true; - continue; - } - - boolean validDates = PartnerCertificateManagerUtil.isCertificateDatesValid(reqX509Cert); - if (!validDates) { - LOGGER.info(PartnerCertManagerConstants.SESSIONID, PartnerCertManagerConstants.UPLOAD_CA_CERT, - PartnerCertManagerConstants.EMPTY, "Certificate Dates are not valid."); - if(certsCount == 1) { - throw new PartnerCertManagerException( - PartnerCertManagerErrorConstants.CERTIFICATE_DATES_NOT_VALID.getErrorCode(), - PartnerCertManagerErrorConstants.CERTIFICATE_DATES_NOT_VALID.getErrorMessage()); - } - foundError = true; - continue; - } - - String certSubject = PartnerCertificateManagerUtil - .formatCertificateDN(reqX509Cert.getSubjectX500Principal().getName()); - String certIssuer = PartnerCertificateManagerUtil - .formatCertificateDN(reqX509Cert.getIssuerX500Principal().getName()); - boolean selfSigned = PartnerCertificateManagerUtil.isSelfSignedCertificate(reqX509Cert); - - if (selfSigned) { - LOGGER.info(PartnerCertManagerConstants.SESSIONID, PartnerCertManagerConstants.UPLOAD_CA_CERT, - PartnerCertManagerConstants.EMPTY, "Adding Self-signed Certificate in store."); - String certId = UUID.randomUUID().toString(); - certDBHelper.storeCACertificate(certId, certSubject, certIssuer, certId, reqX509Cert, certThumbprint, - partnerDomain); - uploadedCert = true; - } else { - LOGGER.info(PartnerCertManagerConstants.SESSIONID, PartnerCertManagerConstants.UPLOAD_CA_CERT, - PartnerCertManagerConstants.EMPTY, "Adding Intermediate Certificates in store."); - - boolean certValid = validateCertificatePath(reqX509Cert, partnerDomain); - if (!certValid) { - LOGGER.info(PartnerCertManagerConstants.SESSIONID, PartnerCertManagerConstants.UPLOAD_CA_CERT, - PartnerCertManagerConstants.EMPTY, - "Sub-CA Certificate not allowed to upload as root CA is not available."); - if (certsCount == 1) { - throw new PartnerCertManagerException(PartnerCertManagerErrorConstants.ROOT_CA_NOT_FOUND.getErrorCode(), - PartnerCertManagerErrorConstants.ROOT_CA_NOT_FOUND.getErrorMessage()); - } - foundError = true; - continue; - } - String issuerId = certDBHelper.getIssuerCertId(certIssuer); - String certId = UUID.randomUUID().toString(); - certDBHelper.storeCACertificate(certId, certSubject, certIssuer, issuerId, reqX509Cert, certThumbprint, - partnerDomain); - uploadedCert = true; - } - } - CACertificateResponseDto responseDto = new CACertificateResponseDto(); - if (uploadedCert && (certsCount == 1 || !foundError)) - responseDto.setStatus(PartnerCertManagerConstants.SUCCESS_UPLOAD); - else if (uploadedCert && foundError) - responseDto.setStatus(PartnerCertManagerConstants.PARTIAL_SUCCESS_UPLOAD); - else - responseDto.setStatus(PartnerCertManagerConstants.UPLOAD_FAILED); - responseDto.setTimestamp(DateUtils.getUTCCurrentDateTime()); - return responseDto; - } - - private List parseCertificateData(String certificateData) { - List certList = new ArrayList<>(); - try { - X509Certificate reqX509Cert = (X509Certificate) keymanagerUtil.convertToCertificate(certificateData); - certList.add(reqX509Cert); - return certList; - } catch(KeymanagerServiceException kse) { - LOGGER.info(PartnerCertManagerConstants.SESSIONID, PartnerCertManagerConstants.UPLOAD_CA_CERT, - PartnerCertManagerConstants.EMPTY, "Ignore this exception, the exception thrown when certificate is not" - + " able to parse, may be p7b certificate data inputed."); - } - // Try to Parse as P7B file. - byte[] p7bBytes = CryptoUtil.decodeBase64(certificateData); - try (ByteArrayInputStream certStream = new ByteArrayInputStream(p7bBytes)) { - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - Collection p7bCertList = cf.generateCertificates(certStream); - p7bCertList.forEach(cert -> { - certList.add((Certificate)cert); - }); - Collections.reverse(certList); - return certList; - } catch(CertificateException | IOException exp) { - LOGGER.error(PartnerCertManagerConstants.SESSIONID, PartnerCertManagerConstants.UPLOAD_CA_CERT, - PartnerCertManagerConstants.EMPTY, "Error Parsing P7B Certificate data.", exp); - } - throw new PartnerCertManagerException( - PartnerCertManagerErrorConstants.INVALID_CERTIFICATE.getErrorCode(), - PartnerCertManagerErrorConstants.INVALID_CERTIFICATE.getErrorMessage()); - } - - private String validateAllowedDomains(String partnerDomain) { - String validPartnerDomain = Stream.of(partnerAllowedDomains.split(",")).map(String::trim) - .filter(allowedDomain -> allowedDomain.equalsIgnoreCase(partnerDomain)).findFirst() - .orElseThrow(() -> new PartnerCertManagerException( - PartnerCertManagerErrorConstants.INVALID_PARTNER_DOMAIN.getErrorCode(), - PartnerCertManagerErrorConstants.INVALID_PARTNER_DOMAIN.getErrorMessage())); - return validPartnerDomain.toUpperCase(); - } - - @SuppressWarnings("unchecked") - private List getCertificateTrustPath(X509Certificate reqX509Cert, String partnerDomain) { - - try { - Map> trustStoreMap = certDBHelper.getTrustAnchors(partnerDomain); - Set rootTrustAnchors = (Set) trustStoreMap - .get(PartnerCertManagerConstants.TRUST_ROOT); - Set interCerts = (Set) trustStoreMap - .get(PartnerCertManagerConstants.TRUST_INTER); - - LOGGER.info(PartnerCertManagerConstants.SESSIONID, PartnerCertManagerConstants.CERT_TRUST_VALIDATION, - PartnerCertManagerConstants.EMPTY, "Certificate Trust Path Validation for domain: " + partnerDomain); - LOGGER.info(PartnerCertManagerConstants.SESSIONID, PartnerCertManagerConstants.CERT_TRUST_VALIDATION, - PartnerCertManagerConstants.EMPTY, "Total Number of ROOT Trust Found: " + rootTrustAnchors.size()); - LOGGER.info(PartnerCertManagerConstants.SESSIONID, PartnerCertManagerConstants.CERT_TRUST_VALIDATION, - PartnerCertManagerConstants.EMPTY, "Total Number of INTERMEDIATE Trust Found: " + interCerts.size()); - - X509CertSelector certToVerify = new X509CertSelector(); - certToVerify.setCertificate(reqX509Cert); - - PKIXBuilderParameters pkixBuilderParams = new PKIXBuilderParameters(rootTrustAnchors, certToVerify); - pkixBuilderParams.setRevocationEnabled(false); - - CertStore interCertStore = CertStore.getInstance("Collection", - new CollectionCertStoreParameters(interCerts)); - pkixBuilderParams.addCertStore(interCertStore); - - // Building the cert path and verifying the certification chain - CertPathBuilder certPathBuilder = CertPathBuilder.getInstance("PKIX"); - //certPathBuilder.build(pkixBuilderParams); - PKIXCertPathBuilderResult result = (PKIXCertPathBuilderResult) certPathBuilder.build(pkixBuilderParams); - - X509Certificate rootCert = result.getTrustAnchor().getTrustedCert(); - List certList = result.getCertPath().getCertificates(); - List trustCertList = new ArrayList<>(); - certList.stream().forEach(cert -> { - trustCertList.add(cert); - }); - trustCertList.add(rootCert); - return trustCertList; - } catch (CertPathBuilderException | InvalidAlgorithmParameterException | NoSuchAlgorithmException exp) { - LOGGER.info(PartnerCertManagerConstants.SESSIONID, PartnerCertManagerConstants.UPLOAD_CA_CERT, - PartnerCertManagerConstants.EMPTY, - "Ignore this exception, the exception thrown when trust validation failed."); - } - return null; - } - - private boolean validateCertificatePath(X509Certificate reqX509Cert, String partnerDomain) { - List certList = getCertificateTrustPath(reqX509Cert, partnerDomain); - return Objects.nonNull(certList); - } - - @Override - public PartnerCertificateResponseDto uploadPartnerCertificate(PartnerCertificateRequestDto partnerCertRequesteDto) { - LOGGER.info(PartnerCertManagerConstants.SESSIONID, PartnerCertManagerConstants.UPLOAD_PARTNER_CERT, - PartnerCertManagerConstants.EMPTY, "Uploading Partner Certificate."); - - String certificateData = partnerCertRequesteDto.getCertificateData(); - if (!keymanagerUtil.isValidCertificateData(certificateData)) { - LOGGER.error(PartnerCertManagerConstants.SESSIONID, PartnerCertManagerConstants.UPLOAD_PARTNER_CERT, - PartnerCertManagerConstants.EMPTY, - "Invalid Certificate Data provided to upload the partner certificate."); - throw new PartnerCertManagerException(PartnerCertManagerErrorConstants.INVALID_CERTIFICATE.getErrorCode(), - PartnerCertManagerErrorConstants.INVALID_CERTIFICATE.getErrorMessage()); - } - - X509Certificate reqX509Cert = (X509Certificate) keymanagerUtil.convertToCertificate(certificateData); - String certThumbprint = PartnerCertificateManagerUtil.getCertificateThumbprint(reqX509Cert); - String reqOrgName = partnerCertRequesteDto.getOrganizationName(); - String partnerDomain = validateAllowedDomains(partnerCertRequesteDto.getPartnerDomain()); - - LOGGER.info(PartnerCertManagerConstants.SESSIONID, PartnerCertManagerConstants.UPLOAD_PARTNER_CERT, - PartnerCertManagerConstants.EMPTY, "Partner certificate upload for domain: " + partnerDomain); - - validateBasicPartnerCertParams(reqX509Cert, certThumbprint, reqOrgName, partnerDomain); - - List certList = getCertificateTrustPath(reqX509Cert, partnerDomain); - //boolean certValid = validateCertificatePath(reqX509Cert, partnerDomain); - if (Objects.isNull(certList)) { - LOGGER.error(PartnerCertManagerConstants.SESSIONID, PartnerCertManagerConstants.UPLOAD_PARTNER_CERT, - PartnerCertManagerConstants.EMPTY, - "Partner Certificate not allowed to upload as root CA/Intermediate CAs are not found in trust cert path."); - throw new PartnerCertManagerException( - PartnerCertManagerErrorConstants.ROOT_INTER_CA_NOT_FOUND.getErrorCode(), - PartnerCertManagerErrorConstants.ROOT_INTER_CA_NOT_FOUND.getErrorMessage()); - } - validateOtherPartnerCertParams(reqX509Cert, reqOrgName); - - String certSubject = PartnerCertificateManagerUtil - .formatCertificateDN(reqX509Cert.getSubjectX500Principal().getName()); - String certIssuer = PartnerCertificateManagerUtil - .formatCertificateDN(reqX509Cert.getIssuerX500Principal().getName()); - String issuerId = certDBHelper.getIssuerCertId(certIssuer); - String certId = UUID.randomUUID().toString(); - - X509Certificate rootCert = (X509Certificate) keymanagerUtil.convertToCertificate( - keymanagerService.getCertificate(PartnerCertManagerConstants.ROOT_APP_ID, - Optional.of(PartnerCertManagerConstants.EMPTY)).getCertificate()); - String timestamp = DateUtils.getUTCCurrentDateTimeString(); - SignatureCertificate certificateResponse = keymanagerService.getSignatureCertificate(masterSignKeyAppId, - Optional.of(PartnerCertManagerConstants.EMPTY), timestamp); - X509Certificate pmsCert = certificateResponse.getCertificateEntry().getChain()[0]; - - X509Certificate resignedCert = reSignPartnerKey(reqX509Cert, certificateResponse, partnerDomain); - String signedCertData = keymanagerUtil.getPEMFormatedData(resignedCert); - certDBHelper.storePartnerCertificate(certId, certSubject, certIssuer, issuerId, reqX509Cert, certThumbprint, - reqOrgName, partnerDomain, signedCertData); - - String p7bCertChain = PartnerCertificateManagerUtil.buildP7BCertificateChain(certList, resignedCert, partnerDomain, - resignFTMDomainCerts, rootCert, pmsCert); - CACertificateRequestDto caCertReqDto = new CACertificateRequestDto(); - caCertReqDto.setCertificateData(p7bCertChain); - caCertReqDto.setPartnerDomain(partnerDomain); - CACertificateResponseDto uploadResponseDto = uploadCACertificate(caCertReqDto); - LOGGER.info(PartnerCertManagerConstants.SESSIONID, PartnerCertManagerConstants.UPLOAD_PARTNER_CERT, - "Chain Upload Status: ", uploadResponseDto.getStatus()); - PartnerCertificateResponseDto responseDto = new PartnerCertificateResponseDto(); - responseDto.setCertificateId(certId); - responseDto.setSignedCertificateData(p7bCertChain); - responseDto.setTimestamp(DateUtils.getUTCCurrentDateTime()); - return responseDto; - } - - private void validateBasicPartnerCertParams(X509Certificate reqX509Cert, String certThumbprint, String reqOrgName, - String partnerDomain) { - boolean certExist = certDBHelper.isPartnerCertificateExist(certThumbprint, partnerDomain); - if (certExist) { - LOGGER.info(PartnerCertManagerConstants.SESSIONID, PartnerCertManagerConstants.UPLOAD_PARTNER_CERT, - PartnerCertManagerConstants.EMPTY, "Partner certificate already exists in Store."); - // Commented below throw clause because renewal of certificate should be allowed for existing certificates. - // Added one more condition to check certificate validity is in allowed date range. - /* throw new PartnerCertManagerException( - PartnerCertManagerErrorConstants.CERTIFICATE_EXIST_ERROR.getErrorCode(), - PartnerCertManagerErrorConstants.CERTIFICATE_EXIST_ERROR.getErrorMessage()); */ - } - - boolean validDates = PartnerCertificateManagerUtil.isCertificateDatesValid(reqX509Cert); - if (!validDates) { - LOGGER.error(PartnerCertManagerConstants.SESSIONID, PartnerCertManagerConstants.UPLOAD_PARTNER_CERT, - PartnerCertManagerConstants.EMPTY, "Certificate Dates are not valid."); - throw new PartnerCertManagerException( - PartnerCertManagerErrorConstants.CERTIFICATE_DATES_NOT_VALID.getErrorCode(), - PartnerCertManagerErrorConstants.CERTIFICATE_DATES_NOT_VALID.getErrorMessage()); - } - - boolean validDuration = PartnerCertificateManagerUtil.isCertificateValidForDuration(reqX509Cert, issuerCertDuration, gracePeriod); - if (!validDuration) { - LOGGER.error(PartnerCertManagerConstants.SESSIONID, PartnerCertManagerConstants.UPLOAD_PARTNER_CERT, - PartnerCertManagerConstants.EMPTY, "Certificate Dates are not in allowed range."); - throw new PartnerCertManagerException( - PartnerCertManagerErrorConstants.CERTIFICATE_DATES_NOT_VALID.getErrorCode(), - PartnerCertManagerErrorConstants.CERTIFICATE_DATES_NOT_VALID.getErrorMessage()); - } - - boolean selfSigned = PartnerCertificateManagerUtil.isSelfSignedCertificate(reqX509Cert); - if (selfSigned) { - LOGGER.error(PartnerCertManagerConstants.SESSIONID, PartnerCertManagerConstants.UPLOAD_PARTNER_CERT, - PartnerCertManagerConstants.EMPTY, "Self Signed Certificate are not in allowed as Partner."); - throw new PartnerCertManagerException( - PartnerCertManagerErrorConstants.SELF_SIGNED_CERT_NOT_ALLOWED.getErrorCode(), - PartnerCertManagerErrorConstants.SELF_SIGNED_CERT_NOT_ALLOWED.getErrorMessage()); - } - } - - private void validateOtherPartnerCertParams(X509Certificate reqX509Cert, String reqOrgName) { - int certVersion = reqX509Cert.getVersion(); - if (certVersion != 3) { - LOGGER.error(PartnerCertManagerConstants.SESSIONID, PartnerCertManagerConstants.UPLOAD_PARTNER_CERT, - PartnerCertManagerConstants.EMPTY, - "Partner Certificate version not valid, the version has to be V3"); - throw new PartnerCertManagerException(PartnerCertManagerErrorConstants.INVALID_CERT_VERSION.getErrorCode(), - PartnerCertManagerErrorConstants.INVALID_CERT_VERSION.getErrorMessage()); - } - - String certOrgName = PartnerCertificateManagerUtil.getCertificateOrgName(reqX509Cert.getSubjectX500Principal()); - if (!certOrgName.equals(reqOrgName)) { - LOGGER.error(PartnerCertManagerConstants.SESSIONID, PartnerCertManagerConstants.UPLOAD_PARTNER_CERT, - PartnerCertManagerConstants.EMPTY, - "Partner Certificate Organization and Partner Organization Name not matching."); - throw new PartnerCertManagerException(PartnerCertManagerErrorConstants.PARTNER_ORG_NOT_MATCH.getErrorCode(), - PartnerCertManagerErrorConstants.PARTNER_ORG_NOT_MATCH.getErrorMessage()); - } - - String keyAlgorithm = reqX509Cert.getPublicKey().getAlgorithm(); - if (keyAlgorithm.equalsIgnoreCase(PartnerCertManagerConstants.RSA_ALGORITHM)) { - int keySize = ((java.security.interfaces.RSAPublicKey) reqX509Cert.getPublicKey()).getModulus().bitLength(); - if (keySize < PartnerCertManagerConstants.RSA_MIN_KEY_SIZE) { - LOGGER.error(PartnerCertManagerConstants.SESSIONID, PartnerCertManagerConstants.UPLOAD_PARTNER_CERT, - PartnerCertManagerConstants.EMPTY, "Partner Certificate key is less than allowed size."); - throw new PartnerCertManagerException( - PartnerCertManagerErrorConstants.CERT_KEY_NOT_ALLOWED.getErrorCode(), - PartnerCertManagerErrorConstants.CERT_KEY_NOT_ALLOWED.getErrorMessage()); - } - } - - String signatureAlgorithm = reqX509Cert.getSigAlgName(); - if (!signatureAlgorithm.toUpperCase().startsWith(PartnerCertManagerConstants.HASH_SHA2)) { - LOGGER.error(PartnerCertManagerConstants.SESSIONID, PartnerCertManagerConstants.UPLOAD_PARTNER_CERT, - PartnerCertManagerConstants.EMPTY, "Signature Algorithm not supported."); - throw new PartnerCertManagerException( - PartnerCertManagerErrorConstants.CERT_SIGNATURE_ALGO_NOT_ALLOWED.getErrorCode(), - PartnerCertManagerErrorConstants.CERT_SIGNATURE_ALGO_NOT_ALLOWED.getErrorMessage()); - } - } - - private X509Certificate reSignPartnerKey(X509Certificate reqX509Cert, SignatureCertificate certificateResponse, - String partnerDomain) { - - LOGGER.info(PartnerCertManagerConstants.SESSIONID, PartnerCertManagerConstants.UPLOAD_PARTNER_CERT, "KeyAlias", - "Found Master Key Alias: " + certificateResponse.getAlias()); - - PrivateKey signPrivateKey = certificateResponse.getCertificateEntry().getPrivateKey(); - X509Certificate signCert = certificateResponse.getCertificateEntry().getChain()[0]; - X500Principal signerPrincipal = signCert.getSubjectX500Principal(); - - X500Principal subjectPrincipal = reqX509Cert.getSubjectX500Principal(); - PublicKey partnerPublicKey = reqX509Cert.getPublicKey(); - - int noOfDays = PartnerCertManagerConstants.YEAR_DAYS * issuerCertDuration; - LOGGER.info(PartnerCertManagerConstants.SESSIONID, PartnerCertManagerConstants.UPLOAD_PARTNER_CERT, "Cert Duration", - "Calculated Signed Certficiate Number of Days for expire: " + noOfDays); - LocalDateTime notBeforeDate = DateUtils.getUTCCurrentDateTime(); - LocalDateTime notAfterDate = notBeforeDate.plus(noOfDays, ChronoUnit.DAYS); - CertificateParameters certParams = PartnerCertificateManagerUtil.getCertificateParameters(subjectPrincipal, - notBeforeDate, notAfterDate); - boolean encKeyUsage = partnerDomain.equalsIgnoreCase(PartnerCertManagerConstants.AUTH_DOMAIN); - return (X509Certificate) CertificateUtility.generateX509Certificate(signPrivateKey, partnerPublicKey, certParams, - signerPrincipal, signAlgorithm, keyStore.getKeystoreProviderName(), encKeyUsage); - } - - @Override - public PartnerCertDownloadResponeDto getPartnerCertificate(PartnerCertDownloadRequestDto certDownloadRequestDto) { - - LOGGER.info(PartnerCertManagerConstants.SESSIONID, PartnerCertManagerConstants.GET_PARTNER_CERT, - PartnerCertManagerConstants.EMPTY, "Get Partner Certificate Request."); - - String partnetCertId = certDownloadRequestDto.getPartnerCertId(); - - if (!PartnerCertificateManagerUtil.isValidCertificateID(partnetCertId)) { - LOGGER.error(PartnerCertManagerConstants.SESSIONID, PartnerCertManagerConstants.UPLOAD_PARTNER_CERT, - PartnerCertManagerConstants.EMPTY, - "Invalid Certificate ID provided to get the partner certificate."); - throw new PartnerCertManagerException( - PartnerCertManagerErrorConstants.INVALID_CERTIFICATE_ID.getErrorCode(), - PartnerCertManagerErrorConstants.INVALID_CERTIFICATE_ID.getErrorMessage()); - } - PartnerCertificateStore partnerCertStore = certDBHelper.getPartnerCert(partnetCertId); - if (Objects.isNull(partnerCertStore)) { - LOGGER.error(PartnerCertManagerConstants.SESSIONID, PartnerCertManagerConstants.UPLOAD_PARTNER_CERT, - PartnerCertManagerConstants.EMPTY, "Partner Certificate not found for the provided ID."); - throw new PartnerCertManagerException( - PartnerCertManagerErrorConstants.PARTNER_CERT_ID_NOT_FOUND.getErrorCode(), - PartnerCertManagerErrorConstants.PARTNER_CERT_ID_NOT_FOUND.getErrorMessage()); - } - - PartnerCertDownloadResponeDto responseDto = new PartnerCertDownloadResponeDto(); - responseDto.setCertificateData(partnerCertStore.getSignedCertData()); - responseDto.setTimestamp(DateUtils.getUTCCurrentDateTime()); - return responseDto; - } - - @Override - public CertificateTrustResponeDto verifyCertificateTrust(CertificateTrustRequestDto certificateTrustRequestDto) { - LOGGER.info(PartnerCertManagerConstants.SESSIONID, PartnerCertManagerConstants.CERT_TRUST_VALIDATION, - PartnerCertManagerConstants.EMPTY, "Certificate Trust Path Validation."); - - String certificateData = certificateTrustRequestDto.getCertificateData(); - if (!keymanagerUtil.isValidCertificateData(certificateData)) { - LOGGER.error(PartnerCertManagerConstants.SESSIONID, PartnerCertManagerConstants.UPLOAD_PARTNER_CERT, - PartnerCertManagerConstants.EMPTY, - "Invalid Certificate Data provided to verify partner certificate trust."); - throw new PartnerCertManagerException(PartnerCertManagerErrorConstants.INVALID_CERTIFICATE.getErrorCode(), - PartnerCertManagerErrorConstants.INVALID_CERTIFICATE.getErrorMessage()); - } - X509Certificate reqX509Cert = (X509Certificate) keymanagerUtil.convertToCertificate(certificateData); - String partnerDomain = validateAllowedDomains(certificateTrustRequestDto.getPartnerDomain()); - - LOGGER.info(PartnerCertManagerConstants.SESSIONID, PartnerCertManagerConstants.CERT_TRUST_VALIDATION, - PartnerCertManagerConstants.EMPTY, "Certificate Trust Path Validation for domain: " + partnerDomain); - - boolean certValid = validateCertificatePath(reqX509Cert, partnerDomain); - CertificateTrustResponeDto responseDto = new CertificateTrustResponeDto(); - responseDto.setStatus(certValid); - return responseDto; - } - -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/service/spi/PartnerCertificateManagerService.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/service/spi/PartnerCertificateManagerService.java deleted file mode 100644 index 75a912927f0..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/service/spi/PartnerCertificateManagerService.java +++ /dev/null @@ -1,54 +0,0 @@ -package io.mosip.kernel.partnercertservice.service.spi; - -import io.mosip.kernel.partnercertservice.dto.CACertificateRequestDto; -import io.mosip.kernel.partnercertservice.dto.CACertificateResponseDto; -import io.mosip.kernel.partnercertservice.dto.CertificateTrustRequestDto; -import io.mosip.kernel.partnercertservice.dto.CertificateTrustResponeDto; -import io.mosip.kernel.partnercertservice.dto.PartnerCertDownloadRequestDto; -import io.mosip.kernel.partnercertservice.dto.PartnerCertDownloadResponeDto; -import io.mosip.kernel.partnercertservice.dto.PartnerCertificateRequestDto; -import io.mosip.kernel.partnercertservice.dto.PartnerCertificateResponseDto; - -/** - * This interface provides the methods for Partner Certificate Management Service. - * - * @author Mahammed Taheer - * @since 1.1.2 - * - */ - -public interface PartnerCertificateManagerService { - - /** - * Function to Upload CA/Sub-CA certificates - * - * @param CACertificateRequestDto caCertResponseDto - * @return {@link CACertificateResponseDto} instance - */ - public CACertificateResponseDto uploadCACertificate(CACertificateRequestDto caCertResponseDto); - - /** - * Function to Upload Partner certificates - * - * @param PartnerCertificateRequestDto partnerCertResponseDto - * @return {@link PartnerCertificateResponseDto} instance - */ - public PartnerCertificateResponseDto uploadPartnerCertificate(PartnerCertificateRequestDto partnerCertResponseDto); - - /** - * Function to Download Partner certificates - * - * @param PartnerCertDownloadRequestDto certDownloadRequestDto - * @return {@link PartnerCertDownloadResponeDto} instance - */ - public PartnerCertDownloadResponeDto getPartnerCertificate(PartnerCertDownloadRequestDto certDownloadRequestDto); - - /** - * Function to verify partner certificates trust. - * - * @param CertificateTrustRequestDto certificateTrustRequestDto - * @return {@link CertificateTrustResponeDto} instance - */ - public CertificateTrustResponeDto verifyCertificateTrust(CertificateTrustRequestDto certificateTrustRequestDto); - -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/util/PartnerCertificateManagerUtil.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/util/PartnerCertificateManagerUtil.java deleted file mode 100644 index 082dc7800b2..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/partnercertservice/util/PartnerCertificateManagerUtil.java +++ /dev/null @@ -1,244 +0,0 @@ -package io.mosip.kernel.partnercertservice.util; - -import java.io.IOException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.SignatureException; -import java.security.cert.Certificate; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateException; -import java.security.cert.CertificateExpiredException; -import java.security.cert.CertificateNotYetValidException; -import java.security.cert.X509Certificate; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.time.temporal.ChronoUnit; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.List; - -import javax.security.auth.x500.X500Principal; - -import org.apache.commons.codec.digest.DigestUtils; -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.x500.RDN; -import org.bouncycastle.asn1.x500.X500Name; -import org.bouncycastle.asn1.x500.style.BCStyle; -import org.bouncycastle.asn1.x500.style.IETFUtils; -import org.bouncycastle.cert.jcajce.JcaCertStore; -import org.bouncycastle.cms.CMSAbsentContent; -import org.bouncycastle.cms.CMSException; -import org.bouncycastle.cms.CMSSignedData; -import org.bouncycastle.cms.CMSSignedDataGenerator; -import org.bouncycastle.cms.CMSTypedData; - -import io.mosip.kernel.core.keymanager.model.CertificateParameters; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.CryptoUtil; -import io.mosip.kernel.core.util.DateUtils; -import io.mosip.kernel.keymanagerservice.entity.CACertificateStore; -import io.mosip.kernel.keymanagerservice.logger.KeymanagerLogger; -import io.mosip.kernel.partnercertservice.constant.PartnerCertManagerConstants; -import io.mosip.kernel.partnercertservice.constant.PartnerCertManagerErrorConstants; -import io.mosip.kernel.partnercertservice.exception.PartnerCertManagerException; - -/** - * Utility class for Partner Certificate Management - * - * @author Mahammed Taheer - * @since 1.1.3 - * - */ -public class PartnerCertificateManagerUtil { - - private static final Logger LOGGER = KeymanagerLogger.getLogger(PartnerCertificateManagerUtil.class); - - /** - * Function to check certificate is self-signed. - * - * @param x509Cert X509Certificate - * - * @return true if x509Cert is self-signed, else false - */ - public static boolean isSelfSignedCertificate(X509Certificate x509Cert) { - try { - x509Cert.verify(x509Cert.getPublicKey()); - return true; - } catch (CertificateException | NoSuchAlgorithmException | InvalidKeyException | SignatureException - | NoSuchProviderException exp) { - LOGGER.info(PartnerCertManagerConstants.SESSIONID, PartnerCertManagerConstants.UPLOAD_CA_CERT, - PartnerCertManagerConstants.PCM_UTIL, - "Ignore this exception, the exception thrown when signature validation failed."); - } - return false; - } - - /** - * Function to format X500Principal of certificate. - * - * @param certPrincipal String form of X500Principal - * - * @return String of Custom format of certificateDN. - */ - public static String formatCertificateDN(String certPrincipal) { - - X500Name x500Name = new X500Name(certPrincipal); - StringBuilder strBuilder = new StringBuilder(); - strBuilder.append(getAttributeIfExist(x500Name, BCStyle.CN)); - strBuilder.append(getAttributeIfExist(x500Name, BCStyle.OU)); - strBuilder.append(getAttributeIfExist(x500Name, BCStyle.O)); - strBuilder.append(getAttributeIfExist(x500Name, BCStyle.L)); - strBuilder.append(getAttributeIfExist(x500Name, BCStyle.ST)); - strBuilder.append(getAttributeIfExist(x500Name, BCStyle.C)); - - if (strBuilder.length() > 0 && strBuilder.toString().endsWith(",")) { - return strBuilder.substring(0, strBuilder.length() - 1); - } - return strBuilder.toString(); - } - - private static String getAttributeIfExist(X500Name x500Name, ASN1ObjectIdentifier identifier) { - RDN[] rdns = x500Name.getRDNs(identifier); - if (rdns.length == 0) { - return PartnerCertManagerConstants.EMPTY; - } - return BCStyle.INSTANCE.oidToDisplayName(identifier) + PartnerCertManagerConstants.EQUALS - + IETFUtils.valueToString((rdns[0]).getFirst().getValue()) + PartnerCertManagerConstants.COMMA; - } - - public static String getCertificateThumbprint(X509Certificate x509Cert) { - try { - return DigestUtils.sha1Hex(x509Cert.getEncoded()); - } catch (CertificateEncodingException e) { - LOGGER.error(PartnerCertManagerConstants.SESSIONID, PartnerCertManagerConstants.UPLOAD_CA_CERT, - PartnerCertManagerConstants.PCM_UTIL, "Error generating certificate thumbprint."); - throw new PartnerCertManagerException(PartnerCertManagerErrorConstants.CERTIFICATE_THUMBPRINT_ERROR.getErrorCode(), - PartnerCertManagerErrorConstants.CERTIFICATE_THUMBPRINT_ERROR.getErrorMessage()); - } - } - - public static boolean isCertificateDatesValid(X509Certificate x509Cert) { - - try { - Date currentDate = Date.from(DateUtils.getUTCCurrentDateTime().atZone(ZoneId.systemDefault()).toInstant()); - x509Cert.checkValidity(currentDate); - return true; - } catch(CertificateExpiredException | CertificateNotYetValidException exp) { - LOGGER.info(PartnerCertManagerConstants.SESSIONID, PartnerCertManagerConstants.UPLOAD_CA_CERT, - PartnerCertManagerConstants.PCM_UTIL, - "Ignore this exception, the exception thrown when certificate dates are not valid."); - } - try { - // Checking both system default timezone & UTC Offset timezone. Issue found in reg-client during trust validation. - x509Cert.checkValidity(); - return true; - } catch(CertificateExpiredException | CertificateNotYetValidException exp) { - LOGGER.info(PartnerCertManagerConstants.SESSIONID, PartnerCertManagerConstants.UPLOAD_CA_CERT, - PartnerCertManagerConstants.PCM_UTIL, - "Ignore this exception, the exception thrown when certificate dates are not valid."); - } - return false; - } - - public static boolean isCertificateValidForDuration(X509Certificate x509Cert, int issuerCertDuration, int gracePeriod) { - - try { - int noOfDays = (issuerCertDuration * PartnerCertManagerConstants.YEAR_DAYS) - gracePeriod; - LocalDateTime localDateTimeStamp = DateUtils.getUTCCurrentDateTime().plus(noOfDays, ChronoUnit.DAYS); - Date issuerDuration = Date.from(localDateTimeStamp.atZone(ZoneId.systemDefault()).toInstant()); - x509Cert.checkValidity(issuerDuration); - return true; - } catch(CertificateExpiredException | CertificateNotYetValidException exp) { - LOGGER.info(PartnerCertManagerConstants.SESSIONID, PartnerCertManagerConstants.UPLOAD_CA_CERT, - PartnerCertManagerConstants.PCM_UTIL, - "Ignore this exception, the exception thrown when certificate dates are not allowed within grace period."); - } - return false; - } - - public static boolean isValidTimestamp(LocalDateTime timeStamp, CACertificateStore certStore) { - boolean valid = timeStamp.isEqual(certStore.getCertNotBefore()) || timeStamp.isEqual(certStore.getCertNotAfter()) - || (timeStamp.isAfter(certStore.getCertNotBefore()) - && timeStamp.isBefore(certStore.getCertNotAfter())); - if (!valid) { - LocalDateTime localDateTimeNow = LocalDateTime.now(); - valid = localDateTimeNow.isEqual(certStore.getCertNotBefore()) || localDateTimeNow.isEqual(certStore.getCertNotAfter()) - || (localDateTimeNow.isAfter(certStore.getCertNotBefore()) - && localDateTimeNow.isBefore(certStore.getCertNotAfter())); - } - return valid; - } - - public static String getCertificateOrgName(X500Principal x500CertPrincipal) { - X500Name x500Name = new X500Name(x500CertPrincipal.getName()); - RDN[] rdns = x500Name.getRDNs(BCStyle.O); - if (rdns.length == 0) { - return PartnerCertManagerConstants.EMPTY; - } - return IETFUtils.valueToString((rdns[0]).getFirst().getValue()); - } - - public static boolean isValidCertificateID(String certID) { - return certID != null && !certID.trim().isEmpty(); - } - - public static CertificateParameters getCertificateParameters(X500Principal latestCertPrincipal, LocalDateTime notBefore, - LocalDateTime notAfter) { - - CertificateParameters certParams = new CertificateParameters(); - X500Name x500Name = new X500Name(latestCertPrincipal.getName()); - - certParams.setCommonName(IETFUtils.valueToString((x500Name.getRDNs(BCStyle.CN)[0]).getFirst().getValue())); - certParams.setOrganizationUnit(getAttributeValueIfExist(x500Name, BCStyle.OU)); - certParams.setOrganization(getAttributeValueIfExist(x500Name, BCStyle.O)); - certParams.setLocation(getAttributeValueIfExist(x500Name, BCStyle.L)); - certParams.setState(getAttributeValueIfExist(x500Name, BCStyle.ST)); - certParams.setCountry(getAttributeValueIfExist(x500Name, BCStyle.C)); - certParams.setNotBefore(notBefore); - certParams.setNotAfter(notAfter); - return certParams; - } - - private static String getAttributeValueIfExist(X500Name x500Name, ASN1ObjectIdentifier identifier) { - RDN[] rdns = x500Name.getRDNs(identifier); - if (rdns.length == 0) { - return PartnerCertManagerConstants.EMPTY; - } - return IETFUtils.valueToString((rdns[0]).getFirst().getValue()); - } - - public static String buildP7BCertificateChain(List certList, X509Certificate resignedCert, - String partnerDomain, boolean resignFTMDomainCerts, X509Certificate rootCert, X509Certificate pmsCert) { - - if (partnerDomain.toUpperCase().equals(PartnerCertManagerConstants.FTM_PARTNER_DOMAIN) && !resignFTMDomainCerts) { - return buildCertChain(certList.toArray(new Certificate[0])); - } - - List chain = new ArrayList<>(); - chain.add(resignedCert); - chain.add(pmsCert); - chain.add(rootCert); - return buildCertChain(chain.toArray(new Certificate[0])); - } - - private static String buildCertChain(Certificate[] chain) { - - try { - CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); - JcaCertStore jcaStore = new JcaCertStore(Arrays.asList(chain)); - generator.addCertificates(jcaStore); - - CMSTypedData cmsTypedData = new CMSAbsentContent(); - CMSSignedData cmsSignedData = generator.generate(cmsTypedData); - return CryptoUtil.encodeBase64(cmsSignedData.getEncoded()); - } catch(CertificateEncodingException | CMSException | IOException e) { - LOGGER.error(PartnerCertManagerConstants.SESSIONID, PartnerCertManagerConstants.UPLOAD_PARTNER_CERT, - PartnerCertManagerConstants.PCM_UTIL, "Error generating p7b certificates chain."); - throw new PartnerCertManagerException(PartnerCertManagerErrorConstants.CERTIFICATE_THUMBPRINT_ERROR.getErrorCode(), - PartnerCertManagerErrorConstants.CERTIFICATE_THUMBPRINT_ERROR.getErrorMessage(), e); - } - } - -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/constant/SignatureConstant.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/constant/SignatureConstant.java deleted file mode 100644 index 80d956b0e2f..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/constant/SignatureConstant.java +++ /dev/null @@ -1,43 +0,0 @@ -package io.mosip.kernel.signature.constant; - -/** - * Constant class for Signature Constant Service - * - * @author Uday Kumar - * - * @since 1.0.0 - */ -public class SignatureConstant { - /** - * Private Constructor for this class - */ - private SignatureConstant() { - - } - - public static final String VALIDATION_SUCCESSFUL = "Validation Successful"; - public static final String SUCCESS = "success"; - - public static final String SESSIONID = "SignatureSessionId"; - - public static final String JWT_SIGN = "JWTSignature"; - - public static final String BLANK = ""; - - public static final Boolean DEFAULT_INCLUDES = false; - - public static final String JWT_HEADER_CERT_KEY = "x5c"; - - public static final String PERIOD = "\\."; - - public static final String VALIDATION_FAILED = "Validation Failed"; - - public static final String TRUST_NOT_VERIFIED = "TRUST_NOT_VERIFIED"; - - public static final String TRUST_NOT_VERIFIED_NO_DOMAIN = "TRUST_NOT_VERIFIED_NO_DOMAIN"; - - public static final String TRUST_NOT_VALID = "TRUST_CERT_PATH_NOT_VALID"; - - public static final String TRUST_VALID = "TRUST_CERT_PATH_VALID"; - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/constant/SignatureErrorCode.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/constant/SignatureErrorCode.java deleted file mode 100644 index 378894ea4ce..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/constant/SignatureErrorCode.java +++ /dev/null @@ -1,44 +0,0 @@ -package io.mosip.kernel.signature.constant; - -/** - * Constants for CryptoSignaure - * - * @author Uday Kumarl - * @since 1.0.0 - * - */ -public enum SignatureErrorCode { - REQUEST_DATA_NOT_VALID("KER-CSS-999", "Invalid request input"), - NOT_VALID("KER-CSS-101", "Validation Unsuccessful"), - - INVALID_INPUT("KER-JWS-102", "Data to sign is not valid."), - - INVALID_JSON("KER-JWS-103", "Data to sign is not valid JSON."), - - SIGN_ERROR("KER-JWS-104", "Error - Unable to sign the data."), - - VERIFY_ERROR("KER-JWS-105", "Error - Unable to verify the data."), - - INVALID_VERIFY_INPUT("KER-JWS-106", "Signature data to verify not valid."), - - CERT_NOT_VALID("KER-JWS-107", "Signature verification certificate not valid."), - - INTERNAL_SERVER_ERROR("KER-CSS-102", "Internal server error"); - - private final String errorCode; - private final String errorMessage; - - private SignatureErrorCode(final String errorCode, final String errorMessage) { - this.errorCode = errorCode; - this.errorMessage = errorMessage; - } - - public String getErrorCode() { - return errorCode; - } - - public String getErrorMessage() { - return errorMessage; - } - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/controller/SignatureController.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/controller/SignatureController.java deleted file mode 100644 index d7a4b3d3f8a..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/controller/SignatureController.java +++ /dev/null @@ -1,115 +0,0 @@ -package io.mosip.kernel.signature.controller; - -import javax.validation.Valid; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.CrossOrigin; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RestController; - -import io.mosip.kernel.core.http.RequestWrapper; -import io.mosip.kernel.core.http.ResponseFilter; -import io.mosip.kernel.core.http.ResponseWrapper; -import io.mosip.kernel.core.signatureutil.model.SignatureResponse; -import io.mosip.kernel.signature.dto.JWTSignatureRequestDto; -import io.mosip.kernel.signature.dto.JWTSignatureResponseDto; -import io.mosip.kernel.signature.dto.JWTSignatureVerifyRequestDto; -import io.mosip.kernel.signature.dto.JWTSignatureVerifyResponseDto; -import io.mosip.kernel.signature.dto.PDFSignatureRequestDto; -import io.mosip.kernel.signature.dto.SignRequestDto; -import io.mosip.kernel.signature.dto.SignResponseDto; -import io.mosip.kernel.signature.dto.SignatureResponseDto; -import io.mosip.kernel.signature.dto.TimestampRequestDto; -import io.mosip.kernel.signature.dto.ValidatorResponseDto; -import io.mosip.kernel.signature.service.SignatureService; - -/** - * - * @author Uday Kumar - * @since 1.0.0 - * - */ -@RestController -@CrossOrigin -public class SignatureController { - /** - * Crypto signature Service field with functions related to signature - */ - @Autowired - SignatureService service; - - /** - * Function to sign response - * - * @param requestDto {@link SignRequestDto} having required fields. - * @return The {@link SignatureResponse} - */ - @PreAuthorize("hasAnyRole('ZONAL_ADMIN','GLOBAL_ADMIN','INDIVIDUAL','ID_AUTHENTICATION', 'REGISTRATION_ADMIN', 'REGISTRATION_SUPERVISOR', 'REGISTRATION_OFFICER', 'REGISTRATION_PROCESSOR','PRE_REGISTRATION_ADMIN','RESIDENT')") - @ResponseFilter - @PostMapping(value = "/sign") - @Deprecated - public ResponseWrapper sign(@RequestBody @Valid RequestWrapper requestDto) { - SignatureResponse signatureResponse = service.sign(requestDto.getRequest()); - SignResponseDto signResponse = new SignResponseDto(); - signResponse.setTimestamp(signatureResponse.getTimestamp()); - signResponse.setSignature(signatureResponse.getData()); - ResponseWrapper response = new ResponseWrapper<>(); - response.setResponse(signResponse); - return response; - } - - @PreAuthorize("hasAnyRole('ZONAL_ADMIN','GLOBAL_ADMIN','INDIVIDUAL','ID_AUTHENTICATION', 'REGISTRATION_ADMIN', 'REGISTRATION_SUPERVISOR', 'REGISTRATION_OFFICER', 'REGISTRATION_PROCESSOR','PRE_REGISTRATION_ADMIN')") - @ResponseFilter - @PostMapping(value = "/validate") - @Deprecated - public ResponseWrapper validate( - @RequestBody @Valid RequestWrapper timestampRequestDto) { - ResponseWrapper response = new ResponseWrapper<>(); - response.setResponse(service.validate(timestampRequestDto.getRequest())); - return response; - } - - @PreAuthorize("hasAnyRole('ZONAL_ADMIN','GLOBAL_ADMIN','INDIVIDUAL','ID_AUTHENTICATION', 'REGISTRATION_ADMIN', 'REGISTRATION_SUPERVISOR', 'REGISTRATION_OFFICER', 'REGISTRATION_PROCESSOR','PRE_REGISTRATION_ADMIN','RESIDENT')") - @ResponseFilter - @PostMapping("/pdf/sign") - public ResponseWrapper signPDF( - @RequestBody @Valid RequestWrapper signatureResponseDto) { - ResponseWrapper response = new ResponseWrapper<>(); - response.setResponse(service.signPDF(signatureResponseDto.getRequest())); - return response; - } - - /** - * Function to JWT sign data - * - * @param requestDto {@link JWTSignatureRequestDto} having required fields. - * @return The {@link JWTSignatureResponseDto} - */ - @PreAuthorize("hasAnyRole('ZONAL_ADMIN','GLOBAL_ADMIN','INDIVIDUAL','ID_AUTHENTICATION', 'REGISTRATION_ADMIN', 'REGISTRATION_SUPERVISOR', 'REGISTRATION_OFFICER', 'REGISTRATION_PROCESSOR','PRE_REGISTRATION_ADMIN','RESIDENT')") - @ResponseFilter - @PostMapping(value = "/jwtSign") - public ResponseWrapper jwtSign(@RequestBody @Valid RequestWrapper requestDto) { - JWTSignatureResponseDto signatureResponse = service.jwtSign(requestDto.getRequest()); - ResponseWrapper response = new ResponseWrapper<>(); - response.setResponse(signatureResponse); - return response; - } - - /** - * Function to JWT Signature verification - * - * @param requestDto {@link JWTSignatureVerifyRequestDto} having required fields. - * @return The {@link JWTSignatureVerifyResponseDto} - */ - @PreAuthorize("hasAnyRole('ZONAL_ADMIN','GLOBAL_ADMIN','INDIVIDUAL','ID_AUTHENTICATION', 'REGISTRATION_ADMIN', 'REGISTRATION_SUPERVISOR', 'REGISTRATION_OFFICER', 'REGISTRATION_PROCESSOR','PRE_REGISTRATION_ADMIN','RESIDENT')") - @ResponseFilter - @PostMapping(value = "/jwtVerify") - public ResponseWrapper jwtVerify(@RequestBody @Valid RequestWrapper requestDto) { - JWTSignatureVerifyResponseDto signatureResponse = service.jwtVerify(requestDto.getRequest()); - ResponseWrapper response = new ResponseWrapper<>(); - response.setResponse(signatureResponse); - return response; - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/JWTSignatureRequestDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/JWTSignatureRequestDto.java deleted file mode 100644 index 18a49d96c46..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/JWTSignatureRequestDto.java +++ /dev/null @@ -1,62 +0,0 @@ -package io.mosip.kernel.signature.dto; - -import javax.validation.constraints.NotBlank; - -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * - * @author Mahammed Taheer - * @since 1.2.0-SNAPSHOT - * - */ - -@Data -@NoArgsConstructor -@AllArgsConstructor -public class JWTSignatureRequestDto { - - @NotBlank - @ApiModelProperty(notes = "Base64 encoded JSON Data to sign", example = "ewogICAiYW55S2V5IjogIlRlc3QgSnNvbiIKfQ", required = true) - private String dataToSign; - - /** - * Application id of decrypting module - */ - @ApiModelProperty(notes = "Application id to be used for signing", example = "KERNEL", required = false) - private String applicationId; - - /** - * Refrence Id - */ - @ApiModelProperty(notes = "Refrence Id", example = "SIGN", required = false) - private String referenceId; - - /** - * Flag to include payload in JWT Signature Header - */ - @ApiModelProperty(notes = "Flag to include payload in JWT Signature Header.", example = "false", required = false) - private Boolean includePayload; - - /** - * Flag to include certificate in JWT Signature Header - */ - @ApiModelProperty(notes = "Flag to include certificate in JWT Signature Header.", example = "false", required = false) - private Boolean includeCertificate; - - /** - * Flag to include certificate hash in JWT Signature Header - */ - @ApiModelProperty(notes = "Flag to include certificate hash(sha256) in JWT Signature Header.", example = "false", required = false) - private Boolean includeCertHash; - - /** - * Certificate URL to include in JWT Signature Header - */ - @ApiModelProperty(notes = "Flag to include certificate hash(sha256) in JWT Signature Header.", required = false) - private String certificateUrl; - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/JWTSignatureResponseDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/JWTSignatureResponseDto.java deleted file mode 100644 index 7a9e070aefe..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/JWTSignatureResponseDto.java +++ /dev/null @@ -1,29 +0,0 @@ -package io.mosip.kernel.signature.dto; - -import java.time.LocalDateTime; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * - * @author Mahammed Taheer - * @since 1.2.0-SNAPSHOT - * - */ -@Data -@NoArgsConstructor -@AllArgsConstructor -public class JWTSignatureResponseDto { - - /** - * encrypted data - */ - private String jwtSignedData; - - /** - * response time. - */ - private LocalDateTime timestamp; -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/JWTSignatureVerifyRequestDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/JWTSignatureVerifyRequestDto.java deleted file mode 100644 index c26a2876488..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/JWTSignatureVerifyRequestDto.java +++ /dev/null @@ -1,60 +0,0 @@ - -package io.mosip.kernel.signature.dto; - -import javax.validation.constraints.NotBlank; - -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * - * @author Mahammed Taheer - * @since 1.2.0-SNAPSHOT - * - */ - -@Data -@NoArgsConstructor -@AllArgsConstructor -public class JWTSignatureVerifyRequestDto { - - @NotBlank - @ApiModelProperty(notes = "JWT Signature data to verify", example = "eyJhbGciOiJIU.ewogICAiYW55S2V.5IjogIlRlc3QgSnNvbiIKfQ", required = true) - private String jwtSignatureData; - - @ApiModelProperty(notes = "Base64 encoded actual data used for signing", example = "ewogICAiYW55S2V5IjogIlRlc3QgSnNvbiIKfQ", required = false) - private String actualData; - - /** - * Application id of decrypting module - */ - @ApiModelProperty(notes = "Application id to be used for verification", example = "KERNEL", required = false) - private String applicationId; - - /** - * Refrence Id - */ - @ApiModelProperty(notes = "Refrence Id", example = "SIGN", required = false) - private String referenceId; - - /** - * Certificate to be use in JWT Signature verification. - */ - @ApiModelProperty(notes = "Certificate to be use in JWT Signature verification.", example = "", required = false) - private String certificateData; - - /** - * Flag to validate against trust store. - */ - @ApiModelProperty(notes = "Flag to validate against trust store.", example = "false", required = false) - private Boolean validateTrust; - - /** - * Domain to be considered to validate trust store - */ - @ApiModelProperty(notes = "Domain to be considered to validate trust store.", example = "", required = false) - private String domain; - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/JWTSignatureVerifyResponseDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/JWTSignatureVerifyResponseDto.java deleted file mode 100644 index 876595053fb..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/JWTSignatureVerifyResponseDto.java +++ /dev/null @@ -1,32 +0,0 @@ -package io.mosip.kernel.signature.dto; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * - * @author Mahammed Taheer - * @since 1.2.0-SNAPSHOT - * - */ -@Data -@NoArgsConstructor -@AllArgsConstructor -public class JWTSignatureVerifyResponseDto { - - /** - * The Signature verification status. - */ - private boolean signatureValid; - - /** - * The Signature validation message. - */ - private String message; - - /** - * The Trust validation status. - */ - private String trustValid; -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/PDFSignatureRequestDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/PDFSignatureRequestDto.java deleted file mode 100644 index fa4b9ab2f5c..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/PDFSignatureRequestDto.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * - * - * - * - */ -package io.mosip.kernel.signature.dto; - -import javax.validation.constraints.Max; -import javax.validation.constraints.Min; -import javax.validation.constraints.NotBlank; - -import io.mosip.kernel.keymanagerservice.constant.KeymanagerConstant; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; - -/** - * Crypto-Manager-Request model - * - * @author Urvil Joshi - * - * @since 1.0.0 - */ -@Data -@EqualsAndHashCode(callSuper = false) -@AllArgsConstructor -@NoArgsConstructor -@ApiModel(description = "Model representing a PDF sign request") -public class PDFSignatureRequestDto extends SignatureRequestDto { - /** - * The lower left x value of sign rectangle. - */ - @ApiModelProperty(notes = "The lower left x value of sign rectangle.", required = true) - @Min(value = 0) - @Max(value = Integer.MAX_VALUE) - private int lowerLeftX; - - /** - * The lower left y value of sign rectangle. - */ - @ApiModelProperty(notes = "The lower left y value of sign rectangle.", required = true) - @Min(value = 0) - @Max(value = Integer.MAX_VALUE) - private int lowerLeftY; - - /** - * The upper right x value of sign rectangle. - */ - @ApiModelProperty(notes = "The upper right x value of sign rectangle.", required = true) - @Min(value = 0) - @Max(value = Integer.MAX_VALUE) - private int upperRightX; - - /** - * The upper right y value of sign rectangle. - */ - @ApiModelProperty(notes = "The upper right y value of sign rectangle.", required = true) - @Min(value = 0) - @Max(value = Integer.MAX_VALUE) - private int upperRightY; - - /** - * Reason for signing. - */ - @ApiModelProperty(notes = "Reason for signing.", required = true) - @NotBlank(message = KeymanagerConstant.INVALID_REQUEST) - private String reason; - - /** - * Page number for signature. - */ - @ApiModelProperty(notes = "Page number for signature.", required = true) - @Min(value = 0) - @Max(value = Integer.MAX_VALUE) - private int pageNumber; - - /** - * Password for protecting PDF - */ - @ApiModelProperty(notes = "Password for protecting PDF") - private String password; -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/PublicKeyRequestDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/PublicKeyRequestDto.java deleted file mode 100644 index b8a19f66be7..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/PublicKeyRequestDto.java +++ /dev/null @@ -1,20 +0,0 @@ -package io.mosip.kernel.signature.dto; - -import javax.validation.constraints.NotBlank; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -@Data -@NoArgsConstructor -@AllArgsConstructor -public class PublicKeyRequestDto { - @NotBlank - private String signature; - @NotBlank - private String data; - @NotBlank - private String publickey; - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/SignRequestDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/SignRequestDto.java deleted file mode 100644 index 01a194e1338..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/SignRequestDto.java +++ /dev/null @@ -1,16 +0,0 @@ -package io.mosip.kernel.signature.dto; - -import javax.validation.constraints.NotBlank; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -@Data -@NoArgsConstructor -@AllArgsConstructor -public class SignRequestDto { - @NotBlank - private String data; - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/SignResponseDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/SignResponseDto.java deleted file mode 100644 index 5f020346a14..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/SignResponseDto.java +++ /dev/null @@ -1,32 +0,0 @@ -package io.mosip.kernel.signature.dto; - -import java.time.LocalDateTime; - -import com.fasterxml.jackson.annotation.JsonFormat; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * - * @author Srinivasan - * @since 1.0.0 - * - */ -@Data -@NoArgsConstructor -@AllArgsConstructor -public class SignResponseDto { - - /** - * encrypted data - */ - private String signature; - - /** - * response time. - */ - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") - private LocalDateTime timestamp; -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/SignatureRequestDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/SignatureRequestDto.java deleted file mode 100644 index 25e3869eb93..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/SignatureRequestDto.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * - * - * - * - */ -package io.mosip.kernel.signature.dto; - -import javax.validation.constraints.NotBlank; - -import io.mosip.kernel.keymanagerservice.constant.KeymanagerConstant; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * Crypto-Manager-Request model - * - * @author Urvil Joshi - * - * @since 1.0.0 - */ -@Data -@AllArgsConstructor -@NoArgsConstructor -@ApiModel(description = "Model representing a Crypto-Manager-Service Request") -public class SignatureRequestDto { - /** - * Application id of decrypting module - */ - @ApiModelProperty(notes = "Application id of decrypting module", example = "REGISTRATION", required = true) - @NotBlank(message = KeymanagerConstant.INVALID_REQUEST) - private String applicationId; - /** - * Refrence Id - */ - @ApiModelProperty(notes = "Refrence Id", example = "REF01") - private String referenceId; - /** - * Timestamp - */ - @ApiModelProperty(notes = "Timestamp as metadata", example = "2018-12-10T06:12:52.994Z", required = true) - @NotBlank(message = KeymanagerConstant.INVALID_REQUEST) - private String timeStamp; - /** - * Data in BASE64 encoding to encrypt/decrypt - */ - @ApiModelProperty(notes = "Data to sign", required = true) - @NotBlank(message = KeymanagerConstant.INVALID_REQUEST) - private String data; - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/SignatureResponseDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/SignatureResponseDto.java deleted file mode 100644 index ee9cf105a1c..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/SignatureResponseDto.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * - * - * - * - */ -package io.mosip.kernel.signature.dto; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * Crypto-Manager-Response model - * - * @author Urvil Joshi - * - * @since 1.0.0 - */ -@Data -@AllArgsConstructor -@NoArgsConstructor -@ApiModel(description = "Model representing a Crypto-Manager-Service Response") -public class SignatureResponseDto { - /** - * Data Encrypted/Decrypted in BASE64 encoding - */ - @ApiModelProperty(notes = "Data encrypted/decrypted in BASE64 encoding") - private String data; - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/TimestampRequestDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/TimestampRequestDto.java deleted file mode 100644 index 35b1b11366d..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/TimestampRequestDto.java +++ /dev/null @@ -1,26 +0,0 @@ -package io.mosip.kernel.signature.dto; - -import java.time.LocalDateTime; - -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.NotNull; - -import com.fasterxml.jackson.annotation.JsonFormat; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -@Data -@NoArgsConstructor -@AllArgsConstructor -public class TimestampRequestDto { - @NotBlank - private String signature; - @NotBlank - private String data; - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") - @NotNull - private LocalDateTime timestamp; - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/ValidatorResponseDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/ValidatorResponseDto.java deleted file mode 100644 index d8d2c82e72b..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/dto/ValidatorResponseDto.java +++ /dev/null @@ -1,21 +0,0 @@ -package io.mosip.kernel.signature.dto; - -import lombok.Data; - -/** - * - * @author Sagar Mahapatra - * @since 1.0.0 - * - */ -@Data -public class ValidatorResponseDto { - /** - * The validation request status. - */ - private String status; - /** - * The validation request message. - */ - private String message; -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/exception/CertificateNotValidException.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/exception/CertificateNotValidException.java deleted file mode 100644 index 09065e23981..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/exception/CertificateNotValidException.java +++ /dev/null @@ -1,41 +0,0 @@ -package io.mosip.kernel.signature.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; - -/** - * Class to handle exceptions for Signature verification certificate invalid. - * - * @author Mahammed Taheer - * @since 1.1.6 - * - */ -public class CertificateNotValidException extends BaseUncheckedException { - - /** - * Serializable version ID. - */ - private static final long serialVersionUID = -3069970234745966967L; - - /** - * Constructor for CryptoFailureException class. - * - * @param errorCode the error code. - * @param errorMessage the error message. - * @param rootCause the cause. - */ - public CertificateNotValidException(String errorCode, String errorMessage) { - super(errorCode, errorMessage); - } - - /** - * Constructor for CryptoFailureException class. - * - * @param errorCode the error code. - * @param errorMessage the error message. - * @param rootCause the cause. - */ - public CertificateNotValidException(String errorCode, String errorMessage, Throwable rootCause) { - super(errorCode, errorMessage, rootCause); - } - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/exception/PublicKeyParseException.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/exception/PublicKeyParseException.java deleted file mode 100644 index c6bc8f3efaa..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/exception/PublicKeyParseException.java +++ /dev/null @@ -1,30 +0,0 @@ -package io.mosip.kernel.signature.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; - -/** - * Class to handle exceptions for CRYPTO failure. - * - * @author Ritesh Sinha - * @since 1.0.0 - * - */ -public class PublicKeyParseException extends BaseUncheckedException { - - /** - * Serializable version ID. - */ - private static final long serialVersionUID = -3069970234745966967L; - - /** - * Constructor for CryptoFailureException class. - * - * @param errorCode the error code. - * @param errorMessage the error message. - * @param rootCause the cause. - */ - public PublicKeyParseException(String errorCode, String errorMessage, Throwable rootCause) { - super(errorCode, errorMessage, rootCause); - } - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/exception/RequestException.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/exception/RequestException.java deleted file mode 100644 index fd88b084650..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/exception/RequestException.java +++ /dev/null @@ -1,41 +0,0 @@ - -package io.mosip.kernel.signature.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; - -/** - * Customized exception class for invalid request provided by the user. - * - * @see io.mosip.kernel.core.exception.BaseUncheckedException - * @author Bal Vikash Sharma - * @since 1.0.0 - * - */ -public class RequestException extends BaseUncheckedException { - - /** - * Generated serial version id - */ - private static final long serialVersionUID = 2785372588639412708L; - - /** - * Constructor to initialize handler exception - * - * @param errorCode The error code for this exception - * @param errorMessage The error message for this exception - */ - public RequestException(String errorCode, String errorMessage) { - super(errorCode, errorMessage); - } - - /** - * Constructor the initialize Handler exception - * - * @param errorCode The error code for this exception - * @param errorMessage The error message for this exception - * @param rootCause the specified cause - */ - public RequestException(String errorCode, String errorMessage, Throwable rootCause) { - super(errorCode, errorMessage, rootCause); - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/exception/SignatureFailureException.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/exception/SignatureFailureException.java deleted file mode 100644 index 103982dbfd0..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/exception/SignatureFailureException.java +++ /dev/null @@ -1,30 +0,0 @@ -package io.mosip.kernel.signature.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; - -/** - * Class to handle exceptions for CRYPTO failure. - * - * @author Ritesh Sinha - * @since 1.0.0 - * - */ -public class SignatureFailureException extends BaseUncheckedException { - - /** - * Serializable version ID. - */ - private static final long serialVersionUID = -3069970234745966967L; - - /** - * Constructor for CryptoFailureException class. - * - * @param errorCode the error code. - * @param errorMessage the error message. - * @param rootCause the cause. - */ - public SignatureFailureException(String errorCode, String errorMessage, Throwable rootCause) { - super(errorCode, errorMessage, rootCause); - } - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/service/SignatureService.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/service/SignatureService.java deleted file mode 100644 index f091fb4c7e3..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/service/SignatureService.java +++ /dev/null @@ -1,52 +0,0 @@ -package io.mosip.kernel.signature.service; - -import io.mosip.kernel.core.signatureutil.model.SignatureResponse; -import io.mosip.kernel.signature.dto.JWTSignatureRequestDto; -import io.mosip.kernel.signature.dto.JWTSignatureResponseDto; -import io.mosip.kernel.signature.dto.JWTSignatureVerifyRequestDto; -import io.mosip.kernel.signature.dto.JWTSignatureVerifyResponseDto; -import io.mosip.kernel.signature.dto.PDFSignatureRequestDto; -import io.mosip.kernel.signature.dto.SignRequestDto; -import io.mosip.kernel.signature.dto.SignatureResponseDto; -import io.mosip.kernel.signature.dto.TimestampRequestDto; -import io.mosip.kernel.signature.dto.ValidatorResponseDto; - -public interface SignatureService { - /** - * Validate signature - * - * @param timestampRequestDto {@link TimestampRequestDto} - * @return {@link ValidatorResponseDto} - */ - @Deprecated - public ValidatorResponseDto validate(TimestampRequestDto timestampRequestDto); - - /** - * Sign Data. - * - * @param signRequestDto the signRequestDto - * @return the SignatureResponse - */ - @Deprecated - public SignatureResponse sign(SignRequestDto signRequestDto); - - - public SignatureResponseDto signPDF(PDFSignatureRequestDto request); - - /** - * JWT Signature. - * - * @param jwtSignRequestDto the jwtSignRequestDto - * @return the JWTSignatureResponseDto - */ - public JWTSignatureResponseDto jwtSign(JWTSignatureRequestDto jwtSignRequestDto); - - /** - * JWT Signature verification. - * - * @param jwtSignatureVerifyRequestDto the jwtSignatureVerifyRequestDto - * @return the JWTSignatureVerifyResponseDto - */ - public JWTSignatureVerifyResponseDto jwtVerify(JWTSignatureVerifyRequestDto jwtSignatureVerifyRequestDto); - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/service/impl/SignatureServiceImpl.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/service/impl/SignatureServiceImpl.java deleted file mode 100644 index c84cf5cc2d3..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/service/impl/SignatureServiceImpl.java +++ /dev/null @@ -1,420 +0,0 @@ -package io.mosip.kernel.signature.service.impl; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.security.GeneralSecurityException; -import java.security.KeyFactory; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.Security; -import java.security.cert.Certificate; -import java.security.cert.X509Certificate; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.X509EncodedKeySpec; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -import javax.crypto.SecretKey; - -import org.apache.commons.codec.binary.Base64; -import org.jose4j.jws.JsonWebSignature; -import org.jose4j.jwx.CompactSerializer; -import org.jose4j.lang.JoseException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Service; - - -import io.mosip.kernel.core.crypto.spi.CryptoCoreSpec; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.pdfgenerator.model.Rectangle; -import io.mosip.kernel.core.pdfgenerator.spi.PDFGenerator; -import io.mosip.kernel.core.signatureutil.model.SignatureResponse; -import io.mosip.kernel.core.util.CryptoUtil; -import io.mosip.kernel.core.util.DateUtils; -import io.mosip.kernel.core.util.JsonUtils; -import io.mosip.kernel.core.util.exception.JsonMappingException; -import io.mosip.kernel.core.util.exception.JsonParseException; -import io.mosip.kernel.keymanagerservice.constant.KeymanagerConstant; -import io.mosip.kernel.keymanagerservice.constant.KeymanagerErrorConstant; -import io.mosip.kernel.keymanagerservice.dto.KeyPairGenerateResponseDto; -import io.mosip.kernel.keymanagerservice.dto.PublicKeyResponse; -import io.mosip.kernel.keymanagerservice.dto.SignatureCertificate; -import io.mosip.kernel.keymanagerservice.exception.KeymanagerServiceException; -import io.mosip.kernel.keymanagerservice.logger.KeymanagerLogger; -import io.mosip.kernel.keymanagerservice.service.KeymanagerService; -import io.mosip.kernel.keymanagerservice.util.KeymanagerUtil; -import io.mosip.kernel.partnercertservice.dto.CertificateTrustRequestDto; -import io.mosip.kernel.partnercertservice.dto.CertificateTrustResponeDto; -import io.mosip.kernel.partnercertservice.service.spi.PartnerCertificateManagerService; -import io.mosip.kernel.signature.constant.SignatureConstant; -import io.mosip.kernel.signature.constant.SignatureErrorCode; -import io.mosip.kernel.signature.dto.JWTSignatureRequestDto; -import io.mosip.kernel.signature.dto.JWTSignatureResponseDto; -import io.mosip.kernel.signature.dto.JWTSignatureVerifyRequestDto; -import io.mosip.kernel.signature.dto.JWTSignatureVerifyResponseDto; -import io.mosip.kernel.signature.dto.PDFSignatureRequestDto; -import io.mosip.kernel.signature.dto.SignRequestDto; -import io.mosip.kernel.signature.dto.SignatureRequestDto; -import io.mosip.kernel.signature.dto.SignatureResponseDto; -import io.mosip.kernel.signature.dto.TimestampRequestDto; -import io.mosip.kernel.signature.dto.ValidatorResponseDto; -import io.mosip.kernel.signature.exception.CertificateNotValidException; -import io.mosip.kernel.signature.exception.PublicKeyParseException; -import io.mosip.kernel.signature.exception.RequestException; -import io.mosip.kernel.signature.exception.SignatureFailureException; -import io.mosip.kernel.signature.service.SignatureService; -import io.mosip.kernel.signature.util.SignatureUtil; - -/** - * @author Uday Kumar - * @author Urvil - * - */ -@Service -public class SignatureServiceImpl implements SignatureService { - - private static final Logger LOGGER = KeymanagerLogger.getLogger(SignatureServiceImpl.class); - - @Autowired - private KeymanagerService keymanagerService; - - @Autowired - private CryptoCoreSpec cryptoCore; - - @Value("${mosip.kernel.keygenerator.asymmetric-algorithm-name}") - private String asymmetricAlgorithmName; - - /** The sign applicationid. */ - @Value("${mosip.sign.applicationid:KERNEL}") - private String signApplicationid; - - /** The sign refid. */ - @Value("${mosip.sign.refid:SIGN}") - private String signRefid; - - @Value("${mosip.kernel.crypto.sign-algorithm-name:RS256}") - private String signAlgorithm; - - /** - * Utility to generate Metadata - */ - @Autowired - KeymanagerUtil keymanagerUtil; - - @Autowired - private PDFGenerator pdfGenerator; - - /** - * Instance for PartnerCertificateManagerService - */ - @Autowired - PartnerCertificateManagerService partnerCertManagerService; - - - @Override - public SignatureResponse sign(SignRequestDto signRequestDto) { - SignatureRequestDto signatureRequestDto = new SignatureRequestDto(); - signatureRequestDto.setApplicationId(signApplicationid); - signatureRequestDto.setReferenceId(signRefid); - signatureRequestDto.setData(signRequestDto.getData()); - String timestamp = DateUtils.getUTCCurrentDateTimeString(); - signatureRequestDto.setTimeStamp(timestamp); - SignatureResponseDto signatureResponseDTO = sign(signatureRequestDto); - return new SignatureResponse(signatureResponseDTO.getData(), DateUtils.convertUTCToLocalDateTime(timestamp)); - } - - private SignatureResponseDto sign(SignatureRequestDto signatureRequestDto) { - SignatureCertificate certificateResponse = keymanagerService.getSignatureCertificate( - signatureRequestDto.getApplicationId(), Optional.of(signatureRequestDto.getReferenceId()), - signatureRequestDto.getTimeStamp()); - keymanagerUtil.isCertificateValid(certificateResponse.getCertificateEntry(), - DateUtils.parseUTCToDate(signatureRequestDto.getTimeStamp())); - String encryptedSignedData = null; - if (certificateResponse.getCertificateEntry() != null) { - encryptedSignedData = cryptoCore.sign(signatureRequestDto.getData().getBytes(), - certificateResponse.getCertificateEntry().getPrivateKey()); - } - return new SignatureResponseDto(encryptedSignedData); - } - - @Override - public ValidatorResponseDto validate(TimestampRequestDto timestampRequestDto) { - - PublicKeyResponse publicKeyResponse = keymanagerService.getSignPublicKey(signApplicationid, - DateUtils.formatToISOString(timestampRequestDto.getTimestamp()), Optional.of(signRefid)); - boolean status; - try { - PublicKey publicKey = KeyFactory.getInstance(asymmetricAlgorithmName) - .generatePublic(new X509EncodedKeySpec(CryptoUtil.decodeBase64(publicKeyResponse.getPublicKey()))); - status = cryptoCore.verifySignature(timestampRequestDto.getData().getBytes(), - timestampRequestDto.getSignature(), publicKey); - } catch (InvalidKeySpecException | NoSuchAlgorithmException exception) { - throw new PublicKeyParseException(SignatureErrorCode.INTERNAL_SERVER_ERROR.getErrorCode(), - exception.getMessage(), exception); - } - - if (status) { - ValidatorResponseDto response = new ValidatorResponseDto(); - response.setMessage(SignatureConstant.VALIDATION_SUCCESSFUL); - response.setStatus(SignatureConstant.SUCCESS); - return response; - } else { - throw new SignatureFailureException(SignatureErrorCode.NOT_VALID.getErrorCode(), - SignatureErrorCode.NOT_VALID.getErrorMessage(), null); - } - - } - - @Override - public SignatureResponseDto signPDF(PDFSignatureRequestDto request) { - SignatureCertificate signatureCertificate = keymanagerService.getSignatureCertificate( - request.getApplicationId(), Optional.of(request.getReferenceId()), request.getTimeStamp()); - LOGGER.debug(KeymanagerConstant.SESSIONID, KeymanagerConstant.SESSIONID, KeymanagerConstant.SESSIONID, - "Signature fetched from hsm " + signatureCertificate); - Rectangle rectangle = new Rectangle(request.getLowerLeftX(), request.getLowerLeftY(), request.getUpperRightX(), - request.getUpperRightY()); - OutputStream outputStream; - try { - String providerName = signatureCertificate.getProviderName(); - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.SESSIONID, KeymanagerConstant.SESSIONID, - " Keystore Provider Name found: " + providerName); - - Arrays.stream(Security.getProviders()).forEach(x -> { - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.SESSIONID, KeymanagerConstant.SESSIONID, - "provider name " + x.getName()); - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.SESSIONID, KeymanagerConstant.SESSIONID, - "provider info " + x.getInfo()); - }); - LOGGER.info(KeymanagerConstant.SESSIONID, KeymanagerConstant.SESSIONID, KeymanagerConstant.SESSIONID, - "all providers "); - outputStream = pdfGenerator.signAndEncryptPDF(CryptoUtil.decodeBase64(request.getData()), rectangle, - request.getReason(), request.getPageNumber(), Security.getProvider(providerName), - signatureCertificate.getCertificateEntry(), request.getPassword()); - } catch (IOException | GeneralSecurityException e) { - throw new KeymanagerServiceException(KeymanagerErrorConstant.INTERNAL_SERVER_ERROR.getErrorCode(), - KeymanagerErrorConstant.INTERNAL_SERVER_ERROR.getErrorMessage() + " " + e.getMessage()); - } - SignatureResponseDto signatureResponseDto = new SignatureResponseDto(); - signatureResponseDto.setData(CryptoUtil.encodeBase64(((ByteArrayOutputStream) outputStream).toByteArray())); - return signatureResponseDto; - } - - @Override - public JWTSignatureResponseDto jwtSign(JWTSignatureRequestDto jwtSignRequestDto) { - LOGGER.info(SignatureConstant.SESSIONID, SignatureConstant.JWT_SIGN, SignatureConstant.BLANK, - "JWT Signature Request."); - - String reqDataToSign = jwtSignRequestDto.getDataToSign(); - if (!SignatureUtil.isDataValid(reqDataToSign)) { - LOGGER.error(SignatureConstant.SESSIONID, SignatureConstant.JWT_SIGN, SignatureConstant.BLANK, - "Provided Data to sign value is invalid."); - throw new RequestException(SignatureErrorCode.INVALID_INPUT.getErrorCode(), - SignatureErrorCode.INVALID_INPUT.getErrorMessage()); - } - - String decodedDataToSign = new String(CryptoUtil.decodeBase64(reqDataToSign)); - if (!SignatureUtil.isJsonValid(decodedDataToSign)) { - LOGGER.error(SignatureConstant.SESSIONID, SignatureConstant.JWT_SIGN, SignatureConstant.BLANK, - "Provided Data to sign value is invalid JSON."); - throw new RequestException(SignatureErrorCode.INVALID_JSON.getErrorCode(), - SignatureErrorCode.INVALID_JSON.getErrorMessage()); - } - - String timestamp = DateUtils.getUTCCurrentDateTimeString(); - String applicationId = jwtSignRequestDto.getApplicationId(); - String referenceId = jwtSignRequestDto.getReferenceId(); - if (!keymanagerUtil.isValidApplicationId(applicationId)) { - applicationId = signApplicationid; - referenceId = signRefid; - } - - boolean includePayload = SignatureUtil.isIncludeAttrsValid(jwtSignRequestDto.getIncludePayload()); - boolean includeCertificate = SignatureUtil.isIncludeAttrsValid(jwtSignRequestDto.getIncludeCertificate()); - boolean includeCertHash = SignatureUtil.isIncludeAttrsValid(jwtSignRequestDto.getIncludeCertHash()); - String certificateUrl = SignatureUtil.isDataValid( - jwtSignRequestDto.getCertificateUrl()) ? jwtSignRequestDto.getCertificateUrl(): null; - - SignatureCertificate certificateResponse = keymanagerService.getSignatureCertificate(applicationId, - Optional.of(referenceId), timestamp); - keymanagerUtil.isCertificateValid(certificateResponse.getCertificateEntry(), - DateUtils.parseUTCToDate(timestamp)); - String signedData = sign(decodedDataToSign, certificateResponse, includePayload, includeCertificate, - includeCertHash, certificateUrl); - JWTSignatureResponseDto responseDto = new JWTSignatureResponseDto(); - responseDto.setJwtSignedData(signedData); - responseDto.setTimestamp(DateUtils.getUTCCurrentDateTime()); - return responseDto; - } - - private String sign(String dataToSign, SignatureCertificate certificateResponse, boolean includePayload, - boolean includeCertificate, boolean includeCertHash, String certificateUrl) { - - JsonWebSignature jwSign = new JsonWebSignature(); - PrivateKey privateKey = certificateResponse.getCertificateEntry().getPrivateKey(); - X509Certificate x509Certificate = certificateResponse.getCertificateEntry().getChain()[0]; - 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(signAlgorithm); - jwSign.setKey(privateKey); - jwSign.setDoKeyValidation(false); - try { - if (includePayload) - return jwSign.getCompactSerialization(); - - return jwSign.getDetachedContentCompactSerialization(); - } catch (JoseException e) { - LOGGER.error(SignatureConstant.SESSIONID, SignatureConstant.JWT_SIGN, SignatureConstant.BLANK, - "Error occurred while Signing Data."); - throw new SignatureFailureException(SignatureErrorCode.SIGN_ERROR.getErrorCode(), - SignatureErrorCode.SIGN_ERROR.getErrorMessage(), e); - } - } - - public JWTSignatureVerifyResponseDto jwtVerify(JWTSignatureVerifyRequestDto jwtVerifyRequestDto) { - - String signedData = jwtVerifyRequestDto.getJwtSignatureData(); - if (!SignatureUtil.isDataValid(signedData)) { - LOGGER.error(SignatureConstant.SESSIONID, SignatureConstant.JWT_SIGN, SignatureConstant.BLANK, - "Provided Signed Data value is invalid."); - throw new RequestException(SignatureErrorCode.INVALID_INPUT.getErrorCode(), - SignatureErrorCode.INVALID_INPUT.getErrorMessage()); - } - - String encodedActualData = SignatureUtil.isDataValid(jwtVerifyRequestDto.getActualData()) - ? jwtVerifyRequestDto.getActualData() : null; - - String reqCertData = SignatureUtil.isDataValid(jwtVerifyRequestDto.getCertificateData()) - ? jwtVerifyRequestDto.getCertificateData(): null; - String applicationId = jwtVerifyRequestDto.getApplicationId(); - String referenceId = jwtVerifyRequestDto.getReferenceId(); - if (!keymanagerUtil.isValidApplicationId(applicationId)) { - applicationId = signApplicationid; - referenceId = signRefid; - } - - String[] jwtTokens = signedData.split(SignatureConstant.PERIOD, -1); - - boolean signatureValid = false; - Certificate certToVerify = certificateExistsInHeader(jwtTokens[0]); - if (Objects.nonNull(certToVerify)){ - signatureValid = verifySignature(jwtTokens, encodedActualData, certToVerify); - } else { - Certificate reqCertToVerify = getCertificateToVerify(reqCertData, applicationId, referenceId); - signatureValid = verifySignature(jwtTokens, encodedActualData, reqCertToVerify); - } - - JWTSignatureVerifyResponseDto responseDto = new JWTSignatureVerifyResponseDto(); - responseDto.setSignatureValid(signatureValid); - responseDto.setMessage(signatureValid ? SignatureConstant.VALIDATION_SUCCESSFUL : SignatureConstant.VALIDATION_FAILED); - responseDto.setTrustValid(validateTrust(jwtVerifyRequestDto, certToVerify, reqCertData)); - return responseDto; - } - - private Certificate getCertificateToVerify(String reqCertData, String applicationId, String referenceId) { - // 2nd precedence to consider certificate to use in signature verification (Certificate Data provided in request). - if (reqCertData != null) - return keymanagerUtil.convertToCertificate(reqCertData); - - // 3rd precedence to consider certificate to use in signature verification. (based on AppId & RefId) - KeyPairGenerateResponseDto certificateResponse = keymanagerService.getCertificate(applicationId, - Optional.of(referenceId)); - return keymanagerUtil.convertToCertificate(certificateResponse.getCertificate()); - } - - @SuppressWarnings("unchecked") - private Certificate certificateExistsInHeader(String jwtHeader) { - String jwtTokenHeader = new String(CryptoUtil.decodeBase64(jwtHeader)); - Map jwtTokenHeadersMap = null; - try { - jwtTokenHeadersMap = JsonUtils.jsonStringToJavaMap(jwtTokenHeader); - } catch (JsonParseException | JsonMappingException | io.mosip.kernel.core.exception.IOException e) { - LOGGER.error(SignatureConstant.SESSIONID, SignatureConstant.JWT_SIGN, SignatureConstant.BLANK, - "Provided Signed Data value is invalid."); - throw new RequestException(SignatureErrorCode.INVALID_VERIFY_INPUT.getErrorCode(), - SignatureErrorCode.INVALID_VERIFY_INPUT.getErrorMessage()); - } - // 1st precedence to consider certificate to use in signature verification (JWT Header). - if (jwtTokenHeadersMap.containsKey(SignatureConstant.JWT_HEADER_CERT_KEY)) { - LOGGER.info(SignatureConstant.SESSIONID, SignatureConstant.JWT_SIGN, SignatureConstant.BLANK, - "Certificate found in JWT Header."); - List certList = (List) jwtTokenHeadersMap.get(SignatureConstant.JWT_HEADER_CERT_KEY); - return keymanagerUtil.convertToCertificate(Base64.decodeBase64(certList.get(0))); - } - LOGGER.info(SignatureConstant.SESSIONID, SignatureConstant.JWT_SIGN, SignatureConstant.BLANK, - "Certificate not found in JWT Header."); - return null; - } - - private boolean verifySignature(String[] jwtTokens, String actualData, Certificate certToVerify) { - JsonWebSignature jws = new JsonWebSignature(); - try { - boolean validCert = SignatureUtil.isCertificateDatesValid((X509Certificate) certToVerify); - if (!validCert) { - LOGGER.error(SignatureConstant.SESSIONID, SignatureConstant.JWT_SIGN, SignatureConstant.BLANK, - "Error certificate dates are not valid."); - throw new CertificateNotValidException(SignatureErrorCode.CERT_NOT_VALID.getErrorCode(), - SignatureErrorCode.CERT_NOT_VALID.getErrorMessage()); - } - - PublicKey publicKey = certToVerify.getPublicKey(); - if (Objects.nonNull(actualData)) - jwtTokens[1] = actualData; - - jws.setCompactSerialization(CompactSerializer.serialize(jwtTokens)); - if (Objects.nonNull(publicKey)) - jws.setKey(publicKey); - - return jws.verifySignature(); - } catch (ArrayIndexOutOfBoundsException | JoseException e) { - LOGGER.error(SignatureConstant.SESSIONID, SignatureConstant.JWT_SIGN, SignatureConstant.BLANK, - "Provided Signed Data value is invalid."); - throw new SignatureFailureException(SignatureErrorCode.VERIFY_ERROR.getErrorCode(), - SignatureErrorCode.VERIFY_ERROR.getErrorMessage(), e); - } - } - - private String validateTrust(JWTSignatureVerifyRequestDto jwtVerifyRequestDto, Certificate headerCertificate, String reqCertData) { - - boolean validateTrust = SignatureUtil.isIncludeAttrsValid(jwtVerifyRequestDto.getValidateTrust()); - if (!validateTrust) { - return SignatureConstant.TRUST_NOT_VERIFIED; - } - - String domain = jwtVerifyRequestDto.getDomain(); - if(!SignatureUtil.isDataValid(domain)) - return SignatureConstant.TRUST_NOT_VERIFIED_NO_DOMAIN; - - String certData = null; - if (Objects.nonNull(headerCertificate)) { - certData = keymanagerUtil.getPEMFormatedData(headerCertificate); - } - String trustCertData = certData == null ? reqCertData : certData; - - if (trustCertData == null) - return SignatureConstant.TRUST_NOT_VERIFIED; - - CertificateTrustRequestDto trustRequestDto = new CertificateTrustRequestDto(); - trustRequestDto.setCertificateData(trustCertData); - trustRequestDto.setPartnerDomain(domain); - CertificateTrustResponeDto responseDto = partnerCertManagerService.verifyCertificateTrust(trustRequestDto); - - if (responseDto.getStatus()){ - return SignatureConstant.TRUST_VALID; - } - return SignatureConstant.TRUST_NOT_VALID; - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/util/SignatureUtil.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/util/SignatureUtil.java deleted file mode 100644 index 4f318529b56..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/signature/util/SignatureUtil.java +++ /dev/null @@ -1,78 +0,0 @@ -package io.mosip.kernel.signature.util; - -import java.io.IOException; -import java.security.cert.CertificateExpiredException; -import java.security.cert.CertificateNotYetValidException; -import java.security.cert.X509Certificate; -import java.time.ZoneId; -import java.util.Date; -import java.util.Objects; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.DateUtils; -import io.mosip.kernel.keymanagerservice.logger.KeymanagerLogger; -import io.mosip.kernel.signature.constant.SignatureConstant; - -/** - * Utility class for Signature Service - * - * @author Mahammed Taheer - * @since 1.2.0-SNAPSHOT - * - */ - -public class SignatureUtil { - - private static final Logger LOGGER = KeymanagerLogger.getLogger(SignatureUtil.class); - - - public static boolean isDataValid(String anyData) { - return anyData != null && !anyData.trim().isEmpty(); - } - - - public static boolean isJsonValid(String jsonInString) { - try { - ObjectMapper mapper = new ObjectMapper(); - mapper.readTree(jsonInString); - return true; - } catch (IOException e) { - LOGGER.error(SignatureConstant.SESSIONID, SignatureConstant.JWT_SIGN, SignatureConstant.BLANK, - "Provided JSON Data to sign value is invalid."); - } - return false; - } - - public static boolean isIncludeAttrsValid(Boolean includes) { - if (Objects.isNull(includes)) { - return SignatureConstant.DEFAULT_INCLUDES; - } - return includes; - } - - public static boolean isCertificateDatesValid(X509Certificate x509Cert) { - - try { - Date currentDate = Date.from(DateUtils.getUTCCurrentDateTime().atZone(ZoneId.systemDefault()).toInstant()); - x509Cert.checkValidity(currentDate); - return true; - } catch(CertificateExpiredException | CertificateNotYetValidException exp) { - LOGGER.info(SignatureConstant.SESSIONID, SignatureConstant.JWT_SIGN, - SignatureConstant.BLANK, - "Exception thrown when certificate dates are not valid."); - } - try { - // Checking both system default timezone & UTC Offset timezone. Issue found in reg-client during trust validation. - x509Cert.checkValidity(); - return true; - } catch(CertificateExpiredException | CertificateNotYetValidException exp) { - LOGGER.info(SignatureConstant.SESSIONID, SignatureConstant.JWT_SIGN, - SignatureConstant.BLANK, - "Exception thrown when certificate dates are not valid."); - } - return false; - } - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/tokenidgenerator/constant/TokenIDGeneratorErrorCode.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/tokenidgenerator/constant/TokenIDGeneratorErrorCode.java deleted file mode 100644 index f6e27b35e2e..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/tokenidgenerator/constant/TokenIDGeneratorErrorCode.java +++ /dev/null @@ -1,53 +0,0 @@ -package io.mosip.kernel.tokenidgenerator.constant; - -/** - * Error Code for Uin generator - * - * @author Dharmesh Khandelwal - * @since 1.0.0 - * - */ -public enum TokenIDGeneratorErrorCode { - INTERNAL_SERVER_ERROR("KER-UIG-005", "Internal Server Error"), - EMPTY_UIN_OR_PARTNERCODE_EXCEPTION("KER-TIG-010", "UIN and partner code cannot be empty"), - RUNTIME_EXCEPTION("KER-RIG-500", ""); - - /** - * The error code - */ - private final String errorCode; - /** - * The error message - */ - private final String errorMessage; - - /** - * Constructor to set error code and message - * - * @param errorCode the error code - * @param errorMessage the error message - */ - private TokenIDGeneratorErrorCode(final String errorCode, final String errorMessage) { - this.errorCode = errorCode; - this.errorMessage = errorMessage; - } - - /** - * Function to get error code - * - * @return {@link #errorCode} - */ - public String getErrorCode() { - return errorCode; - } - - /** - * Function to get the error message - * - * @return {@link #errorMessage}r - */ - public String getErrorMessage() { - return errorMessage; - } - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/tokenidgenerator/controller/TokenIDGeneratorController.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/tokenidgenerator/controller/TokenIDGeneratorController.java deleted file mode 100644 index bd70c0a7118..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/tokenidgenerator/controller/TokenIDGeneratorController.java +++ /dev/null @@ -1,31 +0,0 @@ -package io.mosip.kernel.tokenidgenerator.controller; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RestController; - -import io.mosip.kernel.core.http.ResponseFilter; -import io.mosip.kernel.core.http.ResponseWrapper; -import io.mosip.kernel.tokenidgenerator.dto.TokenIDResponseDto; -import io.mosip.kernel.tokenidgenerator.service.TokenIDGeneratorService; -import io.swagger.annotations.ApiParam; - -@RestController -public class TokenIDGeneratorController { - - @Autowired - private TokenIDGeneratorService tokenIDGeneratorService; - - @ResponseFilter - @GetMapping(value = "/{uin}/{partnercode}") - @PreAuthorize("hasAnyRole('ZONAL_ADMIN','GLOBAL_ADMIN','ID_AUTHENTICATION','RESIDENT')") - public ResponseWrapper generateTokenID(@ApiParam("uin of user") @PathVariable("uin") String uin, - @ApiParam("Partner Code") @PathVariable("partnercode") String partnerCode) { - ResponseWrapper response = new ResponseWrapper<>(); - response.setResponse(tokenIDGeneratorService.generateTokenID(uin.trim(), partnerCode.trim())); - return response; - } - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/tokenidgenerator/dto/TokenIDResponseDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/tokenidgenerator/dto/TokenIDResponseDto.java deleted file mode 100644 index 7b620bc84c1..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/tokenidgenerator/dto/TokenIDResponseDto.java +++ /dev/null @@ -1,24 +0,0 @@ -package io.mosip.kernel.tokenidgenerator.dto; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * Response dto for vid generator - * - * @author Dharmesh Khandelwal - * @since 1.0.0 - * - */ -@Data -@AllArgsConstructor -@NoArgsConstructor -public class TokenIDResponseDto { - - /** - * The tokenid - */ - private String tokenID; - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/tokenidgenerator/exception/TokenIdGeneratorServiceException.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/tokenidgenerator/exception/TokenIdGeneratorServiceException.java deleted file mode 100644 index cea7b6030db..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/tokenidgenerator/exception/TokenIdGeneratorServiceException.java +++ /dev/null @@ -1,16 +0,0 @@ -package io.mosip.kernel.tokenidgenerator.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; - -public class TokenIdGeneratorServiceException extends BaseUncheckedException { - - /** - * - */ - private static final long serialVersionUID = 7918298357691506740L; - - public TokenIdGeneratorServiceException(String errorCode, String errorMessage) { - super(errorCode, errorMessage); - } - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/tokenidgenerator/generator/TokenIDGenerator.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/tokenidgenerator/generator/TokenIDGenerator.java deleted file mode 100644 index e5053b192ae..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/tokenidgenerator/generator/TokenIDGenerator.java +++ /dev/null @@ -1,29 +0,0 @@ -package io.mosip.kernel.tokenidgenerator.generator; - -import java.math.BigInteger; - -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; - -import io.mosip.kernel.core.util.HMACUtils; - -@Component -public class TokenIDGenerator { - - @Value("${mosip.kernel.tokenid.uin.salt}") - private String uinSalt; - - @Value("${mosip.kernel.tokenid.length}") - private int tokenIDLength; - - @Value("${mosip.kernel.tokenid.partnercode.salt}") - private String partnerCodeSalt; - - public String generateTokenID(String uin, String partnerCode) { - String uinHash = HMACUtils.digestAsPlainText(HMACUtils.generateHash((uin + uinSalt).getBytes())); - String hash = HMACUtils - .digestAsPlainText(HMACUtils.generateHash((partnerCodeSalt + partnerCode + uinHash).getBytes())); - return new BigInteger(hash.getBytes()).toString().substring(0, tokenIDLength); - } - -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/tokenidgenerator/service/TokenIDGeneratorService.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/tokenidgenerator/service/TokenIDGeneratorService.java deleted file mode 100644 index 75005626315..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/tokenidgenerator/service/TokenIDGeneratorService.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * - */ -package io.mosip.kernel.tokenidgenerator.service; - -import io.mosip.kernel.tokenidgenerator.dto.TokenIDResponseDto; - -/** - * @author Urvil Joshi - * @author Ritesh Sinha - * @since 1.0.0 - * - */ -public interface TokenIDGeneratorService { - - /** - * @param uin - * @param partnerCode - * @return - */ - TokenIDResponseDto generateTokenID(String uin, String partnerCode); - -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/tokenidgenerator/service/impl/TokenIDGeneratorServiceImpl.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/tokenidgenerator/service/impl/TokenIDGeneratorServiceImpl.java deleted file mode 100644 index c413f572ea5..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/tokenidgenerator/service/impl/TokenIDGeneratorServiceImpl.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * - */ -package io.mosip.kernel.tokenidgenerator.service.impl; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import io.mosip.kernel.core.idgenerator.exception.TokenIdGeneratorException; -import io.mosip.kernel.tokenidgenerator.constant.TokenIDGeneratorErrorCode; -import io.mosip.kernel.tokenidgenerator.dto.TokenIDResponseDto; -import io.mosip.kernel.tokenidgenerator.generator.TokenIDGenerator; -import io.mosip.kernel.tokenidgenerator.service.TokenIDGeneratorService; - -/** - * @author Urvil Joshi - * @author Ritesh Sinha - * @since 1.0.0 - */ -@Component -public class TokenIDGeneratorServiceImpl implements TokenIDGeneratorService { - - @Autowired - private TokenIDGenerator tokenIDGenerator; - - @Override - public TokenIDResponseDto generateTokenID(String uin, String partnerCode) { - if (uin.isEmpty() || partnerCode.isEmpty()) { - throw new TokenIdGeneratorException( - TokenIDGeneratorErrorCode.EMPTY_UIN_OR_PARTNERCODE_EXCEPTION.getErrorCode(), - TokenIDGeneratorErrorCode.EMPTY_UIN_OR_PARTNERCODE_EXCEPTION.getErrorMessage()); - } - TokenIDResponseDto tokenIDResponseDto = new TokenIDResponseDto(); - tokenIDResponseDto.setTokenID(tokenIDGenerator.generateTokenID(uin, partnerCode)); - return tokenIDResponseDto; - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/constant/ZKCryptoErrorConstants.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/constant/ZKCryptoErrorConstants.java deleted file mode 100644 index 68295bc1708..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/constant/ZKCryptoErrorConstants.java +++ /dev/null @@ -1,56 +0,0 @@ -package io.mosip.kernel.zkcryptoservice.constant; - -/** - * This ENUM provides all the constant identified for ZKCryptoManager errors. - * - * @author Mahammed Taheer - * @version 1.2.0-SNAPSHOT - * - */ -public enum ZKCryptoErrorConstants { - - RANDOM_KEY_CIPHER_FAILED("KER-ZKC-001", "Failed to Encrypt/Decrypt Random Key."), - - NO_UNIQUE_ALIAS("KER-ZKC-002", "No unique alias is found."), - - EMPTY_DATA_ERROR("KER-ZKC-003", "Data attributes Empty."), - - DATA_CIPHER_OPS_ERROR("KER-ZKC-004", "Data Encryption/Decryption Error."), - - KEY_DERIVATION_ERROR("KER-ZKC-005", "Error Key derivation."), - - INVALID_ENCRYPTED_RANDOM_KEY("KER-ZKC-006", "Invalid encrypted random Key."); - - /** - * The error code. - */ - private final String errorCode; - - /** - * The error message. - */ - private final String errorMessage; - - /** - * @param errorCode The error code to be set. - * @param errorMessage The error message to be set. - */ - private ZKCryptoErrorConstants(String errorCode, String errorMessage) { - this.errorCode = errorCode; - this.errorMessage = errorMessage; - } - - /** - * @return The error code. - */ - public String getErrorCode() { - return errorCode; - } - - /** - * @return The error message. - */ - public String getErrorMessage() { - return errorMessage; - } -} diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/constant/ZKCryptoManagerConstants.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/constant/ZKCryptoManagerConstants.java deleted file mode 100644 index 4a10a476f59..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/constant/ZKCryptoManagerConstants.java +++ /dev/null @@ -1,50 +0,0 @@ -package io.mosip.kernel.zkcryptoservice.constant; - -/** - * Constants for Zero Knowledge Crypto Manager. - * - * @author Mahammed Taheer - * @since 1.1.2 - * - */ -public interface ZKCryptoManagerConstants { - - int GCM_NONCE_LENGTH = 12; - - int GCM_AAD_LENGTH = 32; - - int GCM_TAG_LENGTH = 16; - - int INT_BYTES_LEN = 4; - - int GCM_NONCE_PLUS_INT_BYTES_LEN = INT_BYTES_LEN + GCM_NONCE_LENGTH; - - int GCM_NONCE_PLUS_INT_BYTES_PLUS_GCM_AAD_LEN = INT_BYTES_LEN + GCM_NONCE_LENGTH + GCM_AAD_LENGTH; - - String ACTIVE_STATUS = "Active"; - - String SESSIONID = "zkSessionID"; - - String ZK_ENCRYPT = "zkEncrypt"; - - String ZK_DECRYPT = "zkDecrypt"; - - String RANDOM_KEY = "RandomKey"; - - String MASTER_KEY = "MasterKey"; - - String EMPTY = ""; - - String MASTER_CURRENT_ALIAS = "ZKMasterKeyAlias"; - - String DATA_CIPHER = "DataCipher"; - - String DERIVE_KEY = "DeriveKey"; - - String HASH_ALGO = "SHA-256"; - - String ENCRYPT_RANDOM_KEY = "EncryptRandomKey"; - - String RE_ENCRYPT_RANDOM_KEY = "Re-EncryptRandomKey"; - -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/controller/ZKCryptoManagerController.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/controller/ZKCryptoManagerController.java deleted file mode 100644 index 727bd71e657..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/controller/ZKCryptoManagerController.java +++ /dev/null @@ -1,94 +0,0 @@ -package io.mosip.kernel.zkcryptoservice.controller; - -import javax.validation.Valid; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.CrossOrigin; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -import io.mosip.kernel.core.http.RequestWrapper; -import io.mosip.kernel.core.http.ResponseFilter; -import io.mosip.kernel.core.http.ResponseWrapper; -import io.mosip.kernel.cryptomanager.dto.CryptomanagerRequestDto; -import io.mosip.kernel.cryptomanager.dto.CryptomanagerResponseDto; -import io.mosip.kernel.zkcryptoservice.dto.ReEncryptRandomKeyResponseDto; -import io.mosip.kernel.zkcryptoservice.dto.ZKCryptoRequestDto; -import io.mosip.kernel.zkcryptoservice.dto.ZKCryptoResponseDto; -import io.mosip.kernel.zkcryptoservice.service.spi.ZKCryptoManagerService; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiParam; - -/** - * Rest Controller for Zero Knowledge Crypto-Manager-Service - * - * @author Mahammed Taheer - * - * @since 1.1.2 - */ - -@CrossOrigin -@RestController -@Api(value = "Operation related to Zero Knowledge Encryption and Decryption", tags = { "zkcryptomanager" }) -public class ZKCryptoManagerController { - - /** - * Instance for KeymanagerService - */ - @Autowired - ZKCryptoManagerService zkCryptoManagerService; - - /** - * Controller for Encrypt the data - * - * @param zkCryptoRequestDto {@link ZKCryptoRequestDto} request - * @return {@link ZKCryptoResponseDto} encrypted Data - */ - @PreAuthorize("hasAnyRole('ZONAL_ADMIN','GLOBAL_ADMIN','INDIVIDUAL','ID_AUTHENTICATION','TEST', 'REGISTRATION_ADMIN', 'REGISTRATION_SUPERVISOR', 'REGISTRATION_OFFICER', 'REGISTRATION_PROCESSOR','PRE_REGISTRATION_ADMIN','RESIDENT')") - @ResponseFilter - @PostMapping(value = "/zkEncrypt", produces = "application/json") - public ResponseWrapper zkEncrypt( - @ApiParam("List of ZK Data Attributes to Encrypt.") @RequestBody @Valid RequestWrapper zkCryptoRequestDto) { - - ResponseWrapper response = new ResponseWrapper<>(); - response.setResponse(zkCryptoManagerService.zkEncrypt(zkCryptoRequestDto.getRequest())); - return response; - } - - /** - * Controller for Decrypt the data - * - * @param zkCryptoRequestDto {@link ZKCryptoRequestDto} request - * @return {@link ZKCryptoResponseDto} decrypted Data - */ - @PreAuthorize("hasAnyRole('ZONAL_ADMIN','GLOBAL_ADMIN','INDIVIDUAL','ID_AUTHENTICATION', 'TEST', 'REGISTRATION_ADMIN', 'REGISTRATION_SUPERVISOR', 'REGISTRATION_OFFICER', 'REGISTRATION_PROCESSOR','PRE_REGISTRATION_ADMIN','RESIDENT')") - @ResponseFilter - @PostMapping(value = "/zkDecrypt", produces = "application/json") - public ResponseWrapper zkDecrypt( - @ApiParam("List of ZK Data Attributes to Decrypt.") @RequestBody @Valid RequestWrapper zkCryptoRequestDto) { - ResponseWrapper response = new ResponseWrapper<>(); - response.setResponse(zkCryptoManagerService.zkDecrypt(zkCryptoRequestDto.getRequest())); - return response; - } - - - /** - * Controller for Decrypt the data - * - * @param cryptomanagerRequestDto {@link CryptomanagerRequestDto} request - * @return {@link CryptomanagerResponseDto} decrypted Data - */ - @PreAuthorize("hasAnyRole('ZONAL_ADMIN','GLOBAL_ADMIN','INDIVIDUAL','ID_AUTHENTICATION', 'TEST', 'REGISTRATION_ADMIN', 'REGISTRATION_SUPERVISOR', 'REGISTRATION_OFFICER', 'REGISTRATION_PROCESSOR','PRE_REGISTRATION_ADMIN','RESIDENT')") - @ResponseFilter - @PostMapping(value = "/zkReEncryptRandomKey", produces = "application/json") - public ResponseWrapper zkReEncryptRandomKey( - @ApiParam("Random key to re-encrypt") @RequestParam("encryptedKey") String encryptedKey) { - - ResponseWrapper response = new ResponseWrapper<>(); - response.setResponse(zkCryptoManagerService.zkReEncryptRandomKey(encryptedKey)); - return response; - } -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/dto/CryptoDataDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/dto/CryptoDataDto.java deleted file mode 100644 index 3011610326c..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/dto/CryptoDataDto.java +++ /dev/null @@ -1,38 +0,0 @@ -package io.mosip.kernel.zkcryptoservice.dto; - -import javax.validation.constraints.NotBlank; - -import io.mosip.kernel.keymanagerservice.constant.KeymanagerConstant; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * Crypto Data for encrypt/decrypt. - * - * @author Mahammed Taheer - * @since 1.1.2 - */ -@Data -@AllArgsConstructor -@NoArgsConstructor -@ApiModel(description = "Model representing a identifier & value for encrypt/decrypt") -public class CryptoDataDto { - - /** - * identifier for the value to encrypt/decrypt. - */ - @ApiModelProperty(notes = "Identifier", example = "name", required = true) - @NotBlank(message = KeymanagerConstant.INVALID_REQUEST) - private String identifier; - - /** - * actual data to encrypt/decrypt. - */ - @ApiModelProperty(notes = "Data to Encrypt/Decrypt", example = "Plain/Encrypted String", required = true) - @NotBlank(message = KeymanagerConstant.INVALID_REQUEST) - private String value; - -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/dto/ReEncryptRandomKeyResponseDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/dto/ReEncryptRandomKeyResponseDto.java deleted file mode 100644 index ef85adf7072..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/dto/ReEncryptRandomKeyResponseDto.java +++ /dev/null @@ -1,20 +0,0 @@ -package io.mosip.kernel.zkcryptoservice.dto; - -import lombok.Data; - -/** - * DTO class for Re-Encrypt Random Key response. - * - * @author Mahammed Taheer - * @since 1.1.2 - * - */ -@Data -public class ReEncryptRandomKeyResponseDto { - - /** - * Status of upload certificate. - */ - private String encryptedKey; - -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/dto/ZKCryptoRequestDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/dto/ZKCryptoRequestDto.java deleted file mode 100644 index 98e52caaa8e..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/dto/ZKCryptoRequestDto.java +++ /dev/null @@ -1,40 +0,0 @@ -package io.mosip.kernel.zkcryptoservice.dto; - - -import java.util.List; -import javax.validation.constraints.NotBlank; - -import io.mosip.kernel.keymanagerservice.constant.KeymanagerConstant; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * Zero Knowledge Encrypt/Decrypt Request DTO. - * - * @author Mahammed Taheer - * @since 1.1.2 -*/ - -@Data -@AllArgsConstructor -@NoArgsConstructor -@ApiModel(description = "Model representing request a list of data attributes for encrypt/decrypt") -public class ZKCryptoRequestDto { - - /** - * Id used in zero knowledge. - */ - @ApiModelProperty(notes = "Resident ID(VID/UIN)", required = true) - @NotBlank(message = KeymanagerConstant.INVALID_REQUEST) - String id; - - /** - * zero knowledge Data Attributes to encrypt/decrypt. - */ - @ApiModelProperty(notes = "ZK Data Attributes", required = true) - List zkDataAttributes; - -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/dto/ZKCryptoResponseDto.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/dto/ZKCryptoResponseDto.java deleted file mode 100644 index e713f40ef2c..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/dto/ZKCryptoResponseDto.java +++ /dev/null @@ -1,37 +0,0 @@ -package io.mosip.kernel.zkcryptoservice.dto; - -import java.util.List; - -import io.swagger.annotations.ApiModel; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * Zero Knowledge Encrypt/Decrypt Request DTO. - * - * @author Mahammed Taheer - * @since 1.1.2 -*/ - -@Data -@AllArgsConstructor -@NoArgsConstructor -@ApiModel(description = "Model representing response a list of data attributes for encrypt/decrypt") -public class ZKCryptoResponseDto { - - /** - * zero knowledge Data Attributes to encrypt/decrypt. - */ - List zkDataAttributes; - - /** - * Encrypted Random Key - */ - String encryptedRandomKey; - - /** - * Index of the random key used. - */ - String rankomKeyIndex; -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/exception/ZKCryptoException.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/exception/ZKCryptoException.java deleted file mode 100644 index c4a384e8674..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/exception/ZKCryptoException.java +++ /dev/null @@ -1,38 +0,0 @@ -package io.mosip.kernel.zkcryptoservice.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; - -/** - * Custom Exception Class in case of ZKCryptoException - * - * @author Mahammed Taheer - * @since 1.1.2 - * - */ -public class ZKCryptoException extends BaseUncheckedException { - - /** - * Generated serial version id - */ - private static final long serialVersionUID = 8621530697947108810L; - - /** - * Constructor the initialize Handler exception - * - * @param errorCode The errorcode for this exception - * @param errorMessage The error message for this exception - */ - public ZKCryptoException(String errorCode, String errorMessage) { - super(errorCode, errorMessage); - } - - /** - * @param errorCode The errorcode for this exception - * @param errorMessage The error message for this exception - * @param rootCause cause of the error occoured - */ - public ZKCryptoException(String errorCode, String errorMessage, Throwable rootCause) { - super(errorCode, errorMessage, rootCause); - } - -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/exception/ZKKeyDerivationException.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/exception/ZKKeyDerivationException.java deleted file mode 100644 index 81eff7739c4..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/exception/ZKKeyDerivationException.java +++ /dev/null @@ -1,38 +0,0 @@ -package io.mosip.kernel.zkcryptoservice.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; - -/** - * Custom Exception Class in case of Key Derivation Exception. - * - * @author Mahammed Taheer - * @since 1.0.0 - * - */ -public class ZKKeyDerivationException extends BaseUncheckedException { - - /** - * Generated serial version id - */ - private static final long serialVersionUID = 8621530697947108810L; - - /** - * Constructor the initialize Handler exception - * - * @param errorCode The errorcode for this exception - * @param errorMessage The error message for this exception - */ - public ZKKeyDerivationException(String errorCode, String errorMessage) { - super(errorCode, errorMessage); - } - - /** - * @param errorCode The errorcode for this exception - * @param errorMessage The error message for this exception - * @param rootCause cause of the error occoured - */ - public ZKKeyDerivationException(String errorCode, String errorMessage, Throwable rootCause) { - super(errorCode, errorMessage, rootCause); - } - -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/exception/ZKRandomKeyDecryptionException.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/exception/ZKRandomKeyDecryptionException.java deleted file mode 100644 index 0f5781b2248..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/exception/ZKRandomKeyDecryptionException.java +++ /dev/null @@ -1,29 +0,0 @@ -package io.mosip.kernel.zkcryptoservice.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; - -/** - * Custom Exception Class in case of Random Key Decryption Exception. - * - * @author Mahammed Taheer - * @since 1.0.0 - * - */ -public class ZKRandomKeyDecryptionException extends BaseUncheckedException { - - /** - * Generated serial version id - */ - private static final long serialVersionUID = 8621530697947108810L; - - /** - * Constructor the initialize Handler exception - * - * @param errorCode The errorcode for this exception - * @param errorMessage The error message for this exception - */ - public ZKRandomKeyDecryptionException(String errorCode, String errorMessage) { - super(errorCode, errorMessage); - } - -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/service/impl/ZKCryptoManagerServiceImpl.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/service/impl/ZKCryptoManagerServiceImpl.java deleted file mode 100644 index ffeb8c1f3e7..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/service/impl/ZKCryptoManagerServiceImpl.java +++ /dev/null @@ -1,407 +0,0 @@ -package io.mosip.kernel.zkcryptoservice.service.impl; - -import java.nio.ByteBuffer; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.Key; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.cert.X509Certificate; -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Base64; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.concurrent.ThreadLocalRandom; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import javax.crypto.BadPaddingException; -import javax.crypto.Cipher; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; -import javax.crypto.SecretKey; -import javax.crypto.spec.GCMParameterSpec; -import javax.crypto.spec.SecretKeySpec; - -import org.springframework.beans.factory.InitializingBean; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import io.mosip.kernel.core.crypto.spi.CryptoCoreSpec; -import io.mosip.kernel.core.keymanager.spi.KeyStore; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.CryptoUtil; -import io.mosip.kernel.core.util.DateUtils; -import io.mosip.kernel.cryptomanager.util.CryptomanagerUtils; -import io.mosip.kernel.keymanagerservice.constant.KeymanagerConstant; -import io.mosip.kernel.keymanagerservice.dto.SymmetricKeyRequestDto; -import io.mosip.kernel.keymanagerservice.entity.KeyAlias; -import io.mosip.kernel.keymanagerservice.exception.NoUniqueAliasException; -import io.mosip.kernel.keymanagerservice.helper.KeymanagerDBHelper; -import io.mosip.kernel.keymanagerservice.logger.KeymanagerLogger; -import io.mosip.kernel.keymanagerservice.repository.DataEncryptKeystoreRepository; -import io.mosip.kernel.keymanagerservice.repository.KeyAliasRepository; -import io.mosip.kernel.keymanagerservice.repository.KeyStoreRepository; -import io.mosip.kernel.keymanagerservice.service.KeymanagerService; -import io.mosip.kernel.keymanagerservice.util.KeymanagerUtil; -import io.mosip.kernel.zkcryptoservice.constant.ZKCryptoErrorConstants; -import io.mosip.kernel.zkcryptoservice.constant.ZKCryptoManagerConstants; -import io.mosip.kernel.zkcryptoservice.dto.CryptoDataDto; -import io.mosip.kernel.zkcryptoservice.dto.ReEncryptRandomKeyResponseDto; -import io.mosip.kernel.zkcryptoservice.dto.ZKCryptoRequestDto; -import io.mosip.kernel.zkcryptoservice.dto.ZKCryptoResponseDto; -import io.mosip.kernel.zkcryptoservice.exception.ZKCryptoException; -import io.mosip.kernel.zkcryptoservice.exception.ZKKeyDerivationException; -import io.mosip.kernel.zkcryptoservice.exception.ZKRandomKeyDecryptionException; -import io.mosip.kernel.zkcryptoservice.service.spi.ZKCryptoManagerService; - -/** - * Service Implementation for {@link ZKCryptoManagerService} interface - * - * @author Mahammed Taheer - * - * @since 1.1.2 - */ -@Service -@Transactional -public class ZKCryptoManagerServiceImpl implements ZKCryptoManagerService, InitializingBean { - - private static final Logger LOGGER = KeymanagerLogger.getLogger(ZKCryptoManagerServiceImpl.class); - - @Value("${mosip.kernel.crypto.symmetric-algorithm-name}") - private String aesGCMTransformation; - - @Value("${mosip.kernel.zkcrypto.masterkey.application.id}") - private String masterKeyAppId; - - @Value("${mosip.kernel.zkcrypto.masterkey.reference.id}") - private String masterKeyRefId; - - @Value("${mosip.kernel.zkcrypto.publickey.application.id}") - private String pubKeyApplicationId; - - @Value("${mosip.kernel.zkcrypto.publickey.reference.id}") - private String pubKeyReferenceId; - - @Value("${mosip.kernel.zkcrypto.wrap.algorithm-name}") - private String aesECBTransformation; - - @Value("${mosip.kernel.zkcrypto.derive.encrypt.algorithm-name}") - private String aesECBPKCS5Transformation; - - @Autowired - private DataEncryptKeystoreRepository dataEncryptKeystoreRepository; - - /** - * KeymanagerDBHelper instance to handle all DB operations - */ - @Autowired - private KeymanagerDBHelper dbHelper; - - @Autowired - private KeyStoreRepository keyStoreRepository; - - /** - * Keystore instance to handles and store cryptographic keys. - */ - @Autowired - private KeyStore keyStore; - - /** - * Utility to generate Metadata - */ - @Autowired - KeymanagerUtil keymanagerUtil; - - /** The key manager. */ - @Autowired - private KeymanagerService keyManagerService; - - /** - * {@link CryptomanagerUtils} instance - */ - @Autowired - CryptomanagerUtils cryptomanagerUtil; - - - @Autowired - private CryptoCoreSpec cryptoCore; - - @Override - public void afterPropertiesSet() throws Exception { - // temporary fix to resolve issue occurring for first time(softhsm)/third time(real hsm) symmetric key retrival from HSM. - for (int i = 0; i < 3; i++) { - try { - LOGGER.info(ZKCryptoManagerConstants.SESSIONID, ZKCryptoManagerConstants.ZK_ENCRYPT, - ZKCryptoManagerConstants.EMPTY, "Temporary solution to handle the first time decryption failure."); - getDecryptedRandomKey("Tk8tU0VDRVJULUFWQUlMQUJMRS1URU1QLUZJWElORy0="); - } catch(Throwable e) { - // ignore - } - } - } - - @Override - public ZKCryptoResponseDto zkEncrypt(ZKCryptoRequestDto cryptoRequestDto) { - LOGGER.info(ZKCryptoManagerConstants.SESSIONID, ZKCryptoManagerConstants.ZK_ENCRYPT, - ZKCryptoManagerConstants.EMPTY, "Zero Knowledge Encryption."); - String id = cryptoRequestDto.getId(); - Stream cryptoDataList = cryptoRequestDto.getZkDataAttributes().stream(); - int randomKeyIndex = getRandomKeyIndex(); - String encryptedKeyData = dataEncryptKeystoreRepository.findKeyById(randomKeyIndex); - Key secretRandomKey = getDecryptedRandomKey(encryptedKeyData); - Key derivedKey = getDerivedKey(id, secretRandomKey); - - SecureRandom sRandom = new SecureRandom(); - List responseCryptoData = new ArrayList<>(); - cryptoDataList.forEach(reqCryptoData -> { - String identifier = reqCryptoData.getIdentifier(); - byte[] dataToEncrypt = reqCryptoData.getValue().getBytes(); - byte[] nonce = new byte[ZKCryptoManagerConstants.GCM_NONCE_LENGTH]; - byte[] aad = new byte[ZKCryptoManagerConstants.GCM_AAD_LENGTH]; - - sRandom.nextBytes(nonce); - sRandom.nextBytes(aad); - - byte[] encryptedData = doCipherOps(derivedKey, dataToEncrypt, Cipher.ENCRYPT_MODE, nonce, aad); - byte[] dbIndexBytes = getIndexBytes(randomKeyIndex); - responseCryptoData.add(getResponseCryptoData(encryptedData, dbIndexBytes, nonce, aad, identifier)); - }); - ZKCryptoResponseDto cryptoResponseDto = new ZKCryptoResponseDto(); - cryptoResponseDto.setRankomKeyIndex(Integer.toString(randomKeyIndex)); - cryptoResponseDto.setZkDataAttributes(responseCryptoData); - cryptoResponseDto.setEncryptedRandomKey(encryptRandomKey(secretRandomKey)); - keymanagerUtil.destoryKey((SecretKey) secretRandomKey); - return cryptoResponseDto; - } - - @Override - public ZKCryptoResponseDto zkDecrypt(ZKCryptoRequestDto cryptoRequestDto) { - LOGGER.info(ZKCryptoManagerConstants.SESSIONID, ZKCryptoManagerConstants.ZK_DECRYPT, - ZKCryptoManagerConstants.EMPTY, "Zero Knowledge Decryption."); - String id = cryptoRequestDto.getId(); - Stream cryptoDataList = cryptoRequestDto.getZkDataAttributes().stream(); - - List responseCryptoData = new ArrayList<>(); - cryptoDataList.forEach(reqCryptoData -> { - String identifier = reqCryptoData.getIdentifier(); - String dataToDecrypt = reqCryptoData.getValue(); - - byte[] decodedData = CryptoUtil.decodeBase64(dataToDecrypt); - byte[] dbIndexBytes = Arrays.copyOfRange(decodedData, 0, ZKCryptoManagerConstants.INT_BYTES_LEN); - byte[] nonce = Arrays.copyOfRange(decodedData, ZKCryptoManagerConstants.INT_BYTES_LEN, - ZKCryptoManagerConstants.GCM_NONCE_PLUS_INT_BYTES_LEN); - byte[] aad = Arrays.copyOfRange(decodedData, ZKCryptoManagerConstants.GCM_NONCE_PLUS_INT_BYTES_LEN, - ZKCryptoManagerConstants.GCM_NONCE_PLUS_INT_BYTES_PLUS_GCM_AAD_LEN); - byte[] encryptedData = Arrays.copyOfRange(decodedData, ZKCryptoManagerConstants.GCM_NONCE_PLUS_INT_BYTES_PLUS_GCM_AAD_LEN, - decodedData.length); - - int randomKeyIndex = getIndexInt(dbIndexBytes); - String encryptedKeyData = dataEncryptKeystoreRepository.findKeyById(randomKeyIndex); - Key secretRandomKey = getDecryptedRandomKey(encryptedKeyData); - Key derivedKey = getDerivedKey(id, secretRandomKey); - byte[] decryptedData = doCipherOps(derivedKey, encryptedData, Cipher.DECRYPT_MODE, nonce, aad); - responseCryptoData.add(getResponseCryptoData(decryptedData, identifier)); - keymanagerUtil.destoryKey((SecretKey) secretRandomKey); - }); - ZKCryptoResponseDto cryptoResponseDto = new ZKCryptoResponseDto(); - cryptoResponseDto.setZkDataAttributes(responseCryptoData); - return cryptoResponseDto; - } - - private int getRandomKeyIndex() { - List indexes = dataEncryptKeystoreRepository.getIdsByKeyStatus(ZKCryptoManagerConstants.ACTIVE_STATUS); - int randomNum = ThreadLocalRandom.current().nextInt(0, indexes.size() + 1); - return indexes.get(randomNum); - } - - private int getIndexInt(byte[] indexBytes) { - ByteBuffer bBuff = ByteBuffer.wrap(indexBytes); - return bBuff.getInt(); - } - - private Key getDecryptedRandomKey(String encryptedKey) { - LOGGER.info(ZKCryptoManagerConstants.SESSIONID, ZKCryptoManagerConstants.RANDOM_KEY, - ZKCryptoManagerConstants.RANDOM_KEY, "Random Key Decryption."); - byte[] unwrappedKey = doFinal(encryptedKey, Cipher.DECRYPT_MODE); - return new SecretKeySpec(unwrappedKey, 0, unwrappedKey.length, "AES"); - - } - - private String getEncryptedRandomKey(String randomKey) { - LOGGER.info(ZKCryptoManagerConstants.SESSIONID, ZKCryptoManagerConstants.RANDOM_KEY, - ZKCryptoManagerConstants.RANDOM_KEY, "Random Key Encryption."); - byte[] wrappedKey = doFinal(randomKey, Cipher.ENCRYPT_MODE); - return Base64.getEncoder().encodeToString(wrappedKey); - } - - private byte[] doFinal(String secretData, int mode) { - try { - Cipher cipher = Cipher.getInstance(aesECBTransformation); - - byte[] secretDataBytes = Base64.getDecoder().decode(secretData); - cipher.init(mode, getMasterKeyFromHSM()); - return cipher.doFinal(secretDataBytes, 0, secretDataBytes.length); - } catch(NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException - | IllegalBlockSizeException | BadPaddingException | IllegalArgumentException e) { - LOGGER.error(ZKCryptoManagerConstants.SESSIONID, ZKCryptoManagerConstants.RANDOM_KEY, - ZKCryptoManagerConstants.EMPTY, "Error Cipher Operations of Random Key."); - throw new ZKKeyDerivationException(ZKCryptoErrorConstants.RANDOM_KEY_CIPHER_FAILED.getErrorCode(), - ZKCryptoErrorConstants.RANDOM_KEY_CIPHER_FAILED.getErrorMessage(), e); - } - } - - private Key getDerivedKey(String id, Key key) { - try { - LOGGER.info(ZKCryptoManagerConstants.SESSIONID, ZKCryptoManagerConstants.DERIVE_KEY, - ZKCryptoManagerConstants.DERIVE_KEY, "Derive key with Random Key."); - byte[] idBytes = id.getBytes(); - MessageDigest mDigest = MessageDigest.getInstance(ZKCryptoManagerConstants.HASH_ALGO); - mDigest.update(idBytes, 0, idBytes.length); - byte[] hashBytes = mDigest.digest(); - - Cipher cipher = Cipher.getInstance(aesECBTransformation); - cipher.init(Cipher.ENCRYPT_MODE, key); - byte[] encryptedData = cipher.doFinal(hashBytes, 0, hashBytes.length); - return new SecretKeySpec(encryptedData, 0, encryptedData.length, "AES"); - } catch(NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException | - IllegalBlockSizeException | BadPaddingException e) { - LOGGER.error(ZKCryptoManagerConstants.SESSIONID, ZKCryptoManagerConstants.DERIVE_KEY, - ZKCryptoManagerConstants.EMPTY, "Error Deriving Key with Random Key." + e.getMessage()); - throw new ZKRandomKeyDecryptionException(ZKCryptoErrorConstants.KEY_DERIVATION_ERROR.getErrorCode(), - ZKCryptoErrorConstants.KEY_DERIVATION_ERROR.getErrorMessage()); - } - } - - private Key getMasterKeyFromHSM() { - LOGGER.info(ZKCryptoManagerConstants.SESSIONID, ZKCryptoManagerConstants.MASTER_KEY, - ZKCryptoManagerConstants.RANDOM_KEY, "Retrieve Master Key from HSM."); - String keyAlias = getKeyAlias(masterKeyAppId, masterKeyRefId); - if (Objects.nonNull(keyAlias)) { - return keyStore.getSymmetricKey(keyAlias); - } - - LOGGER.error(ZKCryptoManagerConstants.SESSIONID, ZKCryptoManagerConstants.MASTER_KEY, - ZKCryptoManagerConstants.MASTER_KEY, "No Key Alias found."); - throw new NoUniqueAliasException(ZKCryptoErrorConstants.NO_UNIQUE_ALIAS.getErrorCode(), - ZKCryptoErrorConstants.NO_UNIQUE_ALIAS.getErrorMessage()); - } - - private String getKeyAlias(String keyAppId, String keyRefId) { - LOGGER.info(ZKCryptoManagerConstants.SESSIONID, ZKCryptoManagerConstants.MASTER_KEY, - ZKCryptoManagerConstants.RANDOM_KEY, "Retrieve Master Key Alias from DB."); - - Map> keyAliasMap = dbHelper.getKeyAliases(keyAppId, keyRefId, DateUtils.getUTCCurrentDateTime()); - - List currentKeyAliases = keyAliasMap.get(KeymanagerConstant.CURRENTKEYALIAS); - - if (!currentKeyAliases.isEmpty() && currentKeyAliases.size() == 1) { - LOGGER.info(ZKCryptoManagerConstants.SESSIONID, ZKCryptoManagerConstants.MASTER_CURRENT_ALIAS, "getKeyAlias", - "CurrentKeyAlias size is one. Will decrypt random symmetric key for this alias"); - return currentKeyAliases.get(0).getAlias(); - } - - LOGGER.error(ZKCryptoManagerConstants.SESSIONID, ZKCryptoManagerConstants.MASTER_KEY, - ZKCryptoManagerConstants.RANDOM_KEY, "CurrentKeyAlias is not unique. KeyAlias count: " + currentKeyAliases.size()); - throw new NoUniqueAliasException(ZKCryptoErrorConstants.NO_UNIQUE_ALIAS.getErrorCode(), - ZKCryptoErrorConstants.NO_UNIQUE_ALIAS.getErrorMessage()); - } - - private byte[] doCipherOps(Key key, byte[] data, int mode, byte[] nonce, byte[] aad) { - LOGGER.info(ZKCryptoManagerConstants.SESSIONID, ZKCryptoManagerConstants.DATA_CIPHER, - ZKCryptoManagerConstants.EMPTY, "Data Encryption/Decryption Process"); - try { - Cipher cipher = Cipher.getInstance(aesGCMTransformation); - GCMParameterSpec gcmSpec = new GCMParameterSpec(ZKCryptoManagerConstants.GCM_TAG_LENGTH * 8, nonce); - cipher.init(mode, key, gcmSpec); - cipher.updateAAD(aad); - return cipher.doFinal(data, 0, data.length); - } catch(NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | - InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException ex) { - LOGGER.error(ZKCryptoManagerConstants.SESSIONID, ZKCryptoManagerConstants.DATA_CIPHER, - ZKCryptoManagerConstants.DATA_CIPHER, "Error Ciphering inputed data." + ex.getMessage()); - throw new ZKCryptoException(ZKCryptoErrorConstants.DATA_CIPHER_OPS_ERROR.getErrorCode(), - ZKCryptoErrorConstants.DATA_CIPHER_OPS_ERROR.getErrorMessage()); - } - } - - private byte[] getIndexBytes(int randomIndex) { - ByteBuffer byteBuff = ByteBuffer.allocate(ZKCryptoManagerConstants.INT_BYTES_LEN); - byteBuff.putInt(randomIndex); - return byteBuff.array(); - } - - private CryptoDataDto getResponseCryptoData(byte[] encryptedData, byte[] dbIndexBytes, byte[] nonce, byte[] aad, String identifier) { - byte[] finalEncData = new byte[encryptedData.length + dbIndexBytes.length + ZKCryptoManagerConstants.GCM_AAD_LENGTH - + ZKCryptoManagerConstants.GCM_NONCE_LENGTH]; - System.arraycopy(dbIndexBytes, 0, finalEncData, 0, dbIndexBytes.length); - System.arraycopy(nonce, 0, finalEncData, dbIndexBytes.length, nonce.length); - System.arraycopy(aad, 0, finalEncData, dbIndexBytes.length + nonce.length, aad.length); - System.arraycopy(encryptedData, 0, finalEncData, dbIndexBytes.length + nonce.length + aad.length, - encryptedData.length); - String concatEncryptedData = CryptoUtil.encodeBase64(finalEncData); - CryptoDataDto resCryptoData = new CryptoDataDto(); - resCryptoData.setIdentifier(identifier); - resCryptoData.setValue(concatEncryptedData); - return resCryptoData; - } - - private CryptoDataDto getResponseCryptoData(byte[] decryptedData, String identifier) { - - String decryptedDataStr = new String(decryptedData); - CryptoDataDto resCryptoData = new CryptoDataDto(); - resCryptoData.setIdentifier(identifier); - resCryptoData.setValue(decryptedDataStr); - return resCryptoData; - } - - private String encryptRandomKey(Key secretRandomKey) { - LOGGER.info(ZKCryptoManagerConstants.SESSIONID, ZKCryptoManagerConstants.ENCRYPT_RANDOM_KEY, - ZKCryptoManagerConstants.EMPTY, "Encrypting Random Key with Public Key."); - - String keyAlias = getKeyAlias(pubKeyApplicationId, pubKeyReferenceId); - Optional dbKeyStore = keyStoreRepository.findByAlias(keyAlias); - if (!dbKeyStore.isPresent()) { - LOGGER.info(ZKCryptoManagerConstants.SESSIONID, ZKCryptoManagerConstants.ENCRYPT_RANDOM_KEY, - ZKCryptoManagerConstants.ENCRYPT_RANDOM_KEY, "Key in DBStore does not exist for this alias. Throwing exception"); - throw new NoUniqueAliasException(ZKCryptoErrorConstants.NO_UNIQUE_ALIAS.getErrorCode(), - ZKCryptoErrorConstants.NO_UNIQUE_ALIAS.getErrorMessage()); - } - String certificateData = dbKeyStore.get().getCertificateData(); - X509Certificate x509Cert = (X509Certificate) keymanagerUtil.convertToCertificate(certificateData); - PublicKey publicKey = x509Cert.getPublicKey(); - byte[] encryptedRandomKey = cryptoCore.asymmetricEncrypt(publicKey, secretRandomKey.getEncoded()); - byte[] certThumbprint = cryptomanagerUtil.getCertificateThumbprint(x509Cert); - byte[] concatedData = cryptomanagerUtil.concatCertThumbprint(certThumbprint, encryptedRandomKey); - return CryptoUtil.encodeBase64(concatedData); - } - - @Override - public ReEncryptRandomKeyResponseDto zkReEncryptRandomKey(String encryptedKey){ - LOGGER.info(ZKCryptoManagerConstants.SESSIONID, ZKCryptoManagerConstants.RE_ENCRYPT_RANDOM_KEY, - ZKCryptoManagerConstants.EMPTY, "Re-Encrypt Random Key."); - if (encryptedKey == null || encryptedKey.trim().isEmpty()) { - LOGGER.error(ZKCryptoManagerConstants.SESSIONID, ZKCryptoManagerConstants.RE_ENCRYPT_RANDOM_KEY, - ZKCryptoManagerConstants.RE_ENCRYPT_RANDOM_KEY, "Invalid Encrypted Key input."); - throw new ZKCryptoException(ZKCryptoErrorConstants.INVALID_ENCRYPTED_RANDOM_KEY.getErrorCode(), - ZKCryptoErrorConstants.INVALID_ENCRYPTED_RANDOM_KEY.getErrorMessage()); - } - LocalDateTime localDateTimeStamp = DateUtils.getUTCCurrentDateTime(); - SymmetricKeyRequestDto symmetricKeyRequestDto = new SymmetricKeyRequestDto( - pubKeyApplicationId, localDateTimeStamp, pubKeyReferenceId, encryptedKey, true); - String randomKey = keyManagerService.decryptSymmetricKey(symmetricKeyRequestDto).getSymmetricKey(); - String encryptedRandomKey = getEncryptedRandomKey(Base64.getEncoder().encodeToString(CryptoUtil.decodeBase64(randomKey))); - ReEncryptRandomKeyResponseDto responseDto = new ReEncryptRandomKeyResponseDto(); - responseDto.setEncryptedKey(encryptedRandomKey); - return responseDto; - } -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/service/spi/ZKCryptoManagerService.java b/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/service/spi/ZKCryptoManagerService.java deleted file mode 100644 index 4e8c8669ddf..00000000000 --- a/kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/service/spi/ZKCryptoManagerService.java +++ /dev/null @@ -1,43 +0,0 @@ -package io.mosip.kernel.zkcryptoservice.service.spi; - -import org.springframework.stereotype.Service; - -import io.mosip.kernel.zkcryptoservice.dto.ReEncryptRandomKeyResponseDto; -import io.mosip.kernel.zkcryptoservice.dto.ZKCryptoRequestDto; -import io.mosip.kernel.zkcryptoservice.dto.ZKCryptoResponseDto; - -/** - * This interface provides the methods which can be used for Zero Knowledge Encryption and - * Decryption. - * - * @author Mahammed Taheer - * @since 1.1.2 - */ -@Service -public interface ZKCryptoManagerService { - - /** - * Encrypt the data requested with metadata. - * - * @param cryptoRequestDto {@link ZKCryptoRequestDto} instance - * @return {@link ZKCryptoResponseDto} encrypted data - */ - public ZKCryptoResponseDto zkEncrypt(ZKCryptoRequestDto cryptoRequestDto); - - /** - * Decrypt data requested with metadata. - * - * @param cryptoRequestDto {@link ZKCryptoRequestDto} instance - * @return {@link ZKCryptoResponseDto} decrypted data - */ - public ZKCryptoResponseDto zkDecrypt(ZKCryptoRequestDto cryptoRequestDto); - - - /** - * Re-Encrypt Random Key with the master key. - * - * @param encryptedKey encrypted random key - * @return {@link ReEncryptRandomKeyResponseDto} encrypted key - */ - public ReEncryptRandomKeyResponseDto zkReEncryptRandomKey(String encryptedKey); -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/resources/application-local.properties b/kernel/kernel-keymanager-service/src/main/resources/application-local.properties deleted file mode 100644 index 18c8f25187b..00000000000 --- a/kernel/kernel-keymanager-service/src/main/resources/application-local.properties +++ /dev/null @@ -1,125 +0,0 @@ -#mosip.kernel.keymanager.softhsm.config-path=/config/softhsm-application.conf - - -mosip.kernel.keymanager.hsm.keystore-type=PKCS11 - -mosip.kernel.keymanager.hsm.config-path=/hsm-files/pkcs11-softhsm.cfg -#mosip.kernel.keymanager.hsm.config-path=/hsm-files/pkcs/mosip-ks.p12 -mosip.kernel.keymanager.hsm.keystore-pass=1234 - -mosip.kernel.keymanager.certificate.default.common-name=www.mosip.io -mosip.kernel.keymanager.certificate.default.organizational-unit=IIITB -mosip.kernel.keymanager.certificate.default.organization=mosip -mosip.kernel.keymanager.certificate.default.location=BANGALORE -mosip.kernel.keymanager.certificate.default.state=KA -mosip.kernel.keymanager.certificate.default.country=IN - -mosip.kernel.keymanager.softhsm.certificate.common-name=www.mosip.io -mosip.kernel.keymanager.softhsm.certificate.organizational-unit=MOSIP -mosip.kernel.keymanager.softhsm.certificate.organization=IITB -mosip.kernel.keymanager.softhsm.certificate.country=IN - -#----------------------- Crypto -------------------------------------------------- -#Crypto asymmetric algorithm name -mosip.kernel.crypto.asymmetric-algorithm-name=RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING -#Crypto symmetric algorithm name -mosip.kernel.crypto.symmetric-algorithm-name=AES/GCM/PKCS5Padding -#Keygenerator asymmetric algorithm name -mosip.kernel.keygenerator.asymmetric-algorithm-name=RSA -#Keygenerator symmetric algorithm name -mosip.kernel.keygenerator.symmetric-algorithm-name=AES -#Asymmetric algorithm key length -mosip.kernel.keygenerator.asymmetric-key-length=2048 -#Symmetric algorithm key length -mosip.kernel.keygenerator.symmetric-key-length=256 - -#Encrypted data and encrypted symmetric key separator -mosip.kernel.data-key-splitter=#KEY_SPLITTER# -#GCM tag length -mosip.kernel.crypto.gcm-tag-length=128 -#Hash algo name -mosip.kernel.crypto.hash-algorithm-name=PBKDF2WithHmacSHA512 -#Symmtric key length used in hash -mosip.kernel.crypto.hash-symmetric-key-length=256 -#No of iterations in hash -mosip.kernel.crypto.hash-iteration=10 -#Sign algo name -mosip.kernel.crypto.sign-algorithm-name=RS256 -#Certificate Sign algo name -mosip.kernel.certificate.sign.algorithm=SHA256withRSA - - -keymanager.persistence.jdbc.driver=org.postgresql.Driver -keymanager_database_url=jdbc:postgresql://localhost:5432/mosip_keymgr -keymanager_database_username=mosip-db -keymanager_database_password= - - -hibernate.hbm2ddl.auto=none -hibernate.dialect=org.hibernate.dialect.PostgreSQL95Dialect -hibernate.jdbc.lob.non_contextual_creation=true -hibernate.show_sql=false -hibernate.format_sql=false -hibernate.connection.charSet=utf8 -hibernate.cache.use_second_level_cache=false -hibernate.cache.use_query_cache=false -hibernate.cache.use_structured_entries=false -hibernate.generate_statistics=false -hibernate.current_session_context_class=org.springframework.orm.hibernate5.SpringSessionContext - -auth.server.validate.url=http://localhost:8091/v1/authmanager/authorize/admin/validateToken -auth.server.admin.validate.url=http://localhost:8091/v1/authmanager/authorize/admin/validateToken -auth.role.prefix=ROLE_ -auth.header.name=Authorization - -#mosip.kernel.pdf_owner_password=PDFADMIN -#------ -mosip.kernel.signature.signature-request-id=SIGNATURE.REQUEST -mosip.kernel.signature.signature-version-id=v1.0 - -mosip.root.key.applicationid=ROOT -mosip.sign.applicationid=KERNEL -mosip.sign.refid=SIGN -mosip.sign-certificate-refid=SIGN -mosip.signed.header=response-signature - - -#--- - -mosip.kernel.tokenid.uin.salt=zHuDEAbmbxiUbUShgy6pwUhKh9DE0EZn9kQDKPPKbWscGajMwf -mosip.kernel.tokenid.partnercode.salt=yS8w5Wb6vhIKdf1msi4LYTJks7mqkbmITk2O63Iq8h0bkRlD0d -mosip.kernel.tokenid.length=36 - -#--- -#Length of license key to be generated. -mosip.kernel.licensekey.length=16 -#List of permissions -# NOTE: ',' in the below list is used as splitter in the implementation. -# Use of ',' in the values for below key should be avoided. -# Use of spaces before and after ',' also should be avoided. -mosip.kernel.licensekey.permissions=OTP Trigger,OTP Authentication,Demo Authentication - Identity Data Match,Demo Authentication - Address Data Match,Demo Authentication - Full Address Data Match,Demo Authentication - Secondary Language Match,Biometric Authentication - FMR Data Match,Biometric Authentication - IIR Data Match,Biometric Authentication - FID Data Match,Static Pin Authentication,eKYC - limited,eKYC - Full,eKYC - No - -mosip.kernel.zkcrypto.masterkey.application.id=KERNEL -mosip.kernel.zkcrypto.masterkey.reference.id=IDENTITY_CACHE -mosip.kernel.zkcrypto.publickey.application.id=IDA -mosip.kernel.zkcrypto.publickey.reference.id=PUBLIC_KEY -mosip.kernel.zkcrypto.wrap.algorithm-name=AES/ECB/NoPadding -mosip.kernel.zkcrypto.derive.encrypt.algorithm-name=AES/ECB/PKCS5Padding - -mosip.kernel.partner.sign.masterkey.application.id=PMS - -mosip.kernel.partner.allowed.domains=AUTH,DEVICE,FTM - -mosip.iam.impl.basepackage=io.mosip.kernel.auth.defaultimpl -mosip.auth.adapter.impl.basepackage=io.mosip.kernel.auth.defaultadapter - -mosip.kernel.keymanager.hsm.jce.className=io.mosip.keymanager.hsm.impl.HSMKeyStoreImpl -mosip.kernel.keymanager.hsm.jce.keyStoreType=CloudHSM -mosip.kernel.keymanager.hsm.jce.keyStoreFile= -mosip.kernel.keymanager.hsm.jce.localKeyStorePwd= -mosip.kernel.keymanager.hsm.jce.partitionName=PARTITION_01 -mosip.kernel.keymanager.hsm.jce.cuUserName=keyusr -mosip.kernel.keymanager.hsm.jce.cuPassword= - - -mosip.kernel.keymanager.113nothumbprint.support=false \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/main/resources/bootstrap.properties b/kernel/kernel-keymanager-service/src/main/resources/bootstrap.properties deleted file mode 100644 index d02da0468d3..00000000000 --- a/kernel/kernel-keymanager-service/src/main/resources/bootstrap.properties +++ /dev/null @@ -1,24 +0,0 @@ -#spring.cloud.config.uri=http://104.211.212.28:51000 -#spring.cloud.config.label=master -spring.profiles.active=local -spring.cloud.config.name=kernel -spring.application.name=kernel-keymanager-service -#management.security.enabled=false -#management.endpoint.health.show-details=when-authorized -#management.endpoints.web.exposure.include=* -management.endpoint.health.show-details=always -management.endpoints.web.exposure.include=info,health,refresh,mappings,prometheus -management.endpoint.metrics.enabled=true -management.endpoint.prometheus.enabled=true -management.metrics.export.prometheus.enabled=true - -server.port=8088 -server.servlet.path=/v1/keymanager - -keymanager.persistence.jdbc.schema=keymgr - -#disabling health check so that client doesnt try to load properties from sprint config server every -# 5 minutes (should not be done in production) -health.config.enabled=false - -logging.level.org.springframework.web.filter.CommonsRequestLoggingFilter=DEBUG diff --git a/kernel/kernel-keymanager-service/src/main/resources/logback.xml b/kernel/kernel-keymanager-service/src/main/resources/logback.xml deleted file mode 100644 index 150c62249df..00000000000 --- a/kernel/kernel-keymanager-service/src/main/resources/logback.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/clientcrypto/test/ClientCryptoTestBootApplication.java b/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/clientcrypto/test/ClientCryptoTestBootApplication.java deleted file mode 100644 index e9e4ebb158f..00000000000 --- a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/clientcrypto/test/ClientCryptoTestBootApplication.java +++ /dev/null @@ -1,12 +0,0 @@ -package io.mosip.kernel.clientcrypto.test; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication(scanBasePackages = { "io.mosip.kernel.clientcrypto.*", "io.mosip.kernel.crypto.jce.*"}) -public class ClientCryptoTestBootApplication { - - public static void main(String[] args) { - SpringApplication.run(ClientCryptoTestBootApplication.class, args); - } -} diff --git a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/clientcrypto/test/TestSecurityConfig.java b/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/clientcrypto/test/TestSecurityConfig.java deleted file mode 100644 index da5c9e30d61..00000000000 --- a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/clientcrypto/test/TestSecurityConfig.java +++ /dev/null @@ -1,67 +0,0 @@ -package io.mosip.kernel.clientcrypto.test; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.builders.WebSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.config.http.SessionCreationPolicy; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.security.core.userdetails.User; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.provisioning.InMemoryUserDetailsManager; -import org.springframework.security.web.AuthenticationEntryPoint; -import org.springframework.security.web.firewall.DefaultHttpFirewall; -import org.springframework.security.web.firewall.HttpFirewall; - -import javax.servlet.http.HttpServletResponse; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -@Configuration -//@EnableWebSecurity -//@EnableGlobalMethodSecurity(prePostEnabled = true) -public class TestSecurityConfig {// extends WebSecurityConfigurerAdapter { - - @Bean - public HttpFirewall defaultHttpFirewall() { - return new DefaultHttpFirewall(); - } - - /*@Override - public void configure(WebSecurity webSecurity) throws Exception { - webSecurity.ignoring().antMatchers(allowedEndPoints()); - super.configure(webSecurity); - webSecurity.httpFirewall(defaultHttpFirewall()); - }*/ - - private String[] allowedEndPoints() { - return new String[] { "/assets/**", "/icons/**", "/screenshots/**", "/favicon**", "/**/favicon**", "/css/**", - "/js/**", "/*/error**", "/*/webjars/**", "/*/v2/api-docs", "/*/configuration/ui", - "/*/configuration/security", "/*/swagger-resources/**", "/*/swagger-ui.html" }; - } - - /*@Override - protected void configure(final HttpSecurity httpSecurity) throws Exception { - httpSecurity.csrf().disable(); - httpSecurity.httpBasic().and().authorizeRequests().anyRequest().authenticated().and().sessionManagement() - .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().exceptionHandling() - .authenticationEntryPoint(unauthorizedEntryPoint()); - }*/ - - @Bean - public AuthenticationEntryPoint unauthorizedEntryPoint() { - return (request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED); - } - - @Bean - public UserDetailsService userDetailsService() { - List users = new ArrayList<>(); - users.add(new User("test", "mosip", Arrays.asList(new SimpleGrantedAuthority("ROLE_TEST")))); - return new InMemoryUserDetailsManager(users); - } -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/clientcrypto/test/integration/ClientCryptoControllerTest.java b/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/clientcrypto/test/integration/ClientCryptoControllerTest.java deleted file mode 100644 index c3868604eb0..00000000000 --- a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/clientcrypto/test/integration/ClientCryptoControllerTest.java +++ /dev/null @@ -1,120 +0,0 @@ -package io.mosip.kernel.clientcrypto.test.integration; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; -import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; -import io.mosip.kernel.clientcrypto.dto.PublicKeyRequestDto; -import io.mosip.kernel.clientcrypto.service.impl.ClientCryptoFacade; -import io.mosip.kernel.clientcrypto.service.spi.ClientCryptoService; -import io.mosip.kernel.clientcrypto.test.ClientCryptoTestBootApplication; -import io.mosip.kernel.core.http.RequestWrapper; -import io.mosip.kernel.core.util.CryptoUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.http.MediaType; -import org.springframework.security.test.context.support.WithUserDetails; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.MvcResult; - -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.util.ArrayList; -import java.util.Optional; - -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -@SpringBootTest(classes = { ClientCryptoTestBootApplication.class }) -@RunWith(SpringRunner.class) -@AutoConfigureMockMvc -public class ClientCryptoControllerTest { - - @Autowired - private MockMvc mockMvc; - - private ObjectMapper mapper; - - @Autowired - ClientCryptoFacade clientCryptoFacade; - - private static final String ID = "mosip.crypto.service"; - private static final String VERSION = "V1.0"; - - private static final String public_key = "AAEACwACAHIAIINxl2dEhLP4GpDMjUal1yT9UtduBlILZPKh2hszFGmqABAAFwALCAAAAQABAQDiSa/AdVmDrj+ypFywexe/eSaSsrIoO5Ns0jp7niMu4hiFIwsFT7yWx2aQUQcdX5OjyXjv/XJctGxFcphLXke5fwAoW6BsbeM//1Mlhq9YvdMKlwMjhKcd+7MHHAXPUKGVmMjIJe6kWwUWh7FaZyu5hDymM5MJyYZRxz5fRos/N9ykiBxjWKZK06ZpIYI6Tj9rUNZ6HAdbJH2RmBHuO0knpbXdB+lnnVhvArAt3KWoyH3YzodHeOLJRe/Y8a+p8zRZb5h1tqlcLgshpNAqb+WJgyq2xDb0RJwzuyjjHPmJrDqlBMXHestz+ADRwXQL44iVb84LcuMbQTQ1hGcawtBj"; - private static final String dataToEncrypt = "HeloolHelloHelloHello"; - - @Before - public void init() { - mapper = new ObjectMapper(); - mapper.registerModule(new JavaTimeModule()); - mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); - } - - - @Test - @Ignore - public void getEncryptDecryptWithTpm() throws Exception { - byte[] cipher = clientCryptoFacade.encrypt(CryptoUtil.decodeBase64(public_key), dataToEncrypt.getBytes()); - - ClientCryptoService clientCryptoService = clientCryptoFacade.getClientSecurity(); - Assert.assertNotNull(clientCryptoService); - - byte[] plain = clientCryptoFacade.decrypt(cipher); - Assert.assertNotNull(plain); - Assert.assertArrayEquals(dataToEncrypt.getBytes(), plain); - } - - @Test - @Ignore - public void getSignVerifyWithTPM() throws Exception { - ClientCryptoService clientCryptoService = clientCryptoFacade.getClientSecurity(); - Assert.assertNotNull(clientCryptoService); - - byte[] localPubKey = clientCryptoService.getSigningPublicPart(); - - byte[] sigBytes = clientCryptoFacade.getClientSecurity().signData(dataToEncrypt.getBytes()); - Assert.assertNotNull(sigBytes); - - boolean valid = clientCryptoFacade.validateSignature(localPubKey, sigBytes, dataToEncrypt.getBytes()); - Assert.assertTrue(valid); - } - - @Test - @Ignore - public void getEncryptDecryptWithLocal() throws Exception { - ClientCryptoService clientCryptoService = clientCryptoFacade.getClientSecurity(); - Assert.assertNotNull(clientCryptoService); - - byte[] localPubKey = clientCryptoService.getEncryptionPublicPart(); - - byte[] cipher = clientCryptoFacade.encrypt(localPubKey, dataToEncrypt.getBytes()); - - byte[] plain = clientCryptoFacade.decrypt(cipher); - Assert.assertNotNull(plain); - Assert.assertArrayEquals(dataToEncrypt.getBytes(), plain); - } - - @Test - @Ignore - public void getSignVerifyWithLocal() throws Exception { - ClientCryptoService clientCryptoService = clientCryptoFacade.getClientSecurity(); - Assert.assertNotNull(clientCryptoService); - - byte[] localPubKey = clientCryptoService.getSigningPublicPart(); - - byte[] sigBytes = clientCryptoFacade.getClientSecurity().signData(dataToEncrypt.getBytes()); - Assert.assertNotNull(sigBytes); - - boolean valid = clientCryptoFacade.validateSignature(localPubKey, sigBytes, dataToEncrypt.getBytes()); - Assert.assertTrue(valid); - } - - } diff --git a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/crypto/jce/test/CryptoCoreNoSuchAlgorithmExceptionTest.java b/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/crypto/jce/test/CryptoCoreNoSuchAlgorithmExceptionTest.java deleted file mode 100644 index c29c4c06bbb..00000000000 --- a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/crypto/jce/test/CryptoCoreNoSuchAlgorithmExceptionTest.java +++ /dev/null @@ -1,110 +0,0 @@ -package io.mosip.kernel.crypto.jce.test; - -import static org.hamcrest.CoreMatchers.isA; -import static org.junit.Assert.assertThat; - -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.spec.InvalidKeySpecException; - -import javax.crypto.SecretKey; -import javax.crypto.spec.SecretKeySpec; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.ClassMode; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.util.ReflectionTestUtils; - -import io.mosip.kernel.core.crypto.spi.CryptoCoreSpec; -import io.mosip.kernel.core.exception.NoSuchAlgorithmException; - -@RunWith(SpringRunner.class) -@DirtiesContext(classMode = ClassMode.AFTER_CLASS) -@SpringBootTest -public class CryptoCoreNoSuchAlgorithmExceptionTest { - - private static final String MOCKAAD = "MOCKAAD"; - - @Autowired - private CryptoCoreSpec cryptoCore; - - private KeyPair rsaPair; - - private byte[] data; - - private byte[] keyBytes; - - private final SecureRandom random = new SecureRandom(); - - @Before - public void init() throws java.security.NoSuchAlgorithmException { - KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); - generator.initialize(2048, random); - rsaPair = generator.generateKeyPair(); - data = "test".getBytes(); - keyBytes = new byte[16]; - random.nextBytes(keyBytes); - ReflectionTestUtils.setField(cryptoCore, "asymmetricAlgorithm", "INVALIDALGO"); - ReflectionTestUtils.setField(cryptoCore, "symmetricAlgorithm", "INVALIDALGO"); - ReflectionTestUtils.setField(cryptoCore, "signAlgorithm", "INVALIDALGO"); - ReflectionTestUtils.setField(cryptoCore, "passwordAlgorithm", "INVALIDALGO"); - } - - private SecretKeySpec setSymmetricUp(int length, String algo) throws java.security.NoSuchAlgorithmException { - SecureRandom random = new SecureRandom(); - byte[] keyBytes = new byte[length]; - random.nextBytes(keyBytes); - return new SecretKeySpec(keyBytes, algo); - } - - @Test(expected = NoSuchAlgorithmException.class) - public void testAsymmetricPublicEncryptNoSuchAlgorithmException() { - assertThat(cryptoCore.asymmetricEncrypt(rsaPair.getPublic(), data), isA(byte[].class)); - } - - @Test(expected = NoSuchAlgorithmException.class) - public void testAESSymmetricEncryptNoSuchAlgorithmException() throws java.security.NoSuchAlgorithmException { - assertThat(cryptoCore.symmetricEncrypt(setSymmetricUp(32, "AES"), data, null, MOCKAAD.getBytes()), - isA(byte[].class)); - } - - @Test(expected = NoSuchAlgorithmException.class) - public void testAESSymmetricSaltEncryptNoSuchAlgorithmException() throws java.security.NoSuchAlgorithmException { - assertThat(cryptoCore.symmetricEncrypt(setSymmetricUp(32, "AES"), data, keyBytes, MOCKAAD.getBytes()), - isA(byte[].class)); - } - - @Test(expected = NoSuchAlgorithmException.class) - public void testAsymmetricDecryptNoSuchAlgorithmException() { - byte[] encryptedData = cryptoCore.asymmetricEncrypt(rsaPair.getPublic(), data); - assertThat(cryptoCore.asymmetricDecrypt(rsaPair.getPrivate(), encryptedData), isA(byte[].class)); - } - - @Test(expected = NoSuchAlgorithmException.class) - public void testAESSymmetricDecryptNoSuchAlgorithmException() throws java.security.NoSuchAlgorithmException { - SecretKeySpec secretKeySpec = setSymmetricUp(32, "AES"); - assertThat(cryptoCore.symmetricDecrypt(secretKeySpec, "encryptedData".getBytes(), MOCKAAD.getBytes()), - isA(byte[].class)); - } - - @Test(expected = NoSuchAlgorithmException.class) - public void testAESSymmetricSaltDecryptNoSuchAlgorithmException() throws java.security.NoSuchAlgorithmException { - SecretKeySpec secretKeySpec = setSymmetricUp(32, "AES"); - assertThat(cryptoCore.symmetricDecrypt(secretKeySpec, "encryptedData".getBytes(), MOCKAAD.getBytes(), keyBytes), - isA(byte[].class)); - } - - @Test(expected = NoSuchAlgorithmException.class) - public void testHashNoSuchAlgorithmException() throws NoSuchAlgorithmException, InvalidKeySpecException { - assertThat(cryptoCore.hash(data, keyBytes), isA(String.class)); - } - -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/crypto/jce/test/CryptoCoreTest.java b/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/crypto/jce/test/CryptoCoreTest.java deleted file mode 100644 index a72c20d0035..00000000000 --- a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/crypto/jce/test/CryptoCoreTest.java +++ /dev/null @@ -1,228 +0,0 @@ -package io.mosip.kernel.crypto.jce.test; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.isA; -import static org.junit.Assert.assertThat; - -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.spec.InvalidKeySpecException; - -import javax.crypto.SecretKey; -import javax.crypto.spec.SecretKeySpec; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; -import io.mosip.kernel.core.crypto.exception.InvalidDataException; -import io.mosip.kernel.core.crypto.exception.InvalidKeyException; -import io.mosip.kernel.core.crypto.exception.SignatureException; -import io.mosip.kernel.core.crypto.spi.CryptoCoreSpec; - -@SpringBootTest -@RunWith(SpringRunner.class) -public class CryptoCoreTest { - - private static final String MOCKAAD = "MOCKAAD"; - - @Autowired - private CryptoCoreSpec cryptoCore; - - private KeyPair rsaPair; - - private byte[] data; - - private byte[] keyBytes; - - private final SecureRandom random = new SecureRandom(); - - @Before - public void init() throws java.security.NoSuchAlgorithmException { - KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); - generator.initialize(2048, random); - rsaPair = generator.generateKeyPair(); - data = "test".getBytes(); - keyBytes = new byte[16]; - random.nextBytes(keyBytes); - - } - - private SecretKeySpec setSymmetricUp(int length, String algo) throws java.security.NoSuchAlgorithmException { - SecureRandom random = new SecureRandom(); - byte[] keyBytes = new byte[length]; - random.nextBytes(keyBytes); - return new SecretKeySpec(keyBytes, algo); - } - - @Test - public void testAsymmetricPublicEncrypt() { - assertThat(cryptoCore.asymmetricEncrypt(rsaPair.getPublic(), data), isA(byte[].class)); - } - - @Test - public void testAESSymmetricEncrypt() throws java.security.NoSuchAlgorithmException { - assertThat(cryptoCore.symmetricEncrypt(setSymmetricUp(32, "AES"), data, null, MOCKAAD.getBytes()), - isA(byte[].class)); - } - - @Test - public void testAESSymmetricSaltEncrypt() throws java.security.NoSuchAlgorithmException { - SecureRandom random = new SecureRandom(); - byte[] keyBytes = new byte[16]; - random.nextBytes(keyBytes); - assertThat(cryptoCore.symmetricEncrypt(setSymmetricUp(32, "AES"), data, keyBytes, MOCKAAD.getBytes()), - isA(byte[].class)); - } - - @Test(expected = NullPointerException.class) - public void testAESSymmetricEncryptNullKey() throws java.security.NoSuchAlgorithmException { - cryptoCore.symmetricEncrypt(null, data, MOCKAAD.getBytes()); - } - - @Test(expected = InvalidKeyException.class) - public void testAESSymmetricEncryptInvalidKey() throws java.security.NoSuchAlgorithmException { - SecureRandom random = new SecureRandom(); - byte[] keyBytes = new byte[15]; - random.nextBytes(keyBytes); - SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES"); - cryptoCore.symmetricEncrypt(secretKeySpec, data, MOCKAAD.getBytes()); - } - - @Test(expected = InvalidKeyException.class) - public void testAESSymmetricEncryptSaltInvalidKey() throws java.security.NoSuchAlgorithmException { - SecretKeySpec secretKeySpec = setSymmetricUp(15, "AES"); - cryptoCore.symmetricEncrypt(secretKeySpec, data, keyBytes, MOCKAAD.getBytes()); - } - - @Test(expected = InvalidKeyException.class) - public void testAsymmetricPublicInvalidKeyEncrypt() throws NoSuchAlgorithmException, InvalidKeySpecException { - KeyPairGenerator generator = KeyPairGenerator.getInstance("DSA"); - generator.initialize(2048, random); - KeyPair invalidKeyPair = generator.generateKeyPair(); - assertThat(cryptoCore.asymmetricEncrypt(invalidKeyPair.getPublic(), data), isA(byte[].class)); - } - - @Test - public void testHash() throws NoSuchAlgorithmException, InvalidKeySpecException { - assertThat(cryptoCore.hash(data, keyBytes), isA(String.class)); - } - - @Test - public void testSign() throws NoSuchAlgorithmException, InvalidKeySpecException { - assertThat(cryptoCore.sign(data, rsaPair.getPrivate()), isA(String.class)); - } - - @Test(expected = SignatureException.class) - public void testSignInvalidKey() throws NoSuchAlgorithmException, InvalidKeySpecException { - KeyPairGenerator generator = KeyPairGenerator.getInstance("DSA"); - generator.initialize(2048, random); - KeyPair invalidKeyPair = generator.generateKeyPair(); - assertThat(cryptoCore.sign(data, invalidKeyPair.getPrivate()), isA(String.class)); - } - - @Test - public void testVerify() throws NoSuchAlgorithmException, InvalidKeySpecException { - String signature = cryptoCore.sign(data, rsaPair.getPrivate()); - assertThat(cryptoCore.verifySignature(data, signature, rsaPair.getPublic()), is(true)); - } - - @Test(expected = SignatureException.class) - public void testVerifySignatureException() throws NoSuchAlgorithmException, InvalidKeySpecException { - assertThat(cryptoCore.verifySignature(data, "Invaliddata", rsaPair.getPublic()), is(true)); - } - - @Test(expected = SignatureException.class) - public void testVerifySignatureNullException() throws NoSuchAlgorithmException, InvalidKeySpecException { - assertThat(cryptoCore.verifySignature(data, null, rsaPair.getPublic()), is(true)); - } - - @Test(expected = SignatureException.class) - public void testVerifyInvalidKey() throws NoSuchAlgorithmException, InvalidKeySpecException { - KeyPairGenerator generator = KeyPairGenerator.getInstance("DSA"); - generator.initialize(2048, random); - KeyPair invalidKeyPair = generator.generateKeyPair(); - String signature = cryptoCore.sign(data, rsaPair.getPrivate()); - assertThat(cryptoCore.verifySignature(data, signature, invalidKeyPair.getPublic()), is(true)); - } - - @Test - public void testRandom() throws NoSuchAlgorithmException, InvalidKeySpecException { - assertThat(cryptoCore.random(), isA(SecureRandom.class)); - } - - @Test - public void testAsymmetricDecrypt() { - byte[] encryptedData = cryptoCore.asymmetricEncrypt(rsaPair.getPublic(), data); - assertThat(cryptoCore.asymmetricDecrypt(rsaPair.getPrivate(), encryptedData), isA(byte[].class)); - } - - @Test - public void testAESSymmetricDecrypt() throws java.security.NoSuchAlgorithmException { - SecretKeySpec secretKeySpec = setSymmetricUp(32, "AES"); - byte[] encryptedData = cryptoCore.symmetricEncrypt(secretKeySpec, data, MOCKAAD.getBytes()); - assertThat(cryptoCore.symmetricDecrypt(secretKeySpec, encryptedData, null, MOCKAAD.getBytes()), - isA(byte[].class)); - } - - @Test - public void testAESSymmetricSaltDecrypt() throws java.security.NoSuchAlgorithmException { - SecretKeySpec secretKeySpec = setSymmetricUp(32, "AES"); - byte[] encryptedData = cryptoCore.symmetricEncrypt(secretKeySpec, data, MOCKAAD.getBytes(), keyBytes); - assertThat(cryptoCore.symmetricDecrypt(secretKeySpec, encryptedData, MOCKAAD.getBytes(), keyBytes), - isA(byte[].class)); - } - - @Test(expected = NullPointerException.class) - public void testAESSymmetricDecryptInvalidKey() throws java.security.NoSuchAlgorithmException { - SecretKeySpec secretKeySpec = setSymmetricUp(32, "AES"); - byte[] encryptedData = cryptoCore.symmetricEncrypt(secretKeySpec, data, MOCKAAD.getBytes()); - cryptoCore.symmetricDecrypt(null, encryptedData, MOCKAAD.getBytes()); - } - - @Test(expected = InvalidDataException.class) - public void testAESSymmetricDecryptInvalidDataArrayIndexOutOfBounds() - throws java.security.NoSuchAlgorithmException { - cryptoCore.symmetricDecrypt(setSymmetricUp(32, "AES"), "aa".getBytes(), MOCKAAD.getBytes()); - } - - @Test(expected = InvalidDataException.class) - public void testAESSymmetricDecryptInvalidDataIllegalBlockSize() throws java.security.NoSuchAlgorithmException { - cryptoCore.symmetricDecrypt(setSymmetricUp(32, "AES"), new byte[121], MOCKAAD.getBytes()); - } - - @Test(expected = InvalidKeyException.class) - public void testAESSymmetricDecryptInvalidKeyLength() throws java.security.NoSuchAlgorithmException { - SecretKeySpec secretKeySpec = setSymmetricUp(32, "AES"); - byte[] encryptedData = cryptoCore.symmetricEncrypt(secretKeySpec, data, MOCKAAD.getBytes()); - cryptoCore.symmetricDecrypt(setSymmetricUp(15, "AES"), encryptedData, null, MOCKAAD.getBytes()); - } - - @Test(expected = InvalidKeyException.class) - public void testAESSymmetricDecryptSaltInvalidKeyLength() throws java.security.NoSuchAlgorithmException { - SecretKeySpec secretKeySpec = setSymmetricUp(32, "AES"); - byte[] encryptedData = cryptoCore.symmetricEncrypt(secretKeySpec, data, MOCKAAD.getBytes()); - cryptoCore.symmetricDecrypt(setSymmetricUp(15, "AES"), encryptedData, keyBytes, MOCKAAD.getBytes()); - } - - @Test(expected = InvalidKeyException.class) - public void testRSAPKS1AsymmetricPrivateDecryptInvalidDataIllegalBlockSize() { - cryptoCore.asymmetricDecrypt(rsaPair.getPrivate(), new byte[121]); - } - - @Test(expected = InvalidKeyException.class) - public void testAsymmetricPublicInvalidKeyDecrypt() throws NoSuchAlgorithmException, InvalidKeySpecException { - KeyPairGenerator generator = KeyPairGenerator.getInstance("DSA"); - generator.initialize(2048, random); - KeyPair invalidKeyPair = generator.generateKeyPair(); - byte[] encryptedData = cryptoCore.asymmetricEncrypt(rsaPair.getPublic(), data); - assertThat(cryptoCore.asymmetricDecrypt(invalidKeyPair.getPrivate(), rsaPair.getPublic(), encryptedData), isA(byte[].class)); - } - -} diff --git a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/crypto/jce/test/CryptoJceBootApplication.java b/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/crypto/jce/test/CryptoJceBootApplication.java deleted file mode 100644 index 188b06e1f19..00000000000 --- a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/crypto/jce/test/CryptoJceBootApplication.java +++ /dev/null @@ -1,15 +0,0 @@ -package io.mosip.kernel.crypto.jce.test; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.ComponentScan; - -@SpringBootApplication -@ComponentScan({ "io.mosip.kernel.crypto.jce.*" }) -public class CryptoJceBootApplication { - public static void main(String[] args) { - SpringApplication.run(CryptoJceBootApplication.class, args); - - } - -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/crypto/jce/test/CryptoUtilTest.java b/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/crypto/jce/test/CryptoUtilTest.java deleted file mode 100644 index 4d366290450..00000000000 --- a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/crypto/jce/test/CryptoUtilTest.java +++ /dev/null @@ -1,39 +0,0 @@ -package io.mosip.kernel.crypto.jce.test; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import io.mosip.kernel.core.crypto.exception.InvalidDataException; -import io.mosip.kernel.core.crypto.exception.NullDataException; -import io.mosip.kernel.crypto.jce.constant.SecurityExceptionCodeConstant; -import io.mosip.kernel.crypto.jce.util.CryptoUtils; - -@RunWith(SpringRunner.class) -@SpringBootTest -public class CryptoUtilTest { - - @Test(expected = NullDataException.class) - public void testverifyDataNullData() { - CryptoUtils.verifyData(null); - } - - @Test(expected = InvalidDataException.class) - public void testverifyDataEmptyData() { - CryptoUtils.verifyData(new byte[0]); - } - - @Test(expected = NullDataException.class) - public void testverifyDataNullDataWithErrorCode() { - CryptoUtils.verifyData(null, SecurityExceptionCodeConstant.MOSIP_NULL_DATA_EXCEPTION.getErrorCode(), - SecurityExceptionCodeConstant.MOSIP_NULL_DATA_EXCEPTION.getErrorMessage()); - } - - @Test(expected = InvalidDataException.class) - public void testverifyDataEmptyDataWithErrorCode() { - CryptoUtils.verifyData(new byte[0], SecurityExceptionCodeConstant.MOSIP_NULL_DATA_EXCEPTION.getErrorCode(), - SecurityExceptionCodeConstant.MOSIP_NULL_DATA_EXCEPTION.getErrorMessage()); - } - -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/cryptomanager/test/integration/CryptographicServiceIntegrationExceptionTest.java b/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/cryptomanager/test/integration/CryptographicServiceIntegrationExceptionTest.java deleted file mode 100644 index 211858b4e4f..00000000000 --- a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/cryptomanager/test/integration/CryptographicServiceIntegrationExceptionTest.java +++ /dev/null @@ -1,200 +0,0 @@ - -package io.mosip.kernel.cryptomanager.test.integration; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.when; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import java.security.PrivateKey; -import java.security.PublicKey; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.util.Map; -import java.util.Optional; - -import javax.crypto.SecretKey; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; - -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.http.MediaType; -import org.springframework.security.test.context.support.WithUserDetails; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.client.MockRestServiceServer; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.MvcResult; -import org.springframework.web.util.UriComponentsBuilder; - -import io.mosip.kernel.core.crypto.spi.CryptoCoreSpec; -import io.mosip.kernel.core.http.RequestWrapper; -import io.mosip.kernel.core.http.ResponseWrapper; -import io.mosip.kernel.core.keymanager.spi.KeyStore; -import io.mosip.kernel.core.util.CryptoUtil; -import io.mosip.kernel.core.util.DateUtils; -import io.mosip.kernel.cryptomanager.dto.CryptomanagerRequestDto; -import io.mosip.kernel.cryptomanager.dto.CryptomanagerResponseDto; -import io.mosip.kernel.keymanagerservice.dto.KeyPairGenerateResponseDto; -import io.mosip.kernel.keymanagerservice.dto.PublicKeyResponse; -import io.mosip.kernel.keymanagerservice.service.KeymanagerService; -import io.mosip.kernel.keymanagerservice.test.KeymanagerTestBootApplication; - -@SpringBootTest(classes = KeymanagerTestBootApplication.class) -@RunWith(SpringRunner.class) -@AutoConfigureMockMvc -public class CryptographicServiceIntegrationExceptionTest { - - @Autowired - private MockMvc mockMvc; - - @Autowired - private ObjectMapper objectMapper; - - @MockBean - private KeyStore keyStore; - - /** The key manager. */ - @MockBean - private KeymanagerService keyManagerService; - - @Autowired - private ObjectMapper mapper; - - private MockRestServiceServer server; - - private UriComponentsBuilder builder; - - private Map uriParams; - - private CryptomanagerRequestDto requestDto; - - private RequestWrapper requestWrapper; - - /** - * {@link CryptoCoreSpec} instance for cryptographic functionalities. - */ - @MockBean - private CryptoCoreSpec cryptoCore; - - private static final String ID = "mosip.crypto.service"; - private static final String VERSION = "V1.0"; - - @Before - public void setUp() { - mapper = new ObjectMapper(); - mapper.registerModule(new JavaTimeModule()); - - requestWrapper = new RequestWrapper<>(); - requestWrapper.setId(ID); - requestWrapper.setVersion(VERSION); - requestWrapper.setRequesttime(LocalDateTime.now(ZoneId.of("UTC"))); - - } - - @WithUserDetails("reg-processor") - @Ignore - @Test - public void testInvalidSpecEncrypt() throws Exception { - - KeyPairGenerateResponseDto keyPairGenerateResponseDto = new KeyPairGenerateResponseDto("badCertificateData", null, LocalDateTime.now(), - LocalDateTime.now().plusDays(100), LocalDateTime.now()); - - String appid = "REGISTRATION"; - String data = "dXJ2aWw"; - String refid = "ref123"; - String timeStamp = "2018-12-06T12:07:44.403Z"; - - requestDto = new CryptomanagerRequestDto(); - requestWrapper.setRequest(requestDto); - requestDto.setApplicationId(appid); - requestDto.setData(data); - requestDto.setReferenceId(refid); - requestDto.setTimeStamp(DateUtils.parseToLocalDateTime(timeStamp)); - - when(keyManagerService.getCertificate(Mockito.eq(appid), Mockito.eq(Optional.of(refid)))) - .thenReturn(keyPairGenerateResponseDto); - String requestBody = objectMapper.writeValueAsString(requestWrapper); - MvcResult result = mockMvc - .perform(post("/encrypt").contentType(MediaType.APPLICATION_JSON).content(requestBody)) - .andExpect(status().isOk()).andReturn(); - ResponseWrapper responseWrapper = objectMapper.readValue( - result.getResponse().getContentAsString(), - new TypeReference>() { - }); - assertThat(responseWrapper.getErrors().get(0).getErrorCode(), is("KER-KMS-013")); - } - - @WithUserDetails("reg-processor") - - @Test - public void testMethodArgumentNotValidException() throws Exception { - requestDto = new CryptomanagerRequestDto(); - requestWrapper.setRequest(requestDto); - - requestDto.setApplicationId(""); - requestDto.setData(""); - requestDto.setReferenceId("ref123"); - requestDto.setTimeStamp(DateUtils.parseToLocalDateTime("2018-12-06T12:07:44.403Z")); - String requestBody = objectMapper.writeValueAsString(requestWrapper); - MvcResult result = mockMvc - .perform(post("/encrypt").contentType(MediaType.APPLICATION_JSON).content(requestBody)) - .andExpect(status().isOk()).andReturn(); - ResponseWrapper responseWrapper = objectMapper.readValue( - result.getResponse().getContentAsString(), - new TypeReference>() { - }); - assertThat(responseWrapper.getErrors().get(0).getErrorCode(), is("KER-KMS-005")); - } - - @WithUserDetails("reg-processor") - - @Test - public void testInvalidFormatException() throws Exception { - String requestBody = "{\r\n" + "\"id\":\"\",\r\n" + "\"version\":\"\",\r\n" + "\"requesttime\":\"\",\r\n" - + "\"metadata\":{},\r\n" + "\"request\":{\r\n" + " \"applicationId\": \"REGISTRATION\",\r\n" - + " \"data\": \"dXJ2aWwKCgoKam9zaGk=\",\r\n" + " \"referenceId\": \"REF01\",\r\n" - + " \"timeStamp\": \"2018-12-1\"\r\n" + "}\r\n" + "}"; - MvcResult result = mockMvc - .perform(post("/encrypt").contentType(MediaType.APPLICATION_JSON).content(requestBody)) - .andExpect(status().isOk()).andReturn(); - ResponseWrapper responseWrapper = objectMapper.readValue( - result.getResponse().getContentAsString(), - new TypeReference>() { - }); - assertThat(responseWrapper.getErrors().get(0).getErrorCode(), is("KER-KMS-005")); - } - - @WithUserDetails("reg-processor") - - @Test - public void testIllegalArgumentException() throws Exception { - requestDto = new CryptomanagerRequestDto(); - requestWrapper.setRequest(requestDto); - - requestDto.setApplicationId("REGISTRATION"); - requestDto.setData("dXJ2aWw"); - requestDto.setReferenceId("ref123"); - requestDto.setTimeStamp(DateUtils.parseToLocalDateTime("2018-12-06T12:07:44.403Z")); - String requestBody = objectMapper.writeValueAsString(requestWrapper); - MvcResult result = mockMvc - .perform(post("/decrypt").contentType(MediaType.APPLICATION_JSON).content(requestBody)) - .andExpect(status().isOk()).andReturn(); - ResponseWrapper responseWrapper = objectMapper.readValue( - result.getResponse().getContentAsString(), - new TypeReference>() { - }); - assertThat(responseWrapper.getErrors().get(0).getErrorCode(), is("KER-CRY-003")); - } - -} diff --git a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/cryptomanager/test/integration/CryptographicServiceIntegrationTest.java b/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/cryptomanager/test/integration/CryptographicServiceIntegrationTest.java deleted file mode 100644 index 6f6c8890800..00000000000 --- a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/cryptomanager/test/integration/CryptographicServiceIntegrationTest.java +++ /dev/null @@ -1,259 +0,0 @@ -package io.mosip.kernel.cryptomanager.test.integration; - -import static org.hamcrest.CoreMatchers.isA; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.when; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import java.security.KeyPair; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.cert.Certificate; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.util.Optional; - -import javax.crypto.SecretKey; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.http.MediaType; -import org.springframework.security.test.context.support.WithUserDetails; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.MvcResult; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; - -import io.mosip.kernel.core.crypto.spi.CryptoCoreSpec; -import io.mosip.kernel.core.http.RequestWrapper; -import io.mosip.kernel.core.http.ResponseWrapper; -import io.mosip.kernel.core.keymanager.spi.KeyStore; -import io.mosip.kernel.core.util.CryptoUtil; -import io.mosip.kernel.core.util.DateUtils; -import io.mosip.kernel.cryptomanager.dto.CryptoWithPinRequestDto; -import io.mosip.kernel.cryptomanager.dto.CryptoWithPinResponseDto; -import io.mosip.kernel.cryptomanager.dto.CryptomanagerRequestDto; -import io.mosip.kernel.cryptomanager.dto.CryptomanagerResponseDto; -import io.mosip.kernel.cryptomanager.util.CryptomanagerUtils; -import io.mosip.kernel.keygenerator.bouncycastle.KeyGenerator; -import io.mosip.kernel.keymanager.hsm.util.CertificateUtility; -import io.mosip.kernel.keymanagerservice.dto.KeyPairGenerateResponseDto; -import io.mosip.kernel.keymanagerservice.dto.PublicKeyResponse; -import io.mosip.kernel.keymanagerservice.dto.SymmetricKeyRequestDto; -import io.mosip.kernel.keymanagerservice.dto.SymmetricKeyResponseDto; -import io.mosip.kernel.keymanagerservice.service.KeymanagerService; -import io.mosip.kernel.keymanagerservice.test.KeymanagerTestBootApplication; -import io.mosip.kernel.keymanagerservice.util.KeymanagerUtil; - -@SpringBootTest(classes = KeymanagerTestBootApplication.class) -@RunWith(SpringRunner.class) -@AutoConfigureMockMvc -public class CryptographicServiceIntegrationTest { - - /** - * {@link CryptoCoreSpec} instance for cryptographic functionalities. - */ - @MockBean - private CryptoCoreSpec cryptoCore; - - @MockBean - private CryptomanagerUtils cryptomanagerUtil; - - @Autowired - private MockMvc mockMvc; - - @Autowired - private KeyGenerator generator; - - @Autowired - private ObjectMapper objectMapper; - - @MockBean - private KeyStore keyStore; - - /** The key manager. */ - @MockBean - private KeymanagerService keyManagerService; - - @MockBean - private KeymanagerUtil keymanagerUtil; - - private KeyPair keyPair; - - private Certificate cert; - - private String certData; - - private CryptomanagerRequestDto requestDto; - - private RequestWrapper requestWrapper; - - private CryptoWithPinRequestDto requestWithPinDto; - - private RequestWrapper requestWithPinWrapper; - - private static final String ID = "mosip.crypto.service"; - private static final String VERSION = "V1.0"; - - @Before - public void setUp() { - objectMapper = new ObjectMapper(); - objectMapper.registerModule(new JavaTimeModule()); - - keyPair = generator.getAsymmetricKey(); - cert = CertificateUtility.generateX509Certificate(keyPair.getPrivate(), keyPair.getPublic(), - "mosip", "mosip", "mosip", - "india", LocalDateTime.of(2010, 1, 1, 12, 00), LocalDateTime.of(2011, 1, 1, 12, 00), "SHA256withRSA", "BC"); - certData = keymanagerUtil.getPEMFormatedData(cert); - requestWrapper = new RequestWrapper<>(); - requestWrapper.setId(ID); - requestWrapper.setVersion(VERSION); - requestWrapper.setRequesttime(LocalDateTime.now(ZoneId.of("UTC"))); - - requestWithPinWrapper = new RequestWrapper<>(); - requestWithPinWrapper.setId(ID); - requestWithPinWrapper.setVersion(VERSION); - requestWithPinWrapper.setRequesttime(LocalDateTime.now(ZoneId.of("UTC"))); - } - - @WithUserDetails("reg-processor") - @Test - public void testEncrypt() throws Exception { - KeyPairGenerateResponseDto responseDto = new KeyPairGenerateResponseDto(certData, null, LocalDateTime.now(), - LocalDateTime.now(), LocalDateTime.now()); - when(cryptoCore.symmetricEncrypt(Mockito.any(), Mockito.any(), Mockito.any())) - .thenReturn("MOCKENCRYPTEDDATA".getBytes()); - when(cryptoCore.asymmetricEncrypt(Mockito.any(), Mockito.any())) - .thenReturn("MOCKENCRYPTEDSESSIONKEY".getBytes()); - - String appid = "REGISTRATION"; - String data = "dXJ2aWw"; - String refid = "ref123"; - String timeStamp = "2018-12-06T12:07:44.403Z"; - - requestDto = new CryptomanagerRequestDto(); - requestWrapper.setRequest(requestDto); - requestDto.setApplicationId(appid); - requestDto.setData(data); - requestDto.setReferenceId(refid); - requestDto.setTimeStamp(DateUtils.parseToLocalDateTime(timeStamp)); - when(cryptomanagerUtil.isDataValid(Mockito.anyString())).thenReturn(true); - when(cryptomanagerUtil.generateRandomBytes(Mockito.anyInt())).thenReturn("RANDOMBYTES".getBytes()); - when(cryptomanagerUtil.concatByteArrays(Mockito.any(), Mockito.any())).thenReturn("CONCATEDHEADER".getBytes()); - when(keyManagerService.getCertificate(Mockito.eq(appid), Mockito.eq(Optional.of(refid)))) - .thenReturn(responseDto); - when(cryptomanagerUtil.getCertificate(Mockito.any())).thenReturn(cert); - when(cryptomanagerUtil.getCertificateThumbprint(Mockito.any())).thenReturn("CERTTHUMBPRINT".getBytes()); - when(cryptomanagerUtil.concatCertThumbprint(Mockito.any(), Mockito.any())).thenReturn("CONCATEDENCRYPTEDSESSIONKEY".getBytes()); - - String requestBody = objectMapper.writeValueAsString(requestWrapper); - - MvcResult result = mockMvc - .perform(post("/encrypt").contentType(MediaType.APPLICATION_JSON).content(requestBody)) - .andExpect(status().isOk()).andReturn(); - ResponseWrapper responseWrapper = objectMapper.readValue(result.getResponse().getContentAsString(), - ResponseWrapper.class); - CryptomanagerResponseDto cryptomanagerResponseDto = objectMapper.readValue( - objectMapper.writeValueAsString(responseWrapper.getResponse()), CryptomanagerResponseDto.class); - - assertThat(cryptomanagerResponseDto.getData(), isA(String.class)); - } - - @WithUserDetails("reg-processor") - @Test - public void testDecrypt() throws Exception { - SymmetricKeyResponseDto symmetricKeyResponseDto = new SymmetricKeyResponseDto( - CryptoUtil.encodeBase64(generator.getSymmetricKey().getEncoded())); - - when(cryptoCore.symmetricDecrypt(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn("dXJ2aWw".getBytes()); - - requestDto = new CryptomanagerRequestDto(); - requestWrapper.setRequest(requestDto); - String appid = "REGISTRATION"; - String data = "dXJ2aWwjS0VZX1NQTElUVEVSI3Vydmls"; - String refid = "ref123"; - LocalDateTime timeStamp = DateUtils.parseToLocalDateTime("2018-12-06T12:07:44.403Z"); - requestDto.setApplicationId(appid); - requestDto.setData(data); - requestDto.setReferenceId("ref123"); - requestDto.setTimeStamp(timeStamp); - SymmetricKeyRequestDto symmetricKeyRequestDto = new SymmetricKeyRequestDto( - appid, timeStamp, - refid, data, true); - when(keyManagerService.decryptSymmetricKey(Mockito.any())).thenReturn(symmetricKeyResponseDto); - when(cryptomanagerUtil.parseEncryptKeyHeader(Mockito.any())).thenReturn("".getBytes()); - String requestBody = objectMapper.writeValueAsString(requestWrapper); - MvcResult result = mockMvc - .perform(post("/decrypt").contentType(MediaType.APPLICATION_JSON).content(requestBody)) - .andExpect(status().isOk()).andReturn(); - ResponseWrapper responseWrapper = objectMapper.readValue(result.getResponse().getContentAsString(), - ResponseWrapper.class); - CryptomanagerResponseDto cryptomanagerResponseDto = objectMapper.readValue( - objectMapper.writeValueAsString(responseWrapper.getResponse()), CryptomanagerResponseDto.class); - - assertThat(cryptomanagerResponseDto.getData(), isA(String.class)); - } - - @WithUserDetails("reg-processor") - @Test - public void testEncryptWithPin() throws Exception { - when(cryptoCore.hash(Mockito.any(), Mockito.any())).thenReturn("MOCKSECRETKEY"); - when(cryptoCore.symmetricEncrypt(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) - .thenReturn("MOCKENCRYPTEDDATA".getBytes()); - when(cryptomanagerUtil.hexDecode(Mockito.any())).thenReturn("MOCKHEXDATA".getBytes()); - - requestWithPinDto = new CryptoWithPinRequestDto(); - requestWithPinDto.setData("Test Pin Encryption."); - requestWithPinDto.setUserPin("AB1234"); - requestWithPinWrapper.setRequest(requestWithPinDto); - - when(cryptomanagerUtil.isDataValid(Mockito.anyString())).thenReturn(true); - String requestBody = objectMapper.writeValueAsString(requestWithPinWrapper); - - MvcResult result = mockMvc - .perform(post("/encryptWithPin").contentType(MediaType.APPLICATION_JSON).content(requestBody)) - .andExpect(status().isOk()).andReturn(); - ResponseWrapper responseWrapper = objectMapper.readValue(result.getResponse().getContentAsString(), - ResponseWrapper.class); - CryptoWithPinResponseDto responseDto = objectMapper.readValue( - objectMapper.writeValueAsString(responseWrapper.getResponse()), CryptoWithPinResponseDto.class); - - assertThat(responseDto.getData(), isA(String.class)); - } - - @WithUserDetails("reg-processor") - @Test - public void testDecryptWithPin() throws Exception { - when(cryptoCore.hash(Mockito.any(), Mockito.any())).thenReturn("MOCKSECRETKEY"); - when(cryptoCore.symmetricDecrypt(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) - .thenReturn("MOCKENCRYPTEDDATA".getBytes()); - when(cryptomanagerUtil.hexDecode(Mockito.any())).thenReturn("MOCKHEXDATA".getBytes()); - - requestWithPinDto = new CryptoWithPinRequestDto(); - requestWithPinDto.setData("GeB26aCD779DlCzRKkHlwAyctlI1Fh5SvLTctR_8uCZW-OOUombMq_Pt9eM4r40nWxoD_Mt-j3OVd9t9uXrcmECh5ec"); - requestWithPinDto.setUserPin("AB1234"); - requestWithPinWrapper.setRequest(requestWithPinDto); - - when(cryptomanagerUtil.isDataValid(Mockito.anyString())).thenReturn(true); - String requestBody = objectMapper.writeValueAsString(requestWithPinWrapper); - - MvcResult result = mockMvc - .perform(post("/decryptWithPin").contentType(MediaType.APPLICATION_JSON).content(requestBody)) - .andExpect(status().isOk()).andReturn(); - ResponseWrapper responseWrapper = objectMapper.readValue(result.getResponse().getContentAsString(), - ResponseWrapper.class); - CryptoWithPinResponseDto responseDto = objectMapper.readValue( - objectMapper.writeValueAsString(responseWrapper.getResponse()), CryptoWithPinResponseDto.class); - - assertThat(responseDto.getData(), isA(String.class)); - } -} diff --git a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/cryptomanager/test/util/CryptographicUtilExceptionTest.java b/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/cryptomanager/test/util/CryptographicUtilExceptionTest.java deleted file mode 100644 index ad8d95d785e..00000000000 --- a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/cryptomanager/test/util/CryptographicUtilExceptionTest.java +++ /dev/null @@ -1,91 +0,0 @@ - -package io.mosip.kernel.cryptomanager.test.util; - -import static org.mockito.Mockito.when; -import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; -import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; - -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.http.MediaType; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.ClassMode; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.util.ReflectionTestUtils; -import org.springframework.test.web.client.MockRestServiceServer; -import org.springframework.web.client.RestTemplate; -import org.springframework.web.util.UriComponentsBuilder; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.kernel.core.exception.NoSuchAlgorithmException; -import io.mosip.kernel.core.exception.ServiceError; -import io.mosip.kernel.core.http.ResponseWrapper; -import io.mosip.kernel.core.keymanager.spi.KeyStore; -import io.mosip.kernel.core.util.CryptoUtil; -import io.mosip.kernel.core.util.DateUtils; -import io.mosip.kernel.cryptomanager.dto.CryptomanagerRequestDto; -import io.mosip.kernel.cryptomanager.dto.KeymanagerPublicKeyResponseDto; -import io.mosip.kernel.cryptomanager.util.CryptomanagerUtils; -import io.mosip.kernel.keymanagerservice.dto.KeyPairGenerateResponseDto; -import io.mosip.kernel.keymanagerservice.dto.PublicKeyResponse; -import io.mosip.kernel.keymanagerservice.exception.KeymanagerServiceException; -import io.mosip.kernel.keymanagerservice.service.KeymanagerService; -import io.mosip.kernel.keymanagerservice.test.KeymanagerTestBootApplication; - -@SpringBootTest(classes = KeymanagerTestBootApplication.class) - -@RunWith(SpringRunner.class) - -@AutoConfigureMockMvc - -@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) -public class CryptographicUtilExceptionTest { - - - @Autowired - CryptomanagerUtils cryptomanagerUtil; - - @MockBean - private KeyStore keyStore; - - /** The key manager. */ - @MockBean - private KeymanagerService keyManagerService; - - @Before - public void setUp() { - ReflectionTestUtils.setField(cryptomanagerUtil, "asymmetricAlgorithmName", "test"); - - } - - @Test(expected = KeymanagerServiceException.class) - public void testNoSuchAlgorithmEncrypt() throws Exception { - KeyPairGenerateResponseDto keyPairGenerateResponseDto = new KeyPairGenerateResponseDto("badCertificateData", null, LocalDateTime.now(), - LocalDateTime.now().plusDays(100), LocalDateTime.now()); - String appid = "REGISTRATION"; - String refid = "ref123"; - - when(keyManagerService.getCertificate(Mockito.eq(appid), Mockito.eq(Optional.of(refid)))) - .thenReturn(keyPairGenerateResponseDto); - CryptomanagerRequestDto cryptomanagerRequestDto = new CryptomanagerRequestDto("REGISTRATION", "ref123", - LocalDateTime.parse("2018-12-06T12:07:44.403Z", DateTimeFormatter.ISO_DATE_TIME), "test", - "ykrkpgjjtChlVdvDNJJEnQ", "VGhpcyBpcyBzYW1wbGUgYWFk", false); - cryptomanagerUtil.getCertificate(cryptomanagerRequestDto); - } -} diff --git a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/cryptomanager/test/util/CryptographicUtilWithKeyManagerTest.java b/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/cryptomanager/test/util/CryptographicUtilWithKeyManagerTest.java deleted file mode 100644 index 4af1355396a..00000000000 --- a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/cryptomanager/test/util/CryptographicUtilWithKeyManagerTest.java +++ /dev/null @@ -1,94 +0,0 @@ - -package io.mosip.kernel.cryptomanager.test.util; - -import static org.mockito.Mockito.when; - -import java.security.PrivateKey; -import java.security.PublicKey; -import java.time.LocalDateTime; - -import javax.crypto.SecretKey; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.web.client.RestTemplate; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.kernel.core.crypto.spi.CryptoCoreSpec; -import io.mosip.kernel.core.keymanager.spi.KeyStore; -import io.mosip.kernel.core.util.CryptoUtil; -import io.mosip.kernel.cryptomanager.dto.CryptomanagerRequestDto; -import io.mosip.kernel.cryptomanager.util.CryptomanagerUtils; -import io.mosip.kernel.keygenerator.bouncycastle.KeyGenerator; -import io.mosip.kernel.keymanagerservice.dto.KeyPairGenerateResponseDto; -import io.mosip.kernel.keymanagerservice.dto.SymmetricKeyResponseDto; -import io.mosip.kernel.keymanagerservice.exception.KeymanagerServiceException; -import io.mosip.kernel.keymanagerservice.service.KeymanagerService; -import io.mosip.kernel.keymanagerservice.test.KeymanagerTestBootApplication; - -@SpringBootTest(classes = KeymanagerTestBootApplication.class) - -@RunWith(SpringRunner.class) - -@AutoConfigureMockMvc -public class CryptographicUtilWithKeyManagerTest { - - @MockBean - private KeyStore keyStore; - - - @Autowired - private CryptomanagerUtils cryptomanagerUtil; - - @MockBean - private ObjectMapper objectMapper; - - @MockBean - private KeymanagerService keyManagerService; - - @Autowired - private KeyGenerator generator; - - @Autowired - private RestTemplate restTemplate; - - /** - * {@link CryptoCoreSpec} instance for cryptographic functionalities. - */ - @MockBean - private CryptoCoreSpec cryptoCore; - - @Before - public void setUp() { - KeyPairGenerateResponseDto keyPairGenerateResponseDto = new KeyPairGenerateResponseDto(); - keyPairGenerateResponseDto.setCertificate(""); - when(keyManagerService.getCertificate(Mockito.any(), Mockito.any())).thenReturn(keyPairGenerateResponseDto); - SymmetricKeyResponseDto symmetricKeyResponseDto = new SymmetricKeyResponseDto( - CryptoUtil.encodeBase64(generator.getSymmetricKey().getEncoded())); - when(keyManagerService.decryptSymmetricKey(Mockito.any())).thenReturn(symmetricKeyResponseDto); - } - - @Test(expected = KeymanagerServiceException.class) - public void testEncrypt() throws Exception { - cryptomanagerUtil.getCertificate( - new CryptomanagerRequestDto("REGISTRATION", "ref123", LocalDateTime.parse("2018-12-06T12:07:44.403"), - "dXJ2aWw", "ykrkpgjjtChlVdvDNJJEnQ", "VGhpcyBpcyBzYW1wbGUgYWFk", false)); - } - - @Test - public void testDecrypt() throws Exception { - when(cryptoCore.symmetricDecrypt(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn("dXJ2aWw".getBytes()); - cryptomanagerUtil.getDecryptedSymmetricKey( - new CryptomanagerRequestDto("REGISTRATION", "ref123", LocalDateTime.parse("2018-12-06T12:07:44.403"), - "dXJ2aWwjS0VZX1NQTElUVEVSI3Vydmls", "ykrkpgjjtChlVdvDNJJEnQ", "VGhpcyBpcyBzYW1wbGUgYWFk", false)); - } - -} diff --git a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keygenerator/bouncycastle/test/KeyGeneratorBootApplication.java b/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keygenerator/bouncycastle/test/KeyGeneratorBootApplication.java deleted file mode 100644 index ca0c1e05041..00000000000 --- a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keygenerator/bouncycastle/test/KeyGeneratorBootApplication.java +++ /dev/null @@ -1,15 +0,0 @@ -package io.mosip.kernel.keygenerator.bouncycastle.test; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.ComponentScan; - -@SpringBootApplication -@ComponentScan({ "io.mosip.kernel.keygenerator.*" }) -public class KeyGeneratorBootApplication { - public static void main(String[] args) { - SpringApplication.run(KeyGeneratorBootApplication.class, args); - - } - -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keygenerator/bouncycastle/test/KeyGeneratorExceptionTest.java b/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keygenerator/bouncycastle/test/KeyGeneratorExceptionTest.java deleted file mode 100644 index 7e311b15003..00000000000 --- a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keygenerator/bouncycastle/test/KeyGeneratorExceptionTest.java +++ /dev/null @@ -1,24 +0,0 @@ -package io.mosip.kernel.keygenerator.bouncycastle.test; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.junit4.SpringRunner; - -import io.mosip.kernel.core.exception.NoSuchAlgorithmException; -import io.mosip.kernel.keygenerator.bouncycastle.util.KeyGeneratorUtils; - - -@RunWith(SpringRunner.class) -public class KeyGeneratorExceptionTest { - - @Test(expected = NoSuchAlgorithmException.class) - public void testGetAsymmetricKeyException() { - KeyGeneratorUtils.getKeyPairGenerator("AES", 204); - } - - @Test(expected = NoSuchAlgorithmException.class) - public void testGetSymmetricKeyException() { - KeyGeneratorUtils.getKeyGenerator("RSA", 204); - } - -} diff --git a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keygenerator/bouncycastle/test/KeyGeneratorTest.java b/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keygenerator/bouncycastle/test/KeyGeneratorTest.java deleted file mode 100644 index 4c748c1fe7b..00000000000 --- a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keygenerator/bouncycastle/test/KeyGeneratorTest.java +++ /dev/null @@ -1,36 +0,0 @@ -package io.mosip.kernel.keygenerator.bouncycastle.test; - -import static org.hamcrest.CoreMatchers.isA; -import static org.junit.Assert.assertThat; - -import java.security.KeyPair; - -import javax.crypto.SecretKey; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import io.mosip.kernel.keygenerator.bouncycastle.KeyGenerator; - -@SpringBootTest -@RunWith(SpringRunner.class) -public class KeyGeneratorTest { - - @Autowired - KeyGenerator keyGenerator; - - @Test - public void testGetSymmetricKey() { - assertThat(keyGenerator.getSymmetricKey(), isA(SecretKey.class)); - } - - @Test - public void testGetAsymmetricKey() { - assertThat(keyGenerator.getAsymmetricKey(), isA(KeyPair.class)); - - } - -} diff --git a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keymanager/hsm/test/CertificateUtilityExceptionTest.java b/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keymanager/hsm/test/CertificateUtilityExceptionTest.java deleted file mode 100644 index ca7c6b207bf..00000000000 --- a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keymanager/hsm/test/CertificateUtilityExceptionTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package io.mosip.kernel.keymanager.hsm.test; - -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.SecureRandom; -import java.security.Security; -import java.time.LocalDateTime; - -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.junit4.SpringRunner; - -import io.mosip.kernel.core.keymanager.exception.KeystoreProcessingException; -import io.mosip.kernel.keymanager.hsm.util.CertificateUtility; - -@RunWith(SpringRunner.class) -public class CertificateUtilityExceptionTest { - - BouncyCastleProvider provider; - SecureRandom random; - KeyPairGenerator keyGenerator; - - @Before - public void setUp() throws Exception { - provider = new BouncyCastleProvider(); - Security.addProvider(provider); - random = new SecureRandom(); - } - - @Test(expected = KeystoreProcessingException.class) - public void testGenerateX509CertificateException() throws Exception { - keyGenerator = KeyPairGenerator.getInstance("ELGAMAL", provider); - keyGenerator.initialize(2048, random); - KeyPair keyPair = keyGenerator.generateKeyPair(); - CertificateUtility.generateX509Certificate(keyPair.getPrivate(), keyPair.getPublic(), "commonName", "organizationalUnit", - "organization", "country", LocalDateTime.now(), LocalDateTime.now().minusDays(100), "SHA256withRSA", "BC"); - } -} diff --git a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keymanager/hsm/test/KeyStoreImplExceptionTest.java b/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keymanager/hsm/test/KeyStoreImplExceptionTest.java deleted file mode 100644 index a01c53f539b..00000000000 --- a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keymanager/hsm/test/KeyStoreImplExceptionTest.java +++ /dev/null @@ -1,120 +0,0 @@ -package io.mosip.kernel.keymanager.hsm.test; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.security.KeyStore; -import java.security.KeyStore.PrivateKeyEntry; -import java.security.KeyStore.SecretKeyEntry; -import java.security.KeyStoreException; -import java.security.KeyStoreSpi; -import java.security.SecureRandom; -import java.security.Security; -import java.security.UnrecoverableKeyException; - -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.util.ReflectionTestUtils; - -import io.mosip.kernel.core.keymanager.exception.KeystoreProcessingException; -import io.mosip.kernel.core.keymanager.exception.NoSuchSecurityProviderException; -import io.mosip.kernel.core.keymanager.model.CertificateParameters; -import io.mosip.kernel.keymanager.hsm.impl.KeyStoreImpl; -import io.mosip.kernel.keymanager.hsm.impl.offline.OLKeyStoreImpl; - -@RunWith(SpringRunner.class) -public class KeyStoreImplExceptionTest { - - private java.security.KeyStore keyStore; - - private KeyStoreImpl keyStoreImpl; - - private OLKeyStoreImpl offlineImpl; - - BouncyCastleProvider provider; - SecureRandom random; - - @Before - public void setUp() throws Exception { - KeyStoreSpi keyStoreSpiMock = mock(KeyStoreSpi.class); - keyStore = new java.security.KeyStore(keyStoreSpiMock, null, "test") { - }; - keyStoreImpl = new KeyStoreImpl(); - offlineImpl = new OLKeyStoreImpl(null); - ReflectionTestUtils.setField(keyStoreImpl, "configPath", "configPath"); - ReflectionTestUtils.setField(keyStoreImpl, "keystoreType", "keystoreType"); - ReflectionTestUtils.setField(keyStoreImpl, "keystorePass", "keystorePass"); - ReflectionTestUtils.setField(keyStoreImpl, "keyStore", offlineImpl); - keyStore.load(null); - provider = new BouncyCastleProvider(); - Security.addProvider(provider); - random = new SecureRandom(); - - } - - @Test(expected = KeystoreProcessingException.class) - public void testGetKeyKeystoreProcessingException() throws Exception { - when(keyStore.getKey(Mockito.anyString(), Mockito.any(char[].class))) - .thenThrow(UnrecoverableKeyException.class); - keyStoreImpl.getKey("REGISTRATION"); - } - - @Test(expected = KeystoreProcessingException.class) - public void testGetAsymmetricKeyNoSuchSecurityProviderException() throws Exception { - when(keyStore.entryInstanceOf("alias", PrivateKeyEntry.class)).thenReturn(false); - keyStoreImpl.getAsymmetricKey("alias"); - } - - @Test(expected = KeystoreProcessingException.class) - public void testGetAsymmetricKeyKeystoreProcessingException() throws Exception { - when(keyStore.entryInstanceOf("alias", PrivateKeyEntry.class)).thenReturn(true); - when(keyStore.getEntry(Mockito.anyString(), Mockito.any())).thenThrow(KeyStoreException.class); - keyStoreImpl.getAsymmetricKey("alias"); - } - - @Test(expected = KeystoreProcessingException.class) - public void testGetSymmetricKeyNoSuchSecurityProviderException() throws Exception { - when(keyStore.entryInstanceOf("alias", PrivateKeyEntry.class)).thenReturn(false); - keyStoreImpl.getSymmetricKey("alias"); - } - - @Test(expected = KeystoreProcessingException.class) - public void testGetSymmetricKeyKeystoreProcessingException() throws Exception { - when(keyStore.entryInstanceOf("alias", SecretKeyEntry.class)).thenReturn(true); - when(keyStore.getEntry(Mockito.anyString(), Mockito.any())).thenThrow(KeyStoreException.class); - keyStoreImpl.getSymmetricKey("alias"); - } - - @Ignore - @Test(expected = KeystoreProcessingException.class) - public void testAfterPropertiesSet() throws Exception { - keyStoreImpl.afterPropertiesSet(); - } - - @Test(expected = KeystoreProcessingException.class) - public void testDeleteKeyKeystoreProcessingException() throws Exception { - keyStore = mock(KeyStore.class); - keyStoreImpl.deleteKey("alias"); - } - - @Test(expected = KeystoreProcessingException.class) - public void testStoreSymmetricKeyKeystoreProcessingException() throws Exception { - keyStore = mock(KeyStore.class); - javax.crypto.KeyGenerator keyGenerator = javax.crypto.KeyGenerator.getInstance("AES", provider); - keyGenerator.init(256, random); - keyStoreImpl.generateAndStoreSymmetricKey("alias"); - } - - @Test(expected = KeystoreProcessingException.class) - public void testStoreAsymmetricKeyKeystoreProcessingException() throws Exception { - keyStore = mock(KeyStore.class); - CertificateParameters certParams = mock(CertificateParameters.class); - keyStoreImpl.generateAndStoreAsymmetricKey("alias", "signAlias", certParams); - } - -} diff --git a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keymanager/hsm/test/KeyStoreImplTest.java b/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keymanager/hsm/test/KeyStoreImplTest.java deleted file mode 100644 index e37bcc750b1..00000000000 --- a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keymanager/hsm/test/KeyStoreImplTest.java +++ /dev/null @@ -1,179 +0,0 @@ -package io.mosip.kernel.keymanager.hsm.test; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.isA; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.security.Key; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.KeyStore.PrivateKeyEntry; -import java.security.KeyStore.SecretKeyEntry; -import java.security.KeyStoreSpi; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.Security; -import java.security.cert.X509Certificate; -import java.time.LocalDateTime; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.util.ReflectionTestUtils; -import io.mosip.kernel.keymanager.hsm.impl.KeyStoreImpl; -import io.mosip.kernel.keymanager.hsm.impl.pkcs.PKCS12KeyStoreImpl; -import io.mosip.kernel.keymanager.hsm.util.CertificateUtility; -import io.mosip.kernel.core.keymanager.model.CertificateParameters; - -@RunWith(SpringRunner.class) -public class KeyStoreImplTest { - - private java.security.KeyStore keyStore; - - private PKCS12KeyStoreImpl pkcs12Impl; - - private KeyStoreImpl keyStoreImpl; - - private CertificateParameters certParams; - - BouncyCastleProvider provider; - SecureRandom random; - - @Before - public void setUp() throws Exception { - KeyStoreSpi keyStoreSpiMock = mock(KeyStoreSpi.class); - keyStore = new java.security.KeyStore(keyStoreSpiMock, null, "test") { - }; - keyStoreImpl = new KeyStoreImpl(); - - Map map = new HashMap<>(); - map.put("CONFIG_FILE_PATH", "configPath"); - map.put("PKCS11_KEYSTORE_PASSWORD", "keystorePass"); - map.put("SYM_KEY_ALGORITHM", "AES"); - map.put("SYM_KEY_SIZE", "256"); - map.put("ASYM_KEY_ALGORITHM", "RSA"); - map.put("ASYM_KEY_SIZE", "2048"); - map.put("CERT_SIGN_ALGORITHM", "SHA256withRSA"); - pkcs12Impl = new PKCS12KeyStoreImpl(map); - //ReflectionTestUtils.setField(pkcs12Impl, "keyStore", keyStore); - keyStore.load(null); - pkcs12Impl.setKeyStore(keyStore); - ReflectionTestUtils.setField(keyStoreImpl, "keyStore", pkcs12Impl); - provider = new BouncyCastleProvider(); - Security.addProvider(provider); - random = new SecureRandom(); - certParams = new CertificateParameters("commonName", "organizationalUnit", - "organization", "location", "state", "country", LocalDateTime.now(), LocalDateTime.now().plusDays(100)); - } - - @Test - public void testStoreAsymmetricKey() throws Exception { - KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("RSA", provider); - keyGenerator.initialize(2048, random); - KeyPair keyPair = keyGenerator.generateKeyPair(); - keyStoreImpl.generateAndStoreAsymmetricKey("alias", null, certParams); - X509Certificate[] chain = new X509Certificate[1]; - chain[0] = CertificateUtility.generateX509Certificate(keyPair.getPrivate(), keyPair.getPublic(), "commonName", "organizationalUnit", - "organization", "country", LocalDateTime.now(), LocalDateTime.now().plusDays(100), "SHA256withRSA", "BC"); - PrivateKeyEntry keyEntry = new PrivateKeyEntry(keyPair.getPrivate(), chain); - when(keyStore.entryInstanceOf("alias", PrivateKeyEntry.class)).thenReturn(true); - when(keyStore.getEntry(Mockito.anyString(), Mockito.any())).thenReturn(keyEntry); - assertThat(keyStoreImpl.getPrivateKey("alias"), isA(PrivateKey.class)); - } - - @Test - public void testStoreSymmetricKey() throws Exception { - javax.crypto.KeyGenerator keyGenerator = javax.crypto.KeyGenerator.getInstance("AES"); - keyGenerator.init(256, random); - SecretKeyEntry secretKeyEntry = new SecretKeyEntry(keyGenerator.generateKey()); - keyStoreImpl.generateAndStoreSymmetricKey("alias"); - when(keyStore.entryInstanceOf("alias", SecretKeyEntry.class)).thenReturn(true); - when(keyStore.getEntry(Mockito.anyString(), Mockito.any())).thenReturn(secretKeyEntry); - assertThat(keyStoreImpl.getSymmetricKey("alias"), isA(Key.class)); - } - - @Test - public void testDeleteKey() throws Exception { - keyStoreImpl.deleteKey("alias"); - assertThat(keyStoreImpl.getKey("alias"), is(nullValue())); - } - - @Test - public void testGetPrivateKey() throws Exception { - KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("RSA", provider); - keyGenerator.initialize(2048, random); - KeyPair keyPair = keyGenerator.generateKeyPair(); - X509Certificate[] chain = new X509Certificate[1]; - chain[0] = CertificateUtility.generateX509Certificate(keyPair.getPrivate(), keyPair.getPublic(), "commonName", "organizationalUnit", - "organization", "country", LocalDateTime.now(), LocalDateTime.now().plusDays(100), "SHA256withRSA", "BC"); - PrivateKeyEntry keyEntry = new PrivateKeyEntry(keyPair.getPrivate(), chain); - when(keyStore.entryInstanceOf("alias", PrivateKeyEntry.class)).thenReturn(true); - when(keyStore.getEntry(Mockito.anyString(), Mockito.any())).thenReturn(keyEntry); - assertThat(keyStoreImpl.getPrivateKey("alias"), isA(PrivateKey.class)); - } - - @Test - public void testGetPublicKey() throws Exception { - KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("RSA", provider); - keyGenerator.initialize(2048, random); - KeyPair keyPair = keyGenerator.generateKeyPair(); - X509Certificate[] chain = new X509Certificate[1]; - chain[0] = CertificateUtility.generateX509Certificate(keyPair.getPrivate(), keyPair.getPublic(), "commonName", "organizationalUnit", - "organization", "country", LocalDateTime.now(), LocalDateTime.now().plusDays(100), "SHA256withRSA", "BC"); - PrivateKeyEntry keyEntry = new PrivateKeyEntry(keyPair.getPrivate(), chain); - when(keyStore.entryInstanceOf("alias", PrivateKeyEntry.class)).thenReturn(true); - when(keyStore.getEntry(Mockito.anyString(), Mockito.any())).thenReturn(keyEntry); - assertThat(keyStoreImpl.getPublicKey("alias"), isA(PublicKey.class)); - } - - @Test - public void testGetCertificate() throws Exception { - KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("RSA", provider); - keyGenerator.initialize(2048, random); - KeyPair keyPair = keyGenerator.generateKeyPair(); - X509Certificate[] chain = new X509Certificate[1]; - chain[0] = CertificateUtility.generateX509Certificate(keyPair.getPrivate(), keyPair.getPublic(), "commonName", "organizationalUnit", - "organization", "country", LocalDateTime.now(), LocalDateTime.now().plusDays(100), "SHA256withRSA", "BC"); - PrivateKeyEntry keyEntry = new PrivateKeyEntry(keyPair.getPrivate(), chain); - when(keyStore.entryInstanceOf("alias", PrivateKeyEntry.class)).thenReturn(true); - when(keyStore.getEntry(Mockito.anyString(), Mockito.any())).thenReturn(keyEntry); - assertThat(keyStoreImpl.getCertificate("alias"), isA(X509Certificate.class)); - } - - @Test - public void testGetAllAlias() throws Exception { - @SuppressWarnings("unchecked") - Enumeration enumeration = mock(Enumeration.class); - when(keyStore.aliases()).thenReturn(enumeration); - assertThat(keyStoreImpl.getAllAlias(), isA(List.class)); - } - - @Test - public void testGetKey() throws Exception { - Key key = mock(Key.class); - when(keyStore.getKey(Mockito.anyString(), Mockito.any())).thenReturn(key); - assertThat(keyStoreImpl.getKey("alias"), isA(Key.class)); - } - - @Test - public void testGetSymmetricKey() throws Exception { - javax.crypto.KeyGenerator keyGenerator = javax.crypto.KeyGenerator.getInstance("AES", provider); - keyGenerator.init(256, random); - SecretKeyEntry secretKeyEntry = new SecretKeyEntry(keyGenerator.generateKey()); - when(keyStore.entryInstanceOf("alias", SecretKeyEntry.class)).thenReturn(true); - when(keyStore.getEntry(Mockito.anyString(), Mockito.any())).thenReturn(secretKeyEntry); - assertThat(keyStoreImpl.getSymmetricKey("alias"), isA(Key.class)); - } - -} diff --git a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keymanagerservice/test/KeymanagerTestBootApplication.java b/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keymanagerservice/test/KeymanagerTestBootApplication.java deleted file mode 100644 index d52e3d39b18..00000000000 --- a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keymanagerservice/test/KeymanagerTestBootApplication.java +++ /dev/null @@ -1,27 +0,0 @@ -package io.mosip.kernel.keymanagerservice.test; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -/** - * Crypto manager application - * - * @author Urvil Joshi - * @since 1.0.0 - * - */ -@SpringBootApplication(scanBasePackages = { "io.mosip.kernel.keymanagerservice.*","io.mosip.kernel.cryptomanager.*", - "io.mosip.kernel.signature.*","io.mosip.kernel.tokenidgenerator.*", "io.mosip.kernel.lkeymanager.*", - "io.mosip.kernel.keymanager.hsm.*", "io.mosip.kernel.keygenerator.*", - "io.mosip.kernel.crypto.jce.*", "io.mosip.kernel.partnercertservice.*"}) -public class KeymanagerTestBootApplication { - - /** - * Main method to run spring boot application - * - * @param args args - */ - public static void main(String[] args) { - SpringApplication.run(KeymanagerTestBootApplication.class, args); - } -} diff --git a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keymanagerservice/test/config/TestConfig.java b/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keymanagerservice/test/config/TestConfig.java deleted file mode 100644 index 2738be25cec..00000000000 --- a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keymanagerservice/test/config/TestConfig.java +++ /dev/null @@ -1,40 +0,0 @@ -package io.mosip.kernel.keymanagerservice.test.config; - -import java.security.KeyManagementException; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.X509Certificate; - -import javax.net.ssl.SSLContext; - -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.ssl.TrustStrategy; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; -import org.springframework.web.client.RestTemplate; -@Configuration -public class TestConfig { - - @Bean - public RestTemplate restTemplateConfig() - throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException { - - TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true; - - SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy) - .build(); - - SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext); - - CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build(); - HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); - - requestFactory.setHttpClient(httpClient); - return new RestTemplate(requestFactory); - - } - -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keymanagerservice/test/config/TestSecurityConfig.java b/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keymanagerservice/test/config/TestSecurityConfig.java deleted file mode 100644 index 4ee29da4c43..00000000000 --- a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keymanagerservice/test/config/TestSecurityConfig.java +++ /dev/null @@ -1,77 +0,0 @@ -package io.mosip.kernel.keymanagerservice.test.config; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import javax.servlet.http.HttpServletResponse; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.builders.WebSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.config.http.SessionCreationPolicy; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.security.core.userdetails.User; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.provisioning.InMemoryUserDetailsManager; -import org.springframework.security.web.AuthenticationEntryPoint; -import org.springframework.security.web.firewall.DefaultHttpFirewall; -import org.springframework.security.web.firewall.HttpFirewall; - -@Configuration -@EnableWebSecurity -@EnableGlobalMethodSecurity(prePostEnabled = true) -public class TestSecurityConfig extends WebSecurityConfigurerAdapter { - - @Bean - public HttpFirewall defaultHttpFirewall() { - return new DefaultHttpFirewall(); - } - - @Override - public void configure(WebSecurity webSecurity) throws Exception { - webSecurity.ignoring().antMatchers(allowedEndPoints()); - super.configure(webSecurity); - webSecurity.httpFirewall(defaultHttpFirewall()); - } - - private String[] allowedEndPoints() { - return new String[] { "/assets/**", "/icons/**", "/screenshots/**", "/favicon**", "/**/favicon**", "/css/**", - "/js/**", "/*/error**", "/*/webjars/**", "/*/v2/api-docs", "/*/configuration/ui", - "/*/configuration/security", "/*/swagger-resources/**", "/*/swagger-ui.html" }; - } - - @Override - protected void configure(final HttpSecurity httpSecurity) throws Exception { - httpSecurity.csrf().disable(); - httpSecurity.httpBasic().and().authorizeRequests().anyRequest().authenticated().and().sessionManagement() - .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().exceptionHandling() - .authenticationEntryPoint(unauthorizedEntryPoint()); - } - - @Bean - public AuthenticationEntryPoint unauthorizedEntryPoint() { - return (request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED); - } - - @Bean - public UserDetailsService userDetailsService() { - List users = new ArrayList<>(); - users.add(new User("reg-officer", "mosip", - Arrays.asList(new SimpleGrantedAuthority("ROLE_REGISTRATION_OFFICER")))); - users.add(new User("reg-supervisor", "mosip", - Arrays.asList(new SimpleGrantedAuthority("ROLE_REGISTRATION_SUPERVISOR")))); - users.add(new User("reg-admin", "mosip", Arrays.asList(new SimpleGrantedAuthority("ROLE_REGISTRATION_ADMIN")))); - users.add(new User("reg-processor", "mosip", - Arrays.asList(new SimpleGrantedAuthority("ROLE_REGISTRATION_PROCESSOR")))); - users.add(new User("id-auth", "mosip", Arrays.asList(new SimpleGrantedAuthority("ROLE_ID_AUTHENTICATION")))); - users.add(new User("individual", "mosip", Arrays.asList(new SimpleGrantedAuthority("ROLE_INDIVIDUAL")))); - users.add(new User("test", "mosip", Arrays.asList(new SimpleGrantedAuthority("ROLE_TEST")))); - return new InMemoryUserDetailsManager(users); - } -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keymanagerservice/test/integration/KeymanagerIntegrationTest.java b/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keymanagerservice/test/integration/KeymanagerIntegrationTest.java deleted file mode 100644 index 2389bd18a59..00000000000 --- a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keymanagerservice/test/integration/KeymanagerIntegrationTest.java +++ /dev/null @@ -1,372 +0,0 @@ -package io.mosip.kernel.keymanagerservice.test.integration; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.isA; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.when; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.KeyStore.PrivateKeyEntry; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.Security; -import java.security.cert.X509Certificate; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; - -import javax.crypto.SecretKey; - -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.boot.test.mock.mockito.SpyBean; -import org.springframework.http.MediaType; -import org.springframework.security.test.context.support.WithUserDetails; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.MvcResult; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; -import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; - -import io.mosip.kernel.core.crypto.spi.CryptoCoreSpec; -import io.mosip.kernel.core.http.RequestWrapper; -import io.mosip.kernel.core.http.ResponseWrapper; -import io.mosip.kernel.core.keymanager.spi.KeyStore; -import io.mosip.kernel.keymanager.hsm.util.CertificateUtility; -import io.mosip.kernel.keymanagerservice.constant.KeymanagerConstant; -import io.mosip.kernel.keymanagerservice.dto.PublicKeyResponse; -import io.mosip.kernel.signature.dto.SignatureRequestDto; -import io.mosip.kernel.signature.dto.SignatureResponseDto; -import io.mosip.kernel.keymanagerservice.dto.SymmetricKeyRequestDto; -import io.mosip.kernel.keymanagerservice.entity.KeyAlias; -import io.mosip.kernel.keymanagerservice.entity.KeyPolicy; -import io.mosip.kernel.keymanagerservice.repository.KeyAliasRepository; -import io.mosip.kernel.keymanagerservice.repository.KeyPolicyRepository; -import io.mosip.kernel.keymanagerservice.repository.KeyStoreRepository; -import io.mosip.kernel.keymanagerservice.test.KeymanagerTestBootApplication; -import io.mosip.kernel.keymanagerservice.util.KeymanagerUtil; - -/** - * @author Dharmesh Khandelwal - * @since 1.0.0 - * - */ - -@SpringBootTest(classes = { KeymanagerTestBootApplication.class }) -@RunWith(SpringRunner.class) -@AutoConfigureMockMvc -public class KeymanagerIntegrationTest { - - @Autowired - private MockMvc mockMvc; - - @Autowired - private ObjectMapper objectMapper; - - @MockBean - private KeyStore keyStore; - - @MockBean - private KeyAliasRepository keyAliasRepository; - - @MockBean - private KeyPolicyRepository keyPolicyRepository; - - @MockBean - private KeyStoreRepository keyStoreRepository; - - /** - * {@link CryptoCoreSpec} instance for cryptographic functionalities. - */ - @MockBean - private CryptoCoreSpec cryptoCore; - - @Mock - private PublicKey publicKey; - - @Mock - private PrivateKey privateKey; - - private PrivateKeyEntry privateKeyEntry; - - @SpyBean - private KeymanagerUtil keymanagerUtil; - - private KeyPair key; - private ObjectMapper mapper; - private List keyalias; - private Optional keyPolicy; - private Optional dbKeyStore; - private X509Certificate x509Cert; - private String certificateData; - - private static final String ID = "mosip.crypto.service"; - private static final String VERSION = "V1.0"; - - private RequestWrapper requestWrapper; - - @Before - public void init() { - mapper = new ObjectMapper(); - keyalias = new ArrayList<>(); - keyPolicy = Optional.empty(); - dbKeyStore = Optional.empty(); - mapper.registerModule(new JavaTimeModule()); - mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); - - requestWrapper = new RequestWrapper<>(); - requestWrapper.setId(ID); - requestWrapper.setVersion(VERSION); - requestWrapper.setRequesttime(LocalDateTime.now(ZoneId.of("UTC"))); - } - - private void setupMultipleKeyAlias() { - keyalias = new ArrayList<>(); - keyalias.add(new KeyAlias("alias-one", "applicationId", "referenceId", LocalDateTime.of(2020, 1, 1, 12, 00), - LocalDateTime.of(2023, 1, 1, 12, 00), "status")); - keyalias.add(new KeyAlias("alias-two", "applicationId", "referenceId", LocalDateTime.of(2020, 1, 1, 12, 00), - LocalDateTime.of(2023, 1, 1, 12, 00), "status")); - keyalias.add(new KeyAlias("alias-root", "ROOT", "", LocalDateTime.of(2020, 1, 1, 12, 00), - LocalDateTime.of(2025, 1, 1, 12, 00), "status")); - - } - - private void setupSingleKeyAlias() { - keyalias = new ArrayList<>(); - keyalias.add(new KeyAlias("alias", "applicationId", "referenceId", LocalDateTime.of(2010, 1, 1, 12, 00), - LocalDateTime.of(2011, 1, 1, 12, 00), "status")); - keyalias.add(new KeyAlias("alias-root", "ROOT", "", LocalDateTime.of(2020, 1, 1, 12, 00), - LocalDateTime.of(2025, 1, 1, 12, 00), "status")); - } - - private void setupExpiryPolicy() { - keyPolicy = Optional.of(new KeyPolicy("applicationId", 365, true)); - } - - private void setupDBKeyStore() { - dbKeyStore = Optional.of(new io.mosip.kernel.keymanagerservice.entity.KeyStore("db-alias", - "test-public-key", "test-private#KEY_SPLITTER#-key", "alias")); - } - - private void setupDBKeyStoreWithCertificiate() { - dbKeyStore = Optional.of(new io.mosip.kernel.keymanagerservice.entity.KeyStore("db-alias", - certificateData, "test-private#KEY_SPLITTER#-key", "alias")); - } - - private void setupKey() throws NoSuchAlgorithmException { - BouncyCastleProvider provider = new BouncyCastleProvider(); - Security.addProvider(provider); - KeyPairGenerator keyGen = KeyPairGenerator.getInstance(KeymanagerConstant.RSA); - keyGen.initialize(1024); - key = keyGen.generateKeyPair(); - X509Certificate x509Certificate = CertificateUtility.generateX509Certificate(key.getPrivate(), key.getPublic(), - "mosip", "mosip", "mosip", - "india", LocalDateTime.of(2010, 1, 1, 12, 00), LocalDateTime.of(2011, 1, 1, 12, 00), "SHA256withRSA", "BC"); - X509Certificate[] chain = new X509Certificate[1]; - chain[0] = x509Certificate; - privateKeyEntry = new PrivateKeyEntry(key.getPrivate(), chain); - x509Cert = x509Certificate; - certificateData = keymanagerUtil.getPEMFormatedData(x509Certificate); - } - - @WithUserDetails("reg-processor") - @Test - public void decryptSymmetricKeyException() throws Exception { - when(keyAliasRepository.findByApplicationIdAndReferenceId(Mockito.any(), Mockito.any())).thenReturn(keyalias); - SymmetricKeyRequestDto symmetricKeyRequestDto = new SymmetricKeyRequestDto("applicationId", - LocalDateTime.parse("2010-05-01 12:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")), "", "", true); - requestWrapper.setRequest(symmetricKeyRequestDto); - String content = mapper.writeValueAsString(requestWrapper); - MvcResult result = mockMvc.perform(post("/decrypt").contentType(MediaType.APPLICATION_JSON).content(content)) - .andExpect(status().is(200)).andReturn(); - - // System.out.println(result.getResponse().getContentAsString()); - } - - @WithUserDetails("reg-processor") - @Test - public void decryptSymmetricKey() throws Exception { - setupSingleKeyAlias(); - when(keyAliasRepository.findByApplicationIdAndReferenceId(Mockito.any(), Mockito.any())).thenReturn(keyalias); - when(cryptoCore.asymmetricDecrypt(Mockito.any(), Mockito.any())).thenReturn("".getBytes()); - SymmetricKeyRequestDto symmetricKeyRequestDto = new SymmetricKeyRequestDto("applicationId", - LocalDateTime.parse("2010-05-01 12:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")), null, "", true); - requestWrapper.setRequest(symmetricKeyRequestDto); - String content = mapper.writeValueAsString(requestWrapper); - MvcResult result = mockMvc.perform(post("/decrypt").contentType(MediaType.APPLICATION_JSON).content(content)) - .andExpect(status().is(200)).andReturn(); - // System.out.println(result.getResponse().getContentAsString()); - } - - @WithUserDetails("reg-processor") - @Test - public void decryptSymmetricKeyWithReferenceIdException() throws Exception { - when(keyAliasRepository.findByApplicationIdAndReferenceId(Mockito.any(), Mockito.any())).thenReturn(keyalias); - when(cryptoCore.asymmetricDecrypt(Mockito.any(), Mockito.any())).thenReturn("".getBytes()); - SymmetricKeyRequestDto symmetricKeyRequestDto = new SymmetricKeyRequestDto("applicationId", - LocalDateTime.parse("2010-05-01 12:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")), "referenceId", - "", true); - requestWrapper.setRequest(symmetricKeyRequestDto); - String content = mapper.writeValueAsString(requestWrapper); - MvcResult result = mockMvc.perform(post("/decrypt").contentType(MediaType.APPLICATION_JSON).content(content)) - .andExpect(status().is(200)).andReturn(); - - // System.out.println(result.getResponse().getContentAsString()); - } - - @WithUserDetails("reg-processor") - @Test - public void decryptSymmetricKeyWithReferenceIdMultipleAliasException() throws Exception { - setupMultipleKeyAlias(); - when(keyAliasRepository.findByApplicationIdAndReferenceId(Mockito.any(), Mockito.any())).thenReturn(keyalias); - when(cryptoCore.asymmetricDecrypt(Mockito.any(), Mockito.any())).thenReturn("".getBytes()); - SymmetricKeyRequestDto symmetricKeyRequestDto = new SymmetricKeyRequestDto("applicationId", - LocalDateTime.parse("2010-05-01 12:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")), "referenceId", - "", true); - requestWrapper.setRequest(symmetricKeyRequestDto); - String content = mapper.writeValueAsString(requestWrapper); - MvcResult result = mockMvc.perform(post("/decrypt").contentType(MediaType.APPLICATION_JSON).content(content)) - .andExpect(status().is(200)).andReturn(); - // System.out.println(result.getResponse().getContentAsString()); - } - - @WithUserDetails("reg-processor") - @Test - public void decryptSymmetricKeyWithReferenceIdDBException() throws Exception { - setupSingleKeyAlias(); - when(keyAliasRepository.findByApplicationIdAndReferenceId(Mockito.any(), Mockito.any())).thenReturn(keyalias); - when(cryptoCore.asymmetricDecrypt(Mockito.any(), Mockito.any())).thenReturn("".getBytes()); - SymmetricKeyRequestDto symmetricKeyRequestDto = new SymmetricKeyRequestDto("applicationId", - LocalDateTime.parse("2010-05-01 12:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")), "referenceId", - "", true); - requestWrapper.setRequest(symmetricKeyRequestDto); - String content = mapper.writeValueAsString(requestWrapper); - MvcResult result = mockMvc.perform(post("/decrypt").contentType(MediaType.APPLICATION_JSON).content(content)) - .andExpect(status().is(200)).andReturn(); - // System.out.println(result.getResponse().getContentAsString()); - } - - @WithUserDetails("reg-processor") - @Test - public void decryptSymmetricKeyWithReferenceIdCryptoException() throws Exception { - setupSingleKeyAlias(); - setupDBKeyStore(); - when(keyStoreRepository.findByAlias(Mockito.any())).thenReturn(dbKeyStore); - when(keyAliasRepository.findByApplicationIdAndReferenceId(Mockito.any(), Mockito.any())).thenReturn(keyalias); - when(cryptoCore.asymmetricDecrypt(Mockito.any(), Mockito.any())).thenReturn("".getBytes()); - doReturn("".getBytes()).when(keymanagerUtil).decryptKey(Mockito.any(), Mockito.any(), Mockito.any()); - SymmetricKeyRequestDto symmetricKeyRequestDto = new SymmetricKeyRequestDto("applicationId", - LocalDateTime.parse("2010-05-01 12:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")), "referenceId", - "", true); - requestWrapper.setRequest(symmetricKeyRequestDto); - String content = mapper.writeValueAsString(requestWrapper); - MvcResult result = mockMvc.perform(post("/decrypt").contentType(MediaType.APPLICATION_JSON).content(content)) - .andExpect(status().is(200)).andReturn(); - // System.out.println(result.getResponse().getContentAsString()); - } - - @WithUserDetails("reg-processor") - @Test - public void decryptSymmetricKeyWithReferenceId() throws Exception { - setupSingleKeyAlias(); - setupDBKeyStore(); - setupKey(); - when(keyStoreRepository.findByAlias(Mockito.any())).thenReturn(dbKeyStore); - when(keyAliasRepository.findByApplicationIdAndReferenceId(Mockito.any(), Mockito.any())).thenReturn(keyalias); - when(cryptoCore.asymmetricDecrypt(Mockito.any(), Mockito.any())).thenReturn("".getBytes()); - doReturn(key.getPrivate().getEncoded()).when(keymanagerUtil).decryptKey(Mockito.any(), Mockito.any(), Mockito.any()); - SymmetricKeyRequestDto symmetricKeyRequestDto = new SymmetricKeyRequestDto("applicationId", - LocalDateTime.parse("2010-05-01 12:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")), "referenceId", - "", true); - requestWrapper.setRequest(symmetricKeyRequestDto); - String content = mapper.writeValueAsString(requestWrapper); - MvcResult result = mockMvc.perform(post("/decrypt").contentType(MediaType.APPLICATION_JSON).content(content)) - .andExpect(status().is(200)).andReturn(); - // System.out.println(result.getResponse().getContentAsString()); - } - - @WithUserDetails("reg-processor") - @Test - public void encryptWithMultipleAliasReferenceId() throws Exception { - - setupDBKeyStore(); - setupMultipleKeyAlias(); - setupKey(); - when(keyAliasRepository.findByApplicationIdAndReferenceId(Mockito.any(), Mockito.any())).thenReturn(keyalias); - when(cryptoCore.sign(Mockito.any(), Mockito.any())).thenReturn(""); - when(keyStore.getAsymmetricKey(Mockito.any())).thenReturn(privateKeyEntry); - - doReturn(key.getPrivate().getEncoded()).when(keymanagerUtil).decryptKey(Mockito.any(), Mockito.any(), Mockito.any()); - SignatureRequestDto encryptDataRequestDto = new SignatureRequestDto(); - encryptDataRequestDto.setApplicationId("applicationId"); - encryptDataRequestDto.setData("AMert334-edrtda"); - encryptDataRequestDto.setReferenceId("referenceId"); - encryptDataRequestDto.setTimeStamp("2010-05-01T12:00:00.000Z"); - RequestWrapper encryptRequestWrapper = new RequestWrapper<>(); - encryptRequestWrapper.setId(ID); - encryptRequestWrapper.setVersion(VERSION); - encryptRequestWrapper.setRequest(encryptDataRequestDto); - - String content = mapper.writeValueAsString(encryptRequestWrapper); - MvcResult result = mockMvc.perform(post("/sign").contentType(MediaType.APPLICATION_JSON).content(content)) - .andExpect(status().is(200)).andReturn(); - - ResponseWrapper responseWrapper = objectMapper.readValue( - result.getResponse().getContentAsString(), new TypeReference>() { - }); - assertThat(responseWrapper.getErrors().get(0).getErrorCode(), is("KER-KMS-003")); - } - - @WithUserDetails("reg-processor") - @Test - public void encryptWithEmptyAliasReferenceId() throws Exception { - - setupDBKeyStore(); - setupMultipleKeyAlias(); - setupKey(); - when(keyAliasRepository.findByApplicationIdAndReferenceId(Mockito.any(), Mockito.any())).thenReturn(keyalias); - when(cryptoCore.sign(Mockito.any(), Mockito.any())).thenReturn(""); - when(keyStore.getAsymmetricKey(Mockito.any())).thenReturn(privateKeyEntry); - - doReturn(key.getPrivate().getEncoded()).when(keymanagerUtil).decryptKey(Mockito.any(), Mockito.any(), Mockito.any()); - SignatureRequestDto encryptDataRequestDto = new SignatureRequestDto(); - encryptDataRequestDto.setApplicationId("applicationId"); - encryptDataRequestDto.setData("AMert334-edrtda"); - encryptDataRequestDto.setReferenceId("referenceId"); - encryptDataRequestDto.setTimeStamp("2019-05-01T12:00:00.00Z"); - RequestWrapper encryptRequestWrapper = new RequestWrapper<>(); - encryptRequestWrapper.setId(ID); - encryptRequestWrapper.setVersion(VERSION); - encryptRequestWrapper.setRequest(encryptDataRequestDto); - - String content = mapper.writeValueAsString(encryptRequestWrapper); - MvcResult result = mockMvc.perform(post("/sign").contentType(MediaType.APPLICATION_JSON).content(content)) - .andExpect(status().is(200)).andReturn(); - - ResponseWrapper responseWrapper = objectMapper.readValue( - result.getResponse().getContentAsString(), new TypeReference>() { - }); - assertThat(responseWrapper.getErrors().get(0).getErrorCode(), is("KER-KMS-003")); - } - -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keymanagerservice/test/logger/KeymanagerLoggerTest.java b/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keymanagerservice/test/logger/KeymanagerLoggerTest.java deleted file mode 100644 index bd0bcb116d1..00000000000 --- a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keymanagerservice/test/logger/KeymanagerLoggerTest.java +++ /dev/null @@ -1,24 +0,0 @@ -package io.mosip.kernel.keymanagerservice.test.logger; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - -import org.junit.Test; - -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.keymanagerservice.logger.KeymanagerLogger; - -/** - * @author Dharmesh Khandelwal - * @since 1.0.0 - * - */ -public class KeymanagerLoggerTest { - - @Test - public void test() { - Logger logger = KeymanagerLogger.getLogger(KeymanagerLoggerTest.class); - assertThat(logger.getClass().getName(), is("io.mosip.kernel.logger.logback.impl.Slf4jLoggerImpl")); - } - -} \ No newline at end of file diff --git a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keymanagerservice/test/util/KeymanagerUtilTest.java b/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keymanagerservice/test/util/KeymanagerUtilTest.java deleted file mode 100644 index 1ec0aa9fd06..00000000000 --- a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/keymanagerservice/test/util/KeymanagerUtilTest.java +++ /dev/null @@ -1,88 +0,0 @@ -package io.mosip.kernel.keymanagerservice.test.util; - -import static org.hamcrest.CoreMatchers.isA; -import static org.junit.Assert.assertThat; - -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.Security; -import java.security.cert.X509Certificate; -import java.time.LocalDateTime; - -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.test.context.junit4.SpringRunner; - -import io.mosip.kernel.core.keymanager.exception.KeystoreProcessingException; -import io.mosip.kernel.core.keymanager.model.CertificateEntry; -import io.mosip.kernel.core.keymanager.spi.KeyStore; -import io.mosip.kernel.core.util.DateUtils; -import io.mosip.kernel.keymanager.hsm.util.CertificateUtility; -import io.mosip.kernel.keymanagerservice.constant.KeymanagerConstant; -import io.mosip.kernel.keymanagerservice.repository.KeyAliasRepository; -import io.mosip.kernel.keymanagerservice.repository.KeyPolicyRepository; -import io.mosip.kernel.keymanagerservice.repository.KeyStoreRepository; -import io.mosip.kernel.keymanagerservice.test.KeymanagerTestBootApplication; -import io.mosip.kernel.keymanagerservice.util.KeymanagerUtil; - -@SpringBootTest(classes = { KeymanagerTestBootApplication.class }) -@RunWith(SpringRunner.class) -public class KeymanagerUtilTest { - - @MockBean - private KeyStore keyStore; - - @MockBean - private KeyAliasRepository keyAliasRepository; - - @MockBean - private KeyPolicyRepository keyPolicyRepository; - - @MockBean - private KeyStoreRepository keyStoreRepository; - - @Autowired - private KeymanagerUtil keymanagerUtil; - - private KeyPair keyPairMaster; - - private KeyPair keyPair; - - private X509Certificate[] chain; - - @Before - public void setupKey() throws NoSuchAlgorithmException { - BouncyCastleProvider provider = new BouncyCastleProvider(); - Security.addProvider(provider); - KeyPairGenerator keyGen = KeyPairGenerator.getInstance(KeymanagerConstant.RSA); - keyGen.initialize(2048); - keyPairMaster = keyGen.generateKeyPair(); - keyPair = keyGen.generateKeyPair(); - X509Certificate x509Certificate = CertificateUtility.generateX509Certificate(keyPair.getPrivate(), keyPair.getPublic(), "mosip", "mosip", "mosip", - "india", LocalDateTime.of(2010, 1, 1, 12, 00), LocalDateTime.of(2011, 1, 1, 12, 00), "SHA256withRSA", "BC"); - chain = new X509Certificate[1]; - chain[0] = x509Certificate; - } - - @Test - public void encryptdecryptPrivateKeyTest() { - byte[] key = keymanagerUtil.encryptKey(keyPair.getPrivate(), keyPairMaster.getPublic()); - assertThat(key, isA(byte[].class)); - assertThat(keymanagerUtil.decryptKey(key, keyPairMaster.getPrivate(), keyPairMaster.getPublic()), isA(byte[].class)); - } - - @Test(expected = KeystoreProcessingException.class) - public void isCertificateValidExceptionTest() { - CertificateEntry certificateEntry = new CertificateEntry( - chain, keyPair.getPrivate()); - keymanagerUtil.isCertificateValid(certificateEntry, DateUtils.parseUTCToDate("2019-05-01T12:00:00.00Z")); - } - -} diff --git a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/lkeymanager/test/controller/LicenseKeyManagerControllerTest.java b/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/lkeymanager/test/controller/LicenseKeyManagerControllerTest.java deleted file mode 100644 index 4eef6168fea..00000000000 --- a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/lkeymanager/test/controller/LicenseKeyManagerControllerTest.java +++ /dev/null @@ -1,100 +0,0 @@ -package io.mosip.kernel.lkeymanager.test.controller; - -import static org.hamcrest.CoreMatchers.is; -import static org.mockito.BDDMockito.given; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import java.time.LocalDateTime; -import java.time.Month; -import java.util.ArrayList; -import java.util.List; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.http.MediaType; -import org.springframework.security.test.context.support.WithUserDetails; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.kernel.core.keymanager.spi.KeyStore; -import io.mosip.kernel.core.licensekeymanager.spi.LicenseKeyManagerService; -import io.mosip.kernel.keymanagerservice.test.KeymanagerTestBootApplication; -import io.mosip.kernel.lkeymanager.dto.LicenseKeyGenerationDto; -import io.mosip.kernel.lkeymanager.dto.LicenseKeyMappingDto; - -@SpringBootTest(classes = KeymanagerTestBootApplication.class) -@RunWith(SpringRunner.class) -@AutoConfigureMockMvc -public class LicenseKeyManagerControllerTest { - - @MockBean - private KeyStore keyStore; - - @Autowired - private MockMvc mockMvc; - - @Autowired - private ObjectMapper objectMapper; - - @MockBean - private LicenseKeyManagerService service; - - /** - * TEST SCENARIO : Testing generation end point. - */ - @Test - @WithUserDetails("reg-processor") - public void licenseKeyGenerationTest() throws Exception { - LicenseKeyGenerationDto licenseKeyGenerationDto = new LicenseKeyGenerationDto(); - licenseKeyGenerationDto.setLicenseExpiryTime(LocalDateTime.of(2019, Month.FEBRUARY, 9, 10, 23, 0)); - licenseKeyGenerationDto.setTspId("TESTID"); - given(service.generateLicenseKey(Mockito.any())).willReturn("asdfghkngyrthgfyt"); - String json = objectMapper.writeValueAsString(licenseKeyGenerationDto); - mockMvc.perform(post("/license/generate").contentType(MediaType.APPLICATION_JSON).content(json)) - .andExpect(status().isOk()); - } - - /** - * TEST SCENARIO : Testing mapping end point. - */ - @Test - @WithUserDetails("reg-processor") - public void licenseKeyMappingTest() throws Exception { - List permissions = new ArrayList<>(); - permissions.add("permission1"); - permissions.add("permission2"); - LicenseKeyMappingDto licenseKeyMappingDto = new LicenseKeyMappingDto(); - licenseKeyMappingDto.setLicenseKey("fqELcNGoaEeuuJAs"); - licenseKeyMappingDto.setTspId("TESTID"); - licenseKeyMappingDto.setPermissions(permissions); - given(service.mapLicenseKey(Mockito.any())).willReturn("Mapped License with the permissions"); - String json = objectMapper.writeValueAsString(licenseKeyMappingDto); - mockMvc.perform(post("/license/permission").contentType(MediaType.APPLICATION_JSON).content(json)) - .andExpect(status().isOk()); - } - - /** - * TEST SCENARIO : Testing fetch end point. - */ - @Test - @WithUserDetails("reg-processor") - public void licenseKeyFetchTest() throws Exception { - List listPermissions = new ArrayList<>(); - listPermissions.add("PERMISSION1"); - listPermissions.add("PERMISSION2"); - given(service.fetchLicenseKeyPermissions(Mockito.any(), Mockito.any())).willReturn(listPermissions); - mockMvc.perform(get("/license/permission?licenseKey=fqELcNGoaEeuuJAs&tspId=TSPID") - .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) - .andExpect(jsonPath("$.response.permissions[0]", is("PERMISSION1"))); - } -} diff --git a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/lkeymanager/test/exception/LicenseKeyManagerExceptionTest.java b/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/lkeymanager/test/exception/LicenseKeyManagerExceptionTest.java deleted file mode 100644 index e523ba87619..00000000000 --- a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/lkeymanager/test/exception/LicenseKeyManagerExceptionTest.java +++ /dev/null @@ -1,393 +0,0 @@ -package io.mosip.kernel.lkeymanager.test.exception; - -import static org.hamcrest.CoreMatchers.isA; -import static org.mockito.Mockito.when; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import java.time.LocalDateTime; -import java.time.Month; -import java.util.ArrayList; -import java.util.List; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.http.MediaType; -import org.springframework.security.test.context.support.WithUserDetails; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.kernel.core.http.RequestWrapper; -import io.mosip.kernel.core.keymanager.spi.KeyStore; -import io.mosip.kernel.keymanagerservice.test.KeymanagerTestBootApplication; -import io.mosip.kernel.lkeymanager.dto.LicenseKeyGenerationDto; -import io.mosip.kernel.lkeymanager.dto.LicenseKeyMappingDto; -import io.mosip.kernel.lkeymanager.entity.LicenseKeyList; -import io.mosip.kernel.lkeymanager.entity.LicenseKeyTspMap; -import io.mosip.kernel.lkeymanager.repository.LicenseKeyListRepository; -import io.mosip.kernel.lkeymanager.repository.LicenseKeyPermissionRepository; -import io.mosip.kernel.lkeymanager.repository.LicenseKeyTspMapRepository; - -@SpringBootTest(classes = KeymanagerTestBootApplication.class) -@RunWith(SpringRunner.class) -@AutoConfigureMockMvc -public class LicenseKeyManagerExceptionTest { - - @MockBean - private KeyStore keyStore; - - @Autowired - private MockMvc mockMvc; - - @Autowired - private ObjectMapper objectMapper; - - @MockBean - private LicenseKeyListRepository licenseKeyListRepository; - - @MockBean - private LicenseKeyPermissionRepository licenseKeyPermissionRepository; - - @MockBean - private LicenseKeyTspMapRepository licenseKeyTspMapRepository; - - private LicenseKeyList licensekeyList; - - private LicenseKeyTspMap licenseKeyTspMap; - - @Before - public void setUp() { - licenseKeyListEntitySetUp(); - licenseKeyTspMapSetUp(); - } - - private void licenseKeyTspMapSetUp() { - licenseKeyTspMap = new LicenseKeyTspMap(); - licenseKeyTspMap.setActive(true); - licenseKeyTspMap.setCreatedBy("testadmin@mosip.io"); - licenseKeyTspMap.setCreatedDateTimes(LocalDateTime.now()); - licenseKeyTspMap.setDeleted(false); - licenseKeyTspMap.setLKey("tEsTlIcEnSe"); - licenseKeyTspMap.setTspId("TSP_ID_TEST"); - - } - - private void licenseKeyListEntitySetUp() { - licensekeyList = new LicenseKeyList(); - licensekeyList.setActive(true); - licensekeyList.setCreatedAt(LocalDateTime.now()); - licensekeyList.setCreatedBy("testadmin@mosip.io"); - licensekeyList.setDeleted(false); - licensekeyList.setExpiryDateTimes(LocalDateTime.of(2019, Month.FEBRUARY, 2, 6, 23)); - licensekeyList.setLicenseKey("tEsTlIcEnSe"); - - } - - /** - * - * TEST SCENARIO : When TSPID and LICENSEKEY entered for mapping permissions are - * not correct. - * - */ - @Test - @WithUserDetails("reg-processor") - public void testLKMMappingServiceExceptionWhenInvalidValues() throws Exception { - List permissions = new ArrayList<>(); - permissions.add("Biometric Authentication - IIR Data Match"); - permissions.add("Biometric Authentication - FID Data Match"); - LicenseKeyMappingDto licenseKeyMappingDto = new LicenseKeyMappingDto(); - licenseKeyMappingDto.setLicenseKey("tEsTlIcEnSe"); - licenseKeyMappingDto.setTspId("TSP_ID_TEST"); - licenseKeyMappingDto.setPermissions(permissions); - RequestWrapper reqWrapperDTO = new RequestWrapper<>(); - reqWrapperDTO.setId("ID"); - reqWrapperDTO.setMetadata(null); - reqWrapperDTO.setRequest(licenseKeyMappingDto); - reqWrapperDTO.setRequesttime(LocalDateTime.now()); - reqWrapperDTO.setVersion("v1.0"); - String json = objectMapper.writeValueAsString(reqWrapperDTO); - when(licenseKeyTspMapRepository.findByLKeyAndTspId(Mockito.anyString(), Mockito.anyString())).thenReturn(null); - mockMvc.perform(post("/license/permission").contentType(MediaType.APPLICATION_JSON).content(json)) - .andExpect(status().isOk()).andExpect(jsonPath("$.errors[0].errorCode", isA(String.class))); - } - - /** - * - * TEST SCENARIO : When License Key is expired. - * - */ - @Test - @WithUserDetails("reg-processor") - public void testLKMFetchServiceExceptionWhenExpiredLicense() throws Exception { - when(licenseKeyTspMapRepository.findByLKeyAndTspId(Mockito.anyString(), Mockito.anyString())) - .thenReturn(licenseKeyTspMap); - when(licenseKeyListRepository.findByLicenseKey(Mockito.anyString())).thenReturn(licensekeyList); - mockMvc.perform(get("/license/permission?licenseKey=tEsTlIcEnSe&tspId=TSP_ID_TEST") - .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) - .andExpect(jsonPath("$.errors[0].errorCode", isA(String.class))); - } - - /** - * - * TEST SCENARIO : When the license key and TSPID entered for the permissions to - * be fetched are not valid, i.e. the TSPID doesnt has the corresponding license - * key. - * - */ - @Test - @WithUserDetails("reg-processor") - public void testLKMFetchServiceExceptionWhenInvalidValues() throws Exception { - when(licenseKeyTspMapRepository.findByLKeyAndTspId(Mockito.anyString(), Mockito.anyString())).thenReturn(null); - when(licenseKeyListRepository.findByLicenseKey(Mockito.anyString())).thenReturn(licensekeyList); - mockMvc.perform(get("/license/permission?licenseKey=tEsTlIcEnSe&tspId=TSP_ID_TEST") - .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) - .andExpect(jsonPath("$.errors[0].errorCode", isA(String.class))); - } - - /** - * - * TEST SCENARIO : When inputs has empty values. - * - */ - @Test - @WithUserDetails("reg-processor") - public void testLKMFetchServiceExceptionWhenEmptyLKey() throws Exception { - mockMvc.perform( - get("/license/permission?licenseKey=&tspId=TSP_ID_TEST").contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()).andExpect(jsonPath("$.errors[0].errorCode", isA(String.class))); - } - - /** - * - * TEST SCENARIO : When inputs has null values. - * - */ - @Test - @WithUserDetails("reg-processor") - public void testLKMFetchServiceExceptionWhenNullTSP() throws Exception { - mockMvc.perform( - get("/license/permission?licenseKey=hjdesufhdufyisehui").contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()); - } - - /** - * - * TEST SCENARIO : When inputs has empty values. - * - */ - @Test - @WithUserDetails("reg-processor") - public void testLKMFetchServiceExceptionWhenEmptyTSP() throws Exception { - mockMvc.perform( - get("/license/permission?licenseKey=jsudhauidhiw&tspId=").contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()).andExpect(jsonPath("$.errors[0].errorCode", isA(String.class))); - } - - /** - * - * TEST SCENARIO : When inputs has null values. - * - */ - @Test - @WithUserDetails("reg-processor") - public void testLKMFetchServiceExceptionWhenNullLicenseKey() throws Exception { - mockMvc.perform(get("/license/permission?tspId=98376").contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()); - } - - /** - * - * TEST SCENARIO : When Expiry Time entered is a date before current DateTime. - * - */ - @Test - @WithUserDetails("reg-processor") - public void testLKMGenerationServiceExceptionWhenExpiredDateEntered() throws Exception { - LicenseKeyGenerationDto licenseKeyGenerationDto = new LicenseKeyGenerationDto(); - licenseKeyGenerationDto.setLicenseExpiryTime(LocalDateTime.of(2010, Month.FEBRUARY, 6, 6, 23, 0)); - licenseKeyGenerationDto.setTspId("TSP_ID_TEST"); - RequestWrapper reqWrapperDTO = new RequestWrapper<>(); - reqWrapperDTO.setId("ID"); - reqWrapperDTO.setMetadata(null); - reqWrapperDTO.setRequest(licenseKeyGenerationDto); - reqWrapperDTO.setRequesttime(LocalDateTime.now()); - reqWrapperDTO.setVersion("v1.0"); - String json = objectMapper.writeValueAsString(reqWrapperDTO); - mockMvc.perform(post("/license/generate").contentType(MediaType.APPLICATION_JSON).content(json)) - .andExpect(status().isOk()).andExpect(jsonPath("$.errors[0].errorCode", isA(String.class))); - } - - /** - * - * TEST SCENARIO : When permissions are mapped and TSP entered is null. - * - */ - @Test - @WithUserDetails("reg-processor") - public void testLKMMappingServiceExceptionWhenTSPIDNull() throws Exception { - List permissions = new ArrayList<>(); - permissions.add("Biometric Authentication - IIR Data Match"); - permissions.add("Invalid Permission Test"); - LicenseKeyMappingDto licenseKeyMappingDto = new LicenseKeyMappingDto(); - licenseKeyMappingDto.setLicenseKey("tEsTlIcEnSe"); - licenseKeyMappingDto.setTspId(null); - licenseKeyMappingDto.setPermissions(permissions); - RequestWrapper reqWrapperDTO = new RequestWrapper<>(); - reqWrapperDTO.setId("ID"); - reqWrapperDTO.setMetadata(null); - reqWrapperDTO.setRequest(licenseKeyMappingDto); - reqWrapperDTO.setRequesttime(LocalDateTime.now()); - reqWrapperDTO.setVersion("v1.0"); - String json = objectMapper.writeValueAsString(reqWrapperDTO); - when(licenseKeyTspMapRepository.findByLKeyAndTspId(Mockito.anyString(), Mockito.anyString())).thenReturn(null); - mockMvc.perform(post("/license/permission").contentType(MediaType.APPLICATION_JSON).content(json)) - .andExpect(status().isOk()).andExpect(jsonPath("$.errors[0].errorCode", isA(String.class))); - } - - /** - * - * TEST SCENARIO : When permissions are mapped and TSP entered is empty. - * - */ - @Test - @WithUserDetails("reg-processor") - public void testLKMMappingServiceExceptionWhenTSPIDEmpty() throws Exception { - List permissions = new ArrayList<>(); - permissions.add("Biometric Authentication - IIR Data Match"); - permissions.add("Invalid Permission Test"); - LicenseKeyMappingDto licenseKeyMappingDto = new LicenseKeyMappingDto(); - licenseKeyMappingDto.setLicenseKey("tEsTlIcEnSe"); - licenseKeyMappingDto.setTspId(" "); - licenseKeyMappingDto.setPermissions(permissions); - RequestWrapper reqWrapperDTO = new RequestWrapper<>(); - reqWrapperDTO.setId("ID"); - reqWrapperDTO.setMetadata(null); - reqWrapperDTO.setRequest(licenseKeyMappingDto); - reqWrapperDTO.setRequesttime(LocalDateTime.now()); - reqWrapperDTO.setVersion("v1.0"); - String json = objectMapper.writeValueAsString(reqWrapperDTO); - when(licenseKeyTspMapRepository.findByLKeyAndTspId(Mockito.anyString(), Mockito.anyString())).thenReturn(null); - mockMvc.perform(post("/license/permission").contentType(MediaType.APPLICATION_JSON).content(json)) - .andExpect(status().isOk()).andExpect(jsonPath("$.errors[0].errorCode", isA(String.class))); - } - - /** - * - * TEST SCENARIO : When permissions are mapped and license key entered is null. - * - */ - @Test - @WithUserDetails("reg-processor") - public void testLKMMappingServiceExceptionWhenLicenseKeyNull() throws Exception { - List permissions = new ArrayList<>(); - permissions.add("Biometric Authentication - IIR Data Match"); - permissions.add("Invalid Permission Test"); - LicenseKeyMappingDto licenseKeyMappingDto = new LicenseKeyMappingDto(); - licenseKeyMappingDto.setLicenseKey(null); - licenseKeyMappingDto.setTspId("TSP_ID_TEST"); - licenseKeyMappingDto.setPermissions(permissions); - RequestWrapper reqWrapperDTO = new RequestWrapper<>(); - reqWrapperDTO.setId("ID"); - reqWrapperDTO.setMetadata(null); - reqWrapperDTO.setRequest(licenseKeyMappingDto); - reqWrapperDTO.setRequesttime(LocalDateTime.now()); - reqWrapperDTO.setVersion("v1.0"); - String json = objectMapper.writeValueAsString(reqWrapperDTO); - when(licenseKeyTspMapRepository.findByLKeyAndTspId(Mockito.anyString(), Mockito.anyString())).thenReturn(null); - mockMvc.perform(post("/license/permission").contentType(MediaType.APPLICATION_JSON).content(json)) - .andExpect(status().isOk()).andExpect(jsonPath("$.errors[0].errorCode", isA(String.class))); - } - - /** - * - * TEST SCENARIO : When permissions are mapped and license key entered is empty. - * - */ - @Test - @WithUserDetails("reg-processor") - public void testLKMMappingServiceExceptionWhenLicenseKeyEmpty() throws Exception { - List permissions = new ArrayList<>(); - permissions.add("Biometric Authentication - IIR Data Match"); - permissions.add("Invalid Permission Test"); - LicenseKeyMappingDto licenseKeyMappingDto = new LicenseKeyMappingDto(); - licenseKeyMappingDto.setLicenseKey(" "); - licenseKeyMappingDto.setTspId("TSP_ID_TEST"); - licenseKeyMappingDto.setPermissions(permissions); - RequestWrapper reqWrapperDTO = new RequestWrapper<>(); - reqWrapperDTO.setId("ID"); - reqWrapperDTO.setMetadata(null); - reqWrapperDTO.setRequest(licenseKeyMappingDto); - reqWrapperDTO.setRequesttime(LocalDateTime.now()); - reqWrapperDTO.setVersion("v1.0"); - String json = objectMapper.writeValueAsString(reqWrapperDTO); - when(licenseKeyTspMapRepository.findByLKeyAndTspId(Mockito.anyString(), Mockito.anyString())).thenReturn(null); - mockMvc.perform(post("/license/permission").contentType(MediaType.APPLICATION_JSON).content(json)) - .andExpect(status().isOk()).andExpect(jsonPath("$.errors[0].errorCode", isA(String.class))); - } - - /** - * - * TEST SCENARIO : When permission entered is invalid[i.e. permission not - * present in master list]. - * - */ - @Test - @WithUserDetails("reg-processor") - public void testLKMMappingServiceExceptionWhenInvalidPermissions() throws Exception { - List permissions = new ArrayList<>(); - permissions.add("Biometric Authentication - IIR Data Match"); - permissions.add("Invalid Permission Test"); - LicenseKeyMappingDto licenseKeyMappingDto = new LicenseKeyMappingDto(); - licenseKeyMappingDto.setLicenseKey("tEsTlIcEnSe"); - licenseKeyMappingDto.setTspId("TSP_ID_TEST"); - licenseKeyMappingDto.setPermissions(permissions); - RequestWrapper reqWrapperDTO = new RequestWrapper<>(); - reqWrapperDTO.setId("ID"); - reqWrapperDTO.setMetadata(null); - reqWrapperDTO.setRequest(licenseKeyMappingDto); - reqWrapperDTO.setRequesttime(LocalDateTime.now()); - reqWrapperDTO.setVersion("v1.0"); - String json = objectMapper.writeValueAsString(reqWrapperDTO); - when(licenseKeyTspMapRepository.findByLKeyAndTspId(Mockito.anyString(), Mockito.anyString())).thenReturn(null); - mockMvc.perform(post("/license/permission").contentType(MediaType.APPLICATION_JSON).content(json)) - .andExpect(status().isOk()).andExpect(jsonPath("$.errors[0].errorCode", isA(String.class))); - } - - /** - * - * TEST SCENARIO : When permission entered is empty. - * - */ - @Test - @WithUserDetails("reg-processor") - public void testLKMMappingServiceExceptionWhenEmptyPermissions() throws Exception { - List permissions = new ArrayList<>(); - permissions.add("Biometric Authentication - IIR Data Match"); - permissions.add(" "); - LicenseKeyMappingDto licenseKeyMappingDto = new LicenseKeyMappingDto(); - licenseKeyMappingDto.setLicenseKey("tEsTlIcEnSe"); - licenseKeyMappingDto.setTspId("TSP_ID_TEST"); - licenseKeyMappingDto.setPermissions(permissions); - RequestWrapper reqWrapperDTO = new RequestWrapper<>(); - reqWrapperDTO.setId("ID"); - reqWrapperDTO.setMetadata(null); - reqWrapperDTO.setRequest(licenseKeyMappingDto); - reqWrapperDTO.setRequesttime(LocalDateTime.now()); - reqWrapperDTO.setVersion("v1.0"); - String json = objectMapper.writeValueAsString(reqWrapperDTO); - when(licenseKeyTspMapRepository.findByLKeyAndTspId(Mockito.anyString(), Mockito.anyString())).thenReturn(null); - mockMvc.perform(post("/license/permission").contentType(MediaType.APPLICATION_JSON).content(json)) - .andExpect(status().isOk()).andExpect(jsonPath("$.errors[0].errorCode", isA(String.class))); - } - -} diff --git a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/lkeymanager/test/service/LicenseKeyManagerServiceTest.java b/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/lkeymanager/test/service/LicenseKeyManagerServiceTest.java deleted file mode 100644 index 3dcda5b97c2..00000000000 --- a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/lkeymanager/test/service/LicenseKeyManagerServiceTest.java +++ /dev/null @@ -1,214 +0,0 @@ -package io.mosip.kernel.lkeymanager.test.service; - -import static org.hamcrest.CoreMatchers.isA; -import static org.mockito.Mockito.when; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import java.time.LocalDateTime; -import java.time.Month; -import java.util.ArrayList; -import java.util.List; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.http.MediaType; -import org.springframework.security.test.context.support.WithUserDetails; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.kernel.core.http.RequestWrapper; -import io.mosip.kernel.core.keymanager.spi.KeyStore; -import io.mosip.kernel.keymanagerservice.test.KeymanagerTestBootApplication; -import io.mosip.kernel.lkeymanager.dto.LicenseKeyGenerationDto; -import io.mosip.kernel.lkeymanager.dto.LicenseKeyMappingDto; -import io.mosip.kernel.lkeymanager.entity.LicenseKeyList; -import io.mosip.kernel.lkeymanager.entity.LicenseKeyPermission; -import io.mosip.kernel.lkeymanager.entity.LicenseKeyTspMap; -import io.mosip.kernel.lkeymanager.repository.LicenseKeyListRepository; -import io.mosip.kernel.lkeymanager.repository.LicenseKeyPermissionRepository; -import io.mosip.kernel.lkeymanager.repository.LicenseKeyTspMapRepository; - -@SpringBootTest(classes = KeymanagerTestBootApplication.class) -@RunWith(SpringRunner.class) -@AutoConfigureMockMvc -public class LicenseKeyManagerServiceTest { - - @MockBean - private KeyStore keyStore; - - @Autowired - private MockMvc mockMvc; - - @Autowired - private ObjectMapper objectMapper; - - @MockBean - private LicenseKeyListRepository licenseKeyListRepository; - - @MockBean - private LicenseKeyPermissionRepository licenseKeyPermissionRepository; - - @MockBean - private LicenseKeyTspMapRepository licenseKeyTspMapRepository; - - private LicenseKeyList licensekeyList; - - private LicenseKeyTspMap licenseKeyTspMap; - - private LicenseKeyPermission licenseKeyPermission; - - @Before - public void setUp() { - licenseKeyListEntitySetUp(); - licenseKeyTspMapSetUp(); - licenseKeyPermissionSetUp(); - } - - private void licenseKeyListEntitySetUp() { - licensekeyList = new LicenseKeyList(); - licensekeyList.setActive(true); - licensekeyList.setCreatedAt(LocalDateTime.now()); - licensekeyList.setCreatedBy("testadmin@mosip.io"); - licensekeyList.setDeleted(false); - licensekeyList.setExpiryDateTimes(LocalDateTime.of(2600, Month.FEBRUARY, 6, 6, 23)); - licensekeyList.setLicenseKey("tEsTlIcEnSe"); - - } - - private void licenseKeyTspMapSetUp() { - licenseKeyTspMap = new LicenseKeyTspMap(); - licenseKeyTspMap.setActive(true); - licenseKeyTspMap.setCreatedBy("testadmin@mosip.io"); - licenseKeyTspMap.setCreatedDateTimes(LocalDateTime.now()); - licenseKeyTspMap.setDeleted(false); - licenseKeyTspMap.setLKey("tEsTlIcEnSe"); - licenseKeyTspMap.setTspId("TSP_ID_TEST"); - - } - - private void licenseKeyPermissionSetUp() { - licenseKeyPermission = new LicenseKeyPermission(); - licenseKeyPermission.setActive(true); - licenseKeyPermission.setCreatedBy("testadmin@mosip.io"); - licenseKeyPermission.setCreatedDateTimes(LocalDateTime.now()); - licenseKeyPermission.setDeleted(false); - licenseKeyPermission.setLKey("tEsTlIcEnSe"); - licenseKeyPermission - .setPermission("Biometric Authentication - IIR Data Match,Biometric Authentication - FID Data Match"); - licenseKeyPermission.setUpdatedBy("testadmin@mosip.io"); - licenseKeyPermission.setUpdatedDateTimes(LocalDateTime.now()); - } - - /** - * TEST SCENARIO : Testing License Key Generation service implementation. - * - * @throws Exception.class - */ - @Test - @WithUserDetails("reg-processor") - public void testLKMGenerationService() throws Exception { - LicenseKeyGenerationDto licenseKeyGenerationDto = new LicenseKeyGenerationDto(); - licenseKeyGenerationDto.setLicenseExpiryTime(LocalDateTime.of(9999, Month.FEBRUARY, 6, 6, 23, 0)); - licenseKeyGenerationDto.setTspId("TSP_ID_TEST"); - RequestWrapper reqWrapperDTO = new RequestWrapper<>(); - reqWrapperDTO.setId("ID"); - reqWrapperDTO.setMetadata(null); - reqWrapperDTO.setRequest(licenseKeyGenerationDto); - reqWrapperDTO.setRequesttime(LocalDateTime.now()); - reqWrapperDTO.setVersion("v1.0"); - String json = objectMapper.writeValueAsString(reqWrapperDTO); - when(licenseKeyListRepository.save(Mockito.any())).thenReturn(licensekeyList); - when(licenseKeyTspMapRepository.save(Mockito.any())).thenReturn(licenseKeyTspMap); - mockMvc.perform(post("/license/generate").contentType(MediaType.APPLICATION_JSON).content(json)) - .andExpect(status().isOk()); - } - - /** - * TEST SCENARIO : Testing License Key Mapping service implementation when new - * permissions are added to the already existing permissions. - * - * @throws Exception.class - */ - @Test - @WithUserDetails("reg-processor") - public void testLKMMappingServiceUpdatePermission() throws Exception { - List permissions = new ArrayList<>(); - permissions.add("Biometric Authentication - IIR Data Match"); - permissions.add("Biometric Authentication - FID Data Match"); - LicenseKeyMappingDto licenseKeyMappingDto = new LicenseKeyMappingDto(); - licenseKeyMappingDto.setLicenseKey("tEsTlIcEnSe"); - licenseKeyMappingDto.setTspId("TSP_ID_TEST"); - licenseKeyMappingDto.setPermissions(permissions); - RequestWrapper reqWrapperDTO = new RequestWrapper<>(); - reqWrapperDTO.setId("ID"); - reqWrapperDTO.setMetadata(null); - reqWrapperDTO.setRequest(licenseKeyMappingDto); - reqWrapperDTO.setRequesttime(LocalDateTime.now()); - reqWrapperDTO.setVersion("v1.0"); - String json = objectMapper.writeValueAsString(reqWrapperDTO); - when(licenseKeyTspMapRepository.findByLKeyAndTspId(Mockito.anyString(), Mockito.anyString())) - .thenReturn(licenseKeyTspMap); - when(licenseKeyPermissionRepository.findByLKey(Mockito.any())).thenReturn(licenseKeyPermission); - mockMvc.perform(post("/license/permission").contentType(MediaType.APPLICATION_JSON).content(json)) - .andExpect(status().isOk()); - - } - - /** - * TEST SCENARIO : Testing License Key Mapping service implementation when - * permissions are added. - * - * @throws Exception.class - */ - @Test - @WithUserDetails("reg-processor") - public void testLKMMappingServiceCreatePermission() throws Exception { - List permissions = new ArrayList<>(); - permissions.add("Biometric Authentication - IIR Data Match"); - permissions.add("Biometric Authentication - FID Data Match"); - LicenseKeyMappingDto licenseKeyMappingDto = new LicenseKeyMappingDto(); - licenseKeyMappingDto.setLicenseKey("tEsTlIcEnSe"); - licenseKeyMappingDto.setTspId("TSP_ID_TEST"); - licenseKeyMappingDto.setPermissions(permissions); - RequestWrapper reqWrapperDTO = new RequestWrapper<>(); - reqWrapperDTO.setId("ID"); - reqWrapperDTO.setMetadata(null); - reqWrapperDTO.setRequest(licenseKeyMappingDto); - reqWrapperDTO.setRequesttime(LocalDateTime.now()); - reqWrapperDTO.setVersion("v1.0"); - String json = objectMapper.writeValueAsString(reqWrapperDTO); - when(licenseKeyTspMapRepository.findByLKeyAndTspId(Mockito.anyString(), Mockito.anyString())) - .thenReturn(licenseKeyTspMap); - when(licenseKeyPermissionRepository.findByLKey(Mockito.any())).thenReturn(null); - mockMvc.perform(post("/license/permission").contentType(MediaType.APPLICATION_JSON).content(json)) - .andExpect(status().isOk()); - } - - /** - * TEST SCENARIO : Testing fetching permissions service implementation. - * - * @throws Exception.class - */ - @Test - @WithUserDetails("reg-processor") - public void testLKMFetchService() throws Exception { - when(licenseKeyTspMapRepository.findByLKeyAndTspId(Mockito.anyString(), Mockito.anyString())) - .thenReturn(licenseKeyTspMap); - when(licenseKeyListRepository.findByLicenseKey(Mockito.anyString())).thenReturn(licensekeyList); - when(licenseKeyPermissionRepository.findByLKey(Mockito.any())).thenReturn(licenseKeyPermission); - mockMvc.perform(get("/license/permission?licenseKey=tEsTlIcEnSe&tspId=TSP_ID_TEST") - .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) - .andExpect(jsonPath("$.response.permissions[0]", isA(String.class))); - } -} diff --git a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/signature/test/integration/CryptoSignatureIntegrationTest.java b/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/signature/test/integration/CryptoSignatureIntegrationTest.java deleted file mode 100644 index d6240a19eb8..00000000000 --- a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/signature/test/integration/CryptoSignatureIntegrationTest.java +++ /dev/null @@ -1,156 +0,0 @@ -package io.mosip.kernel.signature.test.integration; - -import static org.mockito.Mockito.when; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import java.security.KeyPair; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.time.ZoneOffset; - -import javax.crypto.SecretKey; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.http.MediaType; -import org.springframework.security.test.context.support.WithUserDetails; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.web.client.RestTemplate; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.kernel.core.crypto.spi.CryptoCoreSpec; -import io.mosip.kernel.core.http.RequestWrapper; -import io.mosip.kernel.core.keymanager.spi.KeyStore; -import io.mosip.kernel.core.signatureutil.model.SignatureResponse; -import io.mosip.kernel.core.util.CryptoUtil; -import io.mosip.kernel.keygenerator.bouncycastle.KeyGenerator; -import io.mosip.kernel.keymanagerservice.dto.PublicKeyResponse; -import io.mosip.kernel.signature.dto.SignatureResponseDto; -import io.mosip.kernel.keymanagerservice.service.KeymanagerService; -import io.mosip.kernel.keymanagerservice.test.KeymanagerTestBootApplication; -import io.mosip.kernel.signature.dto.TimestampRequestDto; -import io.mosip.kernel.signature.service.SignatureService; - -@SpringBootTest(classes = KeymanagerTestBootApplication.class) -@RunWith(SpringRunner.class) -@AutoConfigureMockMvc -public class CryptoSignatureIntegrationTest { - - @Autowired - private MockMvc mockMvc; - - private RequestWrapper requestWrapper; - - @Autowired - private CryptoCoreSpec cryptoCore; - - - @MockBean - private KeyStore keyStore; - - @Autowired - private KeyGenerator generator; - - - private KeyPair keyPair; - - @Autowired - private ObjectMapper objectMapper; - - /** The key manager. */ - @MockBean - private KeymanagerService keyManagerService; - - @MockBean - private SignatureService signatureService; - - @MockBean - private RestTemplate restTemplate; - - private static final String SIGNRESPONSEREQUEST = "{ \"id\": \"string\", \"metadata\": {}, \"request\": { \"data\": \"admin\" }, \"requesttime\": \"2018-12-10T06:12:52.994Z\", \"version\": \"string\" }"; - private static final String VALIDATEWITHPUBLICKEY = "{ \"id\": \"string\", \"metadata\": {}, \"request\": { \"publickey\": \"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnoocJbIeMuAzqSzuJX9CvXmFFka3Fz3C-u9vz6c8RsJSKBCe_SAOi31IvL992kuy1qO4XTS-cUuirx-djuF0E7r5TbQFKlNa-FoPJu8QRIGw2rWVQsc2c0Aqd5cfhr9fgTsM3V3URl1jXY645v9EPE0Ih5E26ld6JQQQ90mpvoa6XlJEf5SUAOuzvr5ws5VoZgEQ6wjO05dZSaEL9vrA5npsNSwLb55FqZb7w9qLZfYbPOBVxUZ-HTddBLP6KvlIHWzsVapjvhUHPgSO0AZDYmx3kkKb7jFuWelPibNyKy619AAnlQX3VR39CKi-6sPLRABs4v-npsFLNz9Wd_VJHwIDAQAB\", \"data\": \"admin\", \"signature\": \"ZeNsCOsdgf0UgpXDMry82hrHS6b1ZKvS-tZ_3HBGQHleIu1fZA6LNTtx7XZPFeC8dxsyuYO_iN3mVExM4J2tPlebzsRtuxHigi9o7DI_2xGqFudzlgoH55CP_BBNUDmGm6m-lTMkRx6X61dKfKDNo2NipZdM-a_cHf6Z0aVAU4LdJhV4xWOOm8Pb8sYIc2Nf6kUJRiidEGrxonUCfXX1XlnjMAo75wu99pN8G0mc7JhOehUqbwuXwKo4sQ694ae4F_AYl70sepX24v-0k0ga9esXR4i9rKaoHbzhQFtt2hangQkxHajq9ZTrXWMhd4msTzjHCKdEPXQFsTbKrgKtDQ\" }, \"requesttime\": \"2018-12-10T06:12:52.994Z\", \"version\": \"string\" }"; - private static final String VALIDATEWITHTIMESTAMP = "{ \"id\": \"string\", \"metadata\": {}, \"request\": { \"signature\": \"DrgkF2vm4WvBe04UNe-RePRcrg77uQpsH3GENRcglBsid-K0UDReeeZVKwimOdwV7Ht1j-_D1BFf2sCrM8ni7ztE5Xc_3TEaniOAnOgZDRSI0GG-uSqjH51AwTSl1PYdStfXtOn6HEfEU68JG7TdAliDI5C7thJ1YNmPnHusIsZzX6sW_VfvSpLeA_RzCqnUDH_VaEzZt_5zRYiQv9van4wt0P7HTfIBlQ5zaeO3wXOc3Pogct3ssKwqdaMmZdc7QTDOFqDZZVceMTIXKyiH-ZVs_u3QXRysiLVdXoz7d7yXHdWxQtzsfMjY7alMJNgbmu4X26LYNRemn65Mmn6ixA\", \"data\": \"test\", \"timestamp\": \"2019-05-20T07:28:04.269Z\" }, \"requesttime\": \"2018-12-10T06:12:52.994Z\", \"version\": \"string\" }"; - private static final String ID = "mosip.signature.service"; - private static final String VERSION = "V1.0"; - - StringBuilder builder; - SignatureResponse signResponse; - SignatureResponseDto signatureResponseDTO; - - @Before - public void setup() { - keyPair = generator.getAsymmetricKey(); - signResponse = new SignatureResponse(); - signatureResponseDTO= new SignatureResponseDto(); - signatureResponseDTO.setData("asdasdsadf4e..soidopasid"); - signResponse.setData("asdasdsadf4e..iosdipoasopd"); - signResponse.setTimestamp(LocalDateTime.now(ZoneOffset.UTC)); - requestWrapper = new RequestWrapper<>(); - requestWrapper.setId(ID); - requestWrapper.setVersion(VERSION); - requestWrapper.setRequesttime(LocalDateTime.now(ZoneId.of("UTC"))); - } - - @Test - @WithUserDetails("reg-processor") - public void signResponseSuccess() throws Exception { - when(signatureService.sign(Mockito.any())).thenReturn(signResponse); - mockMvc.perform(post("/sign").contentType(MediaType.APPLICATION_JSON).content(SIGNRESPONSEREQUEST)) - .andExpect(status().isOk()); - } - - - @Test - @WithUserDetails("reg-processor") - public void signResponseTimeStampValidationInvalid() throws Exception { - PublicKeyResponse publicKeyResponseDto = new PublicKeyResponse<>("alias", - CryptoUtil.encodeBase64(keyPair.getPublic().getEncoded()), LocalDateTime.now(), - LocalDateTime.now().plusDays(100)); - when(keyManagerService.getSignPublicKey(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(publicKeyResponseDto); - String data="test"; - String signedData=cryptoCore.sign(data.getBytes(), keyPair.getPrivate()); - TimestampRequestDto dto= new TimestampRequestDto(signedData,"wrongdata",LocalDateTime.now(ZoneId.of("UTC"))); - requestWrapper.setRequest(dto); - mockMvc.perform(post("/validate").contentType(MediaType.APPLICATION_JSON).content(objectMapper.writeValueAsString(requestWrapper))) - .andExpect(status().isOk()); - } - - @Test - @WithUserDetails("reg-processor") - public void signResponseTimeStampValidationValid() throws Exception { - PublicKeyResponse publicKeyResponseDto = new PublicKeyResponse<>("alias", - CryptoUtil.encodeBase64(keyPair.getPublic().getEncoded()), LocalDateTime.now(), - LocalDateTime.now().plusDays(100)); - when(keyManagerService.getSignPublicKey(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(publicKeyResponseDto); - String data="test"; - String signedData=cryptoCore.sign(data.getBytes(), keyPair.getPrivate()); - TimestampRequestDto dto= new TimestampRequestDto(signedData,data,LocalDateTime.now(ZoneId.of("UTC"))); - requestWrapper.setRequest(dto); - mockMvc.perform(post("/validate").contentType(MediaType.APPLICATION_JSON).content(objectMapper.writeValueAsString(requestWrapper))) - .andExpect(status().isOk()); - } - - @Test - @WithUserDetails("reg-processor") - public void signResponseTimeStampValidationException() throws Exception { - when(keyManagerService.getSignPublicKey(Mockito.any(), Mockito.any(), Mockito.any())).thenThrow(RuntimeException.class); - String data="test"; - String signedData=cryptoCore.sign(data.getBytes(), keyPair.getPrivate()); - TimestampRequestDto dto= new TimestampRequestDto(signedData,data,LocalDateTime.now(ZoneId.of("UTC"))); - requestWrapper.setRequest(dto); - mockMvc.perform(post("/validate").contentType(MediaType.APPLICATION_JSON).content(objectMapper.writeValueAsString(requestWrapper))) - .andExpect(status().isOk()); - } - -} diff --git a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/tokenidgenerator/test/integration/TokenIdGeneratorIntegrationTest.java b/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/tokenidgenerator/test/integration/TokenIdGeneratorIntegrationTest.java deleted file mode 100644 index 44bba753de0..00000000000 --- a/kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/tokenidgenerator/test/integration/TokenIdGeneratorIntegrationTest.java +++ /dev/null @@ -1,46 +0,0 @@ -package io.mosip.kernel.tokenidgenerator.test.integration; - -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.http.MediaType; -import org.springframework.security.test.context.support.WithUserDetails; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; - -import io.mosip.kernel.core.keymanager.spi.KeyStore; -import io.mosip.kernel.keymanagerservice.test.KeymanagerTestBootApplication; -import io.mosip.kernel.tokenidgenerator.dto.TokenIDResponseDto; - -@SpringBootTest(classes = KeymanagerTestBootApplication.class) -@RunWith(SpringRunner.class) -@AutoConfigureMockMvc -public class TokenIdGeneratorIntegrationTest { - - @MockBean - private KeyStore keyStore; - - @Autowired - private MockMvc mockMvc; - - @Test - @WithUserDetails("id-auth") - public void generateTokenIDTest() throws Exception { - TokenIDResponseDto response = new TokenIDResponseDto(); - response.setTokenID("123456"); - mockMvc.perform(get("/1234/1234").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()); - - } - - @Test - @WithUserDetails("id-auth") - public void generateTokenIdExceptionTest() throws Exception { - mockMvc.perform(get("/ / ").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()); - } -} diff --git a/kernel/kernel-keymanager-service/src/test/resources/application.properties b/kernel/kernel-keymanager-service/src/test/resources/application.properties deleted file mode 100644 index 91473e7c190..00000000000 --- a/kernel/kernel-keymanager-service/src/test/resources/application.properties +++ /dev/null @@ -1,116 +0,0 @@ -mosip.kernel.keymanager.hsm.config-path=/var/lib/softhsm/softhsm.conf -#mosip.kernel.keymanager.softhsm.config-path=D\:\\SoftHSM2\\etc\\softhsm2-demo.conf -#Type of keystore -mosip.kernel.keymanager.hsm.keystore-type=PKCS11 -#Passkey of keystore -mosip.kernel.keymanager.hsm.keystore-pass=1234 - -mosip.kernel.keymanager.certificate.default.common-name=www.mosip.io -mosip.kernel.keymanager.certificate.default.organizational-unit=MOSIP-TECH-CENTER -mosip.kernel.keymanager.certificate.default.organization=IITB -mosip.kernel.keymanager.certificate.default.location=BANGALORE -mosip.kernel.keymanager.certificate.default.state=KA -mosip.kernel.keymanager.certificate.default.country=IN - -## To disable the logging -logging.level.org.springframework=OFF -logging.level.root=OFF -spring.main.banner-mode=off - -mosip.kernel.keygenerator.asymmetric-key-length=2048 -mosip.kernel.keygenerator.symmetric-key-length=256 -mosip.kernel.crypto.asymmetric-algorithm-name=RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING -mosip.kernel.crypto.symmetric-algorithm-name=AES/GCM/PKCS5Padding -mosip.kernel.keygenerator.asymmetric-algorithm-name=RSA -mosip.kernel.keygenerator.symmetric-algorithm-name=AES -mosip.kernel.crypto.gcm-tag-length=128 -mosip.kernel.crypto.hash-algorithm-name=PBKDF2WithHmacSHA512 -mosip.kernel.crypto.sign-algorithm-name=RS256 -mosip.kernel.crypto.hash-symmetric-key-length=256 -mosip.kernel.crypto.hash-iteration=100000 -mosip.kernel.certificate.sign.algorithm=SHA256withRSA -mosip.kernel.data-key-splitter=#KEY_SPLITTER# - -keymanager.persistence.jdbc.driver=org.h2.Driver -keymanager_database_url=jdbc:h2\:mem\:mosip_kernel;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS kernel -keymanager_database_username=sa -keymanager_database_password= - -licensekeymanager.persistence.jdbc.driver=org.h2.Driver -licensekeymanager_database_url=jdbc:h2\:mem\:mosip_master;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS master -licensekeymanager_database_username=sa -licensekeymanager_database_password= - - -hibernate.hbm2ddl.auto=create-drop -hibernate.dialect=org.hibernate.dialect.H2Dialect -hibernate.show_sql=false -hibernate.format_sql=false -hibernate.connection.charSet=utf8 -hibernate.cache.use_second_level_cache=false -hibernate.cache.use_query_cache=false -hibernate.cache.use_structured_entries=false -hibernate.generate_statistics=false - - -mosip.kernel.keymanager.certificate-file-path=classpath:cert/mosipio.crt -mosip.kernel.keymanager.privatekey-file-path=classpath:cert/mosipio.key -mosip.kernel.keymanager.certificate-type=X509 - -mosip.kernel.pdf_owner_password=PDFADMIN - - -#----------------------tokenidgenerator----------------------------- -mosip.kernel.tokenid.uin.salt=zHuDEAbmbxiUbUShgy6pwUhKh9DE0EZn9kQDKPPKbWscGajMwf -mosip.kernel.tokenid.partnercode.salt=yS8w5Wb6vhIKdf1msi4LYTJks7mqkbmITk2O63Iq8h0bkRlD0d -#lenght of the token id -mosip.kernel.tokenid.length=36 - -#---------------------cryptomanager----------------------------------- -mosip.kernel.cryptomanager.application.name=kernel-cryptomanager-service - - -mosip.kernel.keymanager-service-publickey-url=http://localhost:8088/v1/keymanager/publickey/{applicationId} -mosip.kernel.keymanager-service-decrypt-url=http://localhost:8088/v1/keymanager/decrypt -mosip.kernel.keymanager-service-encrypt-url=https://dev.mosip.io/v1/keymanager/encrypt -mosip.kernel.keymanager-service-auth-decrypt-url=http://localhost:8088/v1/keymanager/auth/decrypt - - -mosip.kernel.cryptomanager.request_id=CRYPTOMANAGER.REQUEST -mosip.kernel.cryptomanager.request_version=v1.0 - -#--------------------licensekeymanager----------------------------------- -#License Key Properties -#-------------------------------------------------------------------------------- -#The length of the license key to be generated. -mosip.kernel.licensekey.length=16 -#The list of permissions separated by comma(','). -#NOTE: ',' is used as a splitter. Use of ',' must be avoided in the name of permission. -mosip.kernel.licensekey.permissions=OTP Trigger,OTP Authentication,Demo Authentication - Identity Data Match,Demo Authentication - Address Data Match,Demo Authentication - Full Address Data Match,Demo Authentication - Secondary Language Match,Biometric Authentication - FMR Data Match,Biometric Authentication - IIR Data Match,Biometric Authentication - FID Data Match,Static Pin Authentication,eKYC - limited,eKYC - Full,eKYC - No -#Problem of using ',' in a permission -#-------------------------------------------------------------------------------- -#If a permission is named as Email,Trigger -#Then the permission will be splitted as Email and Trigger as two different permissions. -#-----------------------Signature service---------------------------------- -auth.server.validate.url=https://dev-int.mosip.io/v1.0/authorize/validateToken -auth.server.refreshToken.url==https://dev-int.mosip.io/v1.0/authorize/refreshToken - - -#mosip.kernel.signature.signature-request-id=V1.0 - -mosip.kernel.signature.signature-request-id=SIGNATURE.REQUEST -mosip.kernel.signature.signature-version-id=v1.0 - -mosip.root.key.applicationid=ROOT -mosip.sign.applicationid=KERNEL -mosip.sign.refid=SIGN - -mosip.signed.header=response-signature -mosip.kernel.signature.cryptomanager-encrypt-url=https://dev.mosip.io/v1/cryptomanager/private/encrypt - - -mosip.kernel.keymanager-service-sign-url=http://localhost:8088/v1/keymanager/sign - -mosip.kernel.partner.sign.masterkey.application.id=PMS - -mosip.kernel.partner.allowed.domains=AUTH,DEVICE,FTM diff --git a/kernel/kernel-keymanager-service/src/test/resources/bootstrap.properties b/kernel/kernel-keymanager-service/src/test/resources/bootstrap.properties deleted file mode 100644 index a81aefb24c9..00000000000 --- a/kernel/kernel-keymanager-service/src/test/resources/bootstrap.properties +++ /dev/null @@ -1,19 +0,0 @@ -spring.cloud.config.uri=localhost -spring.cloud.config.label=master -spring.cloud.config.name=kernel -spring.application.name=kernel-keymanager-service -spring.profiles.active=test -management.endpoints.web.exposure.include=refresh -server.port=8088 -server.servlet.path=/keymanager -#management.security.enabled=false - -#disabling health check so that client doesnt try to load properties from sprint config server every -# 5 minutes (should not be done in production) -health.config.enabled=false - - - - - - diff --git a/kernel/kernel-keymanager-service/src/test/resources/dummy.pdf b/kernel/kernel-keymanager-service/src/test/resources/dummy.pdf deleted file mode 100644 index 774c2ea70c55104973794121eae56bcad918da97..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 13264 zcmaibWmsIxvUW%|5FkJZ7A&~y%m9Oj;I6>~WPrgfxD$eVfZ*=#?hsspJHa(bATYRn zGueBev(G*EKHr+BrK+pDs^6;aH9u<6Dv3$30@ygwX}fZ|TDt1G($Rqw927PN=I8~c_R69-cY5S*jJE@5Wr0JUS6u!J~3#h`{ZMo=LkbbALoD8vfgB}Fh|2>mhOnfS$3 zNV5}8Ox=$fj;C0=UKy*{myZZPRVS|0mqr-HxZAy;()@wxQ}MN`QWAZTXb3Z&Om9W2 zbnA^OWoQbAW|3W^fw#J;YzDato8*`rHQs+@W70D&SyT{wb`SN*3nI z5G%$wJlq932=n{60Eii*9H8dFih2ks?QY=>nAFL=5g^P@#b{YUEHt0S$D7WbX zx%TzvzIK%zpvzLEd9LNr0ch#LFf_(9 zEGt0C9v~%b54vynAc{~;v&2?S(-sTTft@9CABMNFZHtY1W0-99CEbUNfp_yu{LDBz z@8z^$LPN$wX4Hi+dZQs6K3QiKKF0}Nme@EII;;F}IplC(YvT*C3-Oh#(A}e5pIz01 zyR}D2|ftBF0T=1moHZy}$wS*PSCmSzHQ%x z2tCQQCx4jt7w1cuhY69~eH`31KC4)ZZJ^)f=IabocAkBPa zEeg25yPX&9-i_N(Qiq!I3RDrfx&0t^i)&MSQ1D(w%|%#LTNr>1cPiltAYO;6kBn(B?r11c^Bz~#)z5~~V+*`U)lDFtKbZ|;? z&4wTUtK=KE&uQIWUQv1mDE;LIhXXgx44PMa@%Z<7a& zx45^oYSnei^~%}`?!O-+cgfSmn_c?`=Gmm*Z^I(96ve&$zDs|)r84)IEEiE1kfQ$q zm3km*m1)PjdU9nkk9BTlidI1~M|O~WfP7AUu2T}d>5is9l$<%;7r2&Re06w>W$KM~ zqITBTd=Ln>^crw`_N?{ z;2d_=E0n!*NisQ|XYuX9q3+UcqdA(MC45|>2tz^c6HdZOmXTB?X2Elx@_0f)1z&-gS;UxN`>Ll-kWb0X0 zTrQis=w9sJ(q7k|@|k3SA~DJ@uMXP@4(Mgn+LJC+3F~3NHW71pIzY(aHg~{O+squi zWO_|F>78)L5*gcRXXRD9IzQ(ddSxh}E7(8sC~EYrOz$9BkSMBCkGGO9FuZ{#*mW+h zvwE7d)6Ag=a*R5URs>}qdqb_E6g)kN2Wel;pWe9=hZ)XvRZR!RQg&gxAPGj8J0!gR zrdV<2@MZQ?_Ocbd5@0zI?t>$z3eD80_h^{DI)H5lk`T4lbn8kteH3%fOBH^g26#lLN2&P^s zr&d05GDs)u_8OKzCgNxllk5pLC<2wKmghL{zW%}5^}%S$?d=3OzjaSzT3>uWYikZN z2ZcR7*L|%UMs|u)wMi7#vkN?cxlBcyAM80Tyzzv&zHMF1TH9?Mx5&E57P^)^zE5N| z^foq}!--if$Uj=U6Tc>EM!Pv)e^_SZSdvtQ=@>)(ONejQ!XW8u6>ESl<*s^6cH;Q1 z#n}nL{#|{l}}@td^zNSA;R{`3A&Jjr8L9(3^2FSyZ1W9$%;!XP#N2 z-SAzyRfxtgq^py7_3*GJFO%x_v<`xJ46`~S*IukgQDKfLxzFnS&GYL!1LA{I z!c#{A90{k(b*tUfbgjOH>}{#V;%^O+LUU<*#QkLtWzjho*Kb?Cr&wC38%wxpn}^Wy zG6EpV9x3xioCWA6H6=aE3)%jmZePu#Ji7wy0CmkDZNG`a{J1i-2`Bt&UrFb&<~V$^ zy9i`R1<35M&{mtCz144%v#7LKBTPPApjoV}#W-gDc5cn;A@Mbt#zXUK@J9^vj*ME( zo8(%K{c-KDr8n1-I&Mjn)*i|pF|7l*`fXvo8-z&j{$NOfUPM-xILbX1D29IHp|__B zL*JQ8*7-VrZVY*&$!PiE%zv@osg`qx0M8+w9iy7Az7;HYezs;5NRvrdNM~t@o}5Gc zjagk3Y_>6!Ct;ITqhu3FojJO^(^SG-($M4|frkp?4y-QoSmFcw9Z%(z?eC0kGi9@? zm(vAgXU|%!6_)CrnqYL-Hj@B5hA?#8C3G^cjd?0dMSZ!wbe%O4bWvlIG=nwOEInVj zhjzd`Bry8sXBTfIUr+juZH5JyE#7~UQiwR!gmG@wm}aNyo`13xEo)tzP64MWWG|j8 z8u8a2_=C2FdRZ9(eG&Au`@$mY9vvWldP-@wj5@38H0W2V8wnaQO?!)qoS_J=(ieoI zOvH}mkBRh_p1oTW66+?3u-GH2Ex~c=BQiwpJ zJlF7O2PBaCojRRL_mp44*Iq}vcRFpBD>V9M7do5{w&b;4^<_V~Vr{+O_&hz9k5Sm` zq3|%Z(6B5~wz2k0iH-QlafAa>1%ZebdxkR;6SdA?@dK|4Jf8PIO%64Fpw$6RYG2R# zX>Iq(xf`5Xk)79-@;BAQjlWu|w@Ss3sJv3Ew&%lBu-H?vYsC8XPJD!lkv*A~z_-k= zLOaM?B5}$Sf-KF5BWHoB51WFA{GlweQna618{*tqVn)YKUVq?khU_=QER9uW?N17xgAponbjg0W`=>f;sulH3?st)Y_@k$We2-__a>^{E78lUiI13qq!3# zwxMEl75MK1q`~J>ST#?`mUx#vr%-jwpZ+DV;W!0KNkZmO#sK)zt)H@`EQl6RRWhwb z0&E7|fG~@z)wlK1-RsxN#8Gr)D5=xpv=b}=CWPbwz@(9bIhD0Crd-Q>qEo>~Gh{X7 z77AK5>TfF0wK!?7Nx!<5uDy?D{Qg$SEc_R3J9EuH!Z@qmEJ*QRRHd3BPirM6783nv zAnab$>rhdDJ6pO@%Ox(}BYw{Ba<3|=A%Fg5_Hfxj{%CfzZCFO{?%h&=?%CNBvi&p; z(otqN>+5giLLa^*G?xzN30=IgQrV+r7dW4bX;zKtuD)O$UnwAKC?CpkPt{77nUArH ze-jKcCfRrOlp(Q^b&W}mrgt4n%wikNxeSBBE_n>K-IOIzi6!<)xGRYA)wGgqp^s@d46N#krDHPc#9SOgXhI7Vbj?B z%c6@8dCOGPYBoNE#3N7HD^ihbC9*xGm6chu;?fcuv)s01keHHZ1vXl5D;29O7wZBr zyPzyLZHKMtUI%PK+*X2zTFtaDzU1qn(H=hRRj-SoJw7I5i%4b0u=&InEAKgoae-lp zXk0SkjlJ52HruS*1QykTZ&aCN`PbcKuw$1st{peJ@&aF^aR@~{XA@L&YvK%+VU}G4 ze5iuesu&i6=*#nvHbm_v-ZLr5^Ij#|YSAper4XpsH;0x(2h1-tIobIy;0~2a( z!G($SB!iu#P;;hGeI~C`O=-3|d~zoB0!`*JrU-)Ko_X5#kSpy5o^z49RG;{j#l~45 zF?X9Ih4IdviT(8@+q|`BveLTprbESZ6^2I&ew|V3pDXRe9gSyXT)zzqKQ;gCD;p+( zM)2(;YJ%P5)X(N3ZSn>dn6UIcEcvQOXZBn}uD!7V0yXr$f+d@eTSYoquPit2S8cPW zA8t3dX)Cv{0cKF`@e|PP(xS0|z2_R0(P6)#+kC$0^5- z$7Hs|bOQanE z1oJ;uh(dYiDt}mVmtC3&HaGT6-dY429v#ySHJ7V)C8ow=PSmnEI)=b3_RJsU(S*+J zV$p3>RkK?DFvTc;(-T=h!1u~CP!pE=0eSSu#c@N7S0Z57CPg}!5z{QL#`2v?DJDt^ zCGN{0p-&&=)Sb28Xlo;ZXc^CGdwL9prf30uu$y5aPeWD6WIk4%%~DEhTiwOvy!rS% z&3z#DWo2qBA*=M2xIu=_R0sbrmP;Y?_rRa^k}3WYU6n9H^(})Zi-woMKKXfgbab@J zWx3DUr0MLpdDYk_LO8As}d*Z=x^K+uIv#T&SnY6&C$9 zBn1u`G#TBt+n5b%a;Cr0h^sm5Fl^OdxJ^8IebW);DWATq#Ba=#rggj*wNKy5NMzz& zBm`bk9bcSVPJbC`dHrI>o^=LSvTFpT`VAK`x_naOpvS~*l2$1vIk$avBA!|aeZ+7c z$_9Zzh>fc4$uX&w@-$VORCscG(B)OA@SPj>BNY3gxkkcPgNi9bE=?&3A4`3ekrdsb zn~`M;p8I>4?@@ZI{9Afv(tC@pp@Oe5BYUw-%&J_WaTBGls)&d8q?t$i<<@=_CNfH! z4H!ww7#gkp_^`bxZaJI9@C+A9x7@E1ZRoG5PL?w3GDi>`8Qq%I+0ygfT78%{Zt#mP zqX0CzaHKn@hAOQsv=^8UbfpuyFnT8Ht++Vmmx$~09!e{5t8fMkEjr~tfIxMlIpr4zGwvEIWKC2`Q#C)c7QF9wet?hE zLKoU?t@nqm=iBc` z8_((*(i(g}7z)3{%SJ!uya{?Ir-2^Fiap*VC4pF@N zpL5F*DG+(taLhdu4DbyAP(0&60n@%?G~hHugBI^-X6@_YOu}8UqwbQ8V`2vwDRLMz z)aRFo+r1f?5idT9xRF`cjgx$a-IpH3AH|bs$emw}d23*3aU0hYNh4(D0o-Z+wIX{d zeann?lzjgsAt62`er@<$`G755?i7tl%CHNgXp}#j>j&S1n5wZ;ofNbI>B2*4L1}@3 zq(LzPqn()w{KBsX!5*a&=dv<}t=R%II;TcQatbnKM7S4Q1PQIoT=^$#=>Y(m{mBYtl5W z6}|l4kxikOcJ`C3o{TSxIi?8|N6sH7Lkhq5qttl@uBTA|-cBluU$hU0&xYKvNidrL z4q>|j76}G1Db23Fa|XlFm%W&jW0h#7B$_FD-ZhqJ5#7i!0ZmCrereX z|Jlf`<1zR2akFe|boWv-r=}kM03o|%$mZA7Of2T99u~e56~6sh$P=yk9f!H6msn)n zvFOLF?W?iqi6fK9C)a42Sgt0kz4#M6 z-UY6451Er~=V;ITs1O-q*>}{;bs74MMZ(Z&=Z{5#q+i@cw^vI#0|Dh~-Dh-tn2I(S zTXXp-bLEG{p0#BbIqIcTM|DWZmr`&br8u)jQ`CR*^+g_fIX%=K+)x}F%Oak-Uh$6nIHUavnNV5M7YffU80QPRD%y>T{bIzn<6Rsy zb6cW6`?0EwSn;uJddPn@`?^Cry2s(6ccP1ykKr!kmDg2~zbTJq@+e(z5N>ZNr|8$j zPi-~ofp7E|Xx1#H+f@UR@AS}iLP!}}dRwf{u!avAq-_hNw#uaoOD{2jo*eRn8$~bDK`h1&ssOC6ekGV38+hU!KR z+kpnSzT;y#o|V2h|F?SY4-z1MFxz0;)@Lk`H>Cj zSl@fR%*@F79;HJcsX%L8_d!%TwmQyi$|n&C{oBMJ9~Xm!@@#lZdz(WB9SgJ#NIC%@ zy+~ZnI|4E`7f@W0Y9I@N7UTs1fTPD-ZiU%Lr2MnP+2h8AGh?(WGVf>h@W-_M>jRkD z(KNxvo(UJ7)o+*t%fCcM10;2XM$1NAFKwhp(c917^io_ynn-yv58IFIF*UJUw*2Ma zm?a-a1yp9B?WxpLzap-c^$HKkX_IfT_W8Lqaltl*A%vZSZWAe`Kv}vjz}>Tc;Hw9T zA+Nc49X&{WDmxY~ReV0YceXdL!$9mTL$Q@_vXIW6I{G=`$KR7jFcE&IsHwnKX;KldV#YL z(xwKAB5cFiz+r6m*5iJvo&E)XQqVWjmA}BfyVS&dm9&Y%$Sp^sW!JE3iI0v(kQHdo zmhWk|gC!e@CFKPv4BE*U;mYo0y}J0J-Fhu!c%v+paQf9+3Ed2EkfPt(D7|Ok#t)^PGr3Y)RGfvO=k;@Xry=Cf3fLCQ# zi`%oCt+vyB-t{iEgI&+2dczmnMXj>EOmSpMuuL8Ob`1$D;fc$wM6j2HH4Q$ zqaoj&M$2sLhpptdJMbs!krJId=iOd}HdP4Lt@yf42OZ{pOoQ4_gShz_sMoWYX}yQd zDQ8(tc7UvTt%`0#?9K!C^J>GpucEnBhnsWg102Z=uzOlwez^q^j7nV$krID#wC}A$ zcRfc2)T5Y~({6@1`{yL-Lzs;miT@C9|1SIFBMK7cz*E;v2H|EStZphjfb5mGMpw{q z!pl;Vw772tuvDH4o$;j4u8)@=m+&BIf4Ix(u75P?Q{4Y8^uvpq)mCW(enuQc)hx$B zOY{`_*%~bm%k*x6y;)D8_-yYbMsC8y#1H}89X;M=a#*HT>d*NFf}x$pQ&X?nFtvzA zKH|l8y;frsm|&}<%&*}Yu}Yn0M=Jy8qe%<1qXRR%Nut}Aqr+1pQS*D7Cp`+8Y`RO02p14DyVOmSYlEzZ;9&JzYhtybMZ%e4s zlks=V(+aJ!LK-()3ox`%9c)lx#3#y4{ulL6KpG|&>9`n?Uh#m3G-mZy-3h98Scyja zH^3Pb7?P z+2hAkyvg}g$#)n$Gs2fL19JNOZ|~>Nx(|}lmwesC!>?Y~72mpf4XZ8t^TIwbCk;i0 z+a2ymSZ^=OrtrSH!(y#Vn!8KWk#O7<1-!if+`dDDy18U7wS3k$lIeM}Z0fhYqI)+x zo*o4*S$S|hGf6vL>PaQ(OQ_%eskx-G-FV|dXHbTH<#w@RbeIx9I$d$xqHh`{*&d3y zevlYNk)}w@cuu4A$^DYJsOvO7VBaom@Rx@gb$V5IKJ{Xue16H-1H0j=U0brW-aVRG znWCQRkESBmD^4?a7mB@!jf2>(Hs=Bd-;XX1oEilevb9axB^NhIPLO>jl03S+Rw|fx z&oIsIk(~W!4$zzKF|uSR<@S#;{r;fKup)iDaxz_9JouroY>XHcrN(Mm@UHV?-8bCh zXGfY~7U`rCasv(h-R*ava)^ zF1`BMT*n3xQBTdM?`n&h2Ecf*XXuLo7Zyl_El(v~oh>}mK01$%0a@#uzyiX_g>Bav2XWwH%YekAxU%pBT!p*?%cS#zA zv;^eDC#KZP@7o=^GDc_V8<3w>`*L(+=A#(fcH)dGjqM}Vk_el+c>B`{9xm<>IZ-Zm zLL!-Yf*3nju_(8ZGUd9*K`iofWW+BYFnZF&+a|=yxqV?oUOcG#ulnSR$DMs|e5Tph%WW zVjzE3nMh7+rG!}av)+~;o$#+EHyPX zzOUO?^#)Jh*t^b7pTW+I%f;xy&JMPCO&5RR``BmHX-Mw{qoJp9BjKea$;A9%>-iEZ zvuUBm%0j5UWax~`ue!K6dDdip+zs3f{+qQKqH;9C(1Z@95()-Ew=`BdLh2VS3zI8qYGH&&7m9+vpUc+x8l!i-ATXKhw34XL2;ya_VIQz!OL^)8mtqnb?q=~&^h-$;Zn^HRZ2p(gH z39An;`AWT=i&VP0u&CUe7OYW51Icv=q%Vc7%Zm z_uAp9n}osEUdk2*pV)*i`WRSa-FWtCwGqS-75@K#V0)r;+0(0XVp9vnb7lWiMj!q= z>Zf(ioa@gSwA55Jil$lh)%4U<)$j@HTQU2KwuUUsZA*2O^QTKobak8g0Qb~ROMTW7 zfTF2yF*na6i(lQ*Nq^rPen^0>$$b`K!Kp{FVa-VF`kCiXZg0Vtr}i*rcpny_YOR!} z+?Jiv?dWlT`}o$s9Fxt%%684d7ek-q-Q~jS*I5+8HtvSw+Rp!D=+gVr!gqcYy9K74 z&eClx6f6{1Din;ynjz?XZlJ~W7^A@0wiHIt8$aou;f>MYpU%gUlDwAK*nX0#vHtyl z_C=B+ZkOffY|oR^2>(+IlZCTMFirZMhn>bqzR=38hvJpcM4-@gUYY7_k^G*FW9;5r zc9q4c>C?hd{uS3{MThN*(w!3e05e?bI#SNlo$U&%>((Dz0_JeqbG|}!wI$& z%q2JQ)Vas;i0RYqNXW!CC~QK%u$K$beGI zT2KuzMjus26(zmofK;m2gY%d*o~sHBKA#`RBNc9c*-GLmbgh?*9V;^TBSot2E%~Q5 zl+R!WA_h_JT;+irbJ#Z-tSy-;B^t&&dOSwPV(T!CB)no8Y4sP%k(MD^0P!NL1vK&7 z`3luW2$gkI#Zf>IZT2=m4R&e@d zeo#B=Q|9`w8}%|)f%GBjYO01&Dk5qjm$+#1yia#CE=Sh~88Vdp%|VU}0a6mF@JkhUY&~W3f#rHK-1Qdo z>0*z5?#-hQUY}k^X7~1bkI?($-~3#c3mF4Cl@2%|0@1=ARZ z^qlNaN63&>;O_~mmto}?tAhznb}p;GpyIq1Z^yf<_6Ui~cpbbP;uV7W!+ke>wYG-f zPPz2~%UgSs(>vsKFle%uo=WIDYz;BR!doAy)aQ0QCpE_Wz1XK+3Kpr=V_H8w zqzaizn9ALx#?fo-N)_CtENYH*1|ID|x=xa9d#;9~1Wgrcx^8=evrfky*Xj`269~A;kh^O|ewZnM}=SmM7NX=?h#jjLh&1kIT+A z)If4luYo@s+e_L&eRJ$gw1`)>u#efOq=M0iYIPS$GII0z`T56eNxK@~Y%*^~Q&w$1b)jM9Z~kuRc~YX`6r#ySCskW5cq|#a39s;ZiaL~OdEpgu z1k*sKkLZ&?6fAi=)77yKI1xii%)@DG8r}663xkJcwLTj?s`h{GP@_2}`A|;w7zrzk4QOQ*O$(e|M^<`vLD*1^i>Nr*= z+A`y@f{!zLi)ys9OrFM5`Qw0292Ciyq>zC>8(TkG1O;#UUh?#I08kuwpS_vhufJ0v&p^Yr`=^WG7!qVG(8n9u7=J64fr zQq7B|9rzl7s)I_|8UeVp?=cqGILQ}0O(n+^vJz=vFBU9JmG$=DWzi+qCHw@D0a7`M zA`%pmU8+8W{u0{2*^tg&3;I&i`4`{YJe_n8 z{viTJZL?$}#l9w${3mydrW>Z%nY!WXf$HJv5$Zw4F%7^mXWsZ-s&olv31;C*KlH)j z?j?Eika^cI`l>)WJ*ga?%>0HwJm{%<)OP8pdvwMG@fm;Ca`jfy7ixY-sic42*f&ld zJg3(O0~;=Zsp@cdUj@&Zj~#~LX=F5Ws@!Ik0-~(wlbJO6&)S~s6WrAW9lrQ%6+S03 z&P&xJ{;BC%2s%J#uxZy3=Fc}fkwE9(T}QAK9b{FT!L3^PQ~;#X$T|9v&JFq)ru$h|ls zvPxYyWT}V&Dol3#)t6pVE4nIClEq=r++eGcG-tkOW4{n$Ra~3z?`@_gXRUiR`SrhY4K z#>C+t>pNtm>!Zw*;p^qI0|g<)Ob`r0jaN6asw2ZGLT}bMbHnQ$OH8cR7{Rq?=4%&x z2Qe&O`w$~b%fuo>fkgT`PVx=uto@&SdDpIXL)<da|A*x(b?o zdUj^iN+B9%;2{1URo7=%m@r*RJi3fQNO_`AZY;b#tClm;A}NQF#!Y;pMMdh=^fO@9 z>J>Xv^joKJM>M7x=xh!oSLO3JlxVwTn$DPHdGsnkAvB)9d)IE6ZHgd1vd+Z;W1d682CBy4zti z&6;T6!rzSKIy&zKKfAx9J%7q-=Mac{u-_GIYEaZt*`h25Ne?ch`E_c2{pGA<;nVkx z102u6#||N$g5MhA{!rFwaI(;8$S{1DePGc^L~j6?Q$2QMIO09 zPdma#_kX(|;oOau(pX877ac9V4O8x3g{Mdbr6oS)7 zN0v#H_j!bhUNl;q>GrkeA~){;lCg@&Mg5(z%E1HV`d7{>_}@9JZ(VJn>=HKC4q{My zLpw8D2OD@&E}T?=SV7rE-XI?4H+E(aOI8sZOC$NW=!leE6MG6ycn2;fB4XpB!^#Z= zQ?P=-+!R0#4h{+c2LPbUF6{uZG&6i-ZDI+f;6P`8V{ZtxcA((p;6i6ds6r4x005m` z6k;m{H8U}FK+J;+syaZe)G2u2J;eI(G+`)^0+C~@0#BIzJLi_?-}e8NR15?I|34|k zx>2LneiYApj|7nW4k1sp9h-vz^G);Jq7ONB*clw!(IJ2QT3sYWS)>yb_Ual2Um3r5 zw706UJD48HLY73$&Gm=sl|EYND&Uk>VT!eN_p49f6HS<{TU>u{4&#WYh1dwy^E8il ziH`_=$2m8k)y$Q2yDZQluP+AZbND!Yi7Co@fwHnw2pV1bo*=wGx2n7Urt$y1@imz1&#&nK47Nw zT-dLY@^1NHY?5B#-Qf9?`lA_={@NnLpmwJGQG7&oU}0>) ziZ`GdjY(jIKi2Q?e+d=de}nq3pkP;ZG;lyf$Xh!{=x?qF#2$)p%>NM^W_I=tqNWf# zgv;e1fAtY=)-W@2FtyhKb8%3Bfj|mw00#vR4=)857d&XdU z(4fLD4>dA_AWjHkeJ)-u3LZ|NF1w_ijiW6*A6^xXD#Y5}7O{k(E4!#F{9rhl8A4Sg zMcAb&9N>rx39*a9v4(4~r$8jq|MLt0{*hTPYU2nu0sub&aQG~$!9>qU@%LGVw1{ZAdD5crj3WAdl2KV62-uIT7sX=aUZ*>8aV1F3(c z_P=p-FtxG!8!9*^U<3>RcoByeFaipAK|lhB5)AqaI)n^@hmeEwxOw0OKK@%C0pZ{C z5o^F{FbEE(DEt!$_$B<8DlYiaV7ME855ql#Py+_S#o(c8`L;d6lqRR~$cn(zq-4};(pf)4`xt=`PWS`7YO27?$MdgtpDP{`vCa4 z{2x3Z5bm@8-~oUj5Zv+q!Gl}N`CoDX0N4M*gTIpgb1nb?;)Y)s|FIqb0Ot6gw!m#h zTnhg~j+YZ2)c?r?0yzIm4hZ1=FTFrc;D6}=a`OJeW(PY6{AFi{I1;L6ZcsR+>?$@k z@FNVDLEL!K*2XpzfZwk|I3Y%%Lm?mm76XGtKw?0k2(JV$kO#;s#>p!o!6gRf5#f;l j@(7{-|3%=32kuUL2Z)`+Z(jm{U>-0!Ev>ks1p5C2Hj`#V diff --git a/kernel/kernel-keymanager-service/src/test/resources/logback.xml b/kernel/kernel-keymanager-service/src/test/resources/logback.xml deleted file mode 100644 index 7285a15d201..00000000000 --- a/kernel/kernel-keymanager-service/src/test/resources/logback.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - %d [%t] %p [%C{1}].%M.%L : %m%n - - - - - - \ No newline at end of file diff --git a/kernel/keys-generator/.gitignore b/kernel/keys-generator/.gitignore deleted file mode 100644 index d6c5e2c602a..00000000000 --- a/kernel/keys-generator/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -target/ -logs/ -.project -.settings -.classpath \ No newline at end of file diff --git a/kernel/keys-generator/Dockerfile b/kernel/keys-generator/Dockerfile deleted file mode 100644 index 9afdb73e82d..00000000000 --- a/kernel/keys-generator/Dockerfile +++ /dev/null @@ -1,65 +0,0 @@ -FROM openjdk:11 -RUN apt-get update \ - && apt-get -y upgrade \ - && apt-get -y install unzip - -# can be passed during Docker build as build time environment for github branch to pickup configuration from. -ARG spring_config_label - -# can be passed during Docker build as build time environment for spring profiles active -ARG active_profile - -# can be passed during Docker build as build time environment for config server URL -ARG spring_config_url - -# can be passed during Docker build as build time environment for artifactory URL -ARG artifactory_url - -# can be passed during Docker build as build time environment for config server URL -ARG spring_config_name - -# can be passed during Docker build as build time environment for hsm client zip file path -ARG hsm_client_zip_path - -ARG hsm_local_dir=hsm-client - -ENV hsm_local_dir_name=${hsm_local_dir} - -# environment variable to pass active profile such as DEV, QA etc at docker runtime -ENV active_profile_env=${active_profile} - -# environment variable to pass github branch to pickup configuration from, at docker runtime -ENV spring_config_label_env=${spring_config_label} - -# environment variable to pass spring configuration url, at docker runtime -ENV spring_config_url_env=${spring_config_url} - -# environment variable to pass github branch to pickup configuration from, at docker runtime -ENV spring_config_name_env=${spring_config_name} - -# environment variable to pass artifactory url, at docker runtime -ENV artifactory_url_env=${artifactory_url} - -# environment variable to pass hsm client zip file path, at docker runtime -ENV hsm_zip_file_path=${hsm_client_zip_path} - -# creating folder to copy additional supporting jar files required at run-time. -#RUN mkdir /additional-jars - -ENV work_dir=/ - -ARG loader_path=${work_dir}/additional_jars/ - -RUN mkdir -p ${loader_path} - -ENV loader_path_env=${loader_path} - -ADD configure_start.sh configure_start.sh - -RUN chmod +x configure_start.sh - -ADD target/keys-generator-*.jar keys-generator.jar - -ENTRYPOINT [ "/configure_start.sh" ] - -CMD ["java","-jar", "-Dloader.path=${loader_path_env}", "-Dspring.cloud.config.label=${spring_config_label_env}","-Dspring.cloud.config.name=${spring_config_name_env}", "-Dspring.profiles.active=${active_profile_env}", "-Dspring.cloud.config.uri=${spring_config_url_env}", "/keys-generator.jar"] \ No newline at end of file diff --git a/kernel/keys-generator/configure_start.sh b/kernel/keys-generator/configure_start.sh deleted file mode 100644 index 7b899b385d2..00000000000 --- a/kernel/keys-generator/configure_start.sh +++ /dev/null @@ -1,40 +0,0 @@ -#!/bin/bash - -#installs the pkcs11 libraries. -set -e - -DEFAULT_ZIP_PATH=artifactory/libs-release-local/hsm/client.zip -[ -z "$hsm_zip_file_path" ] && zip_path="$DEFAULT_ZIP_PATH" || zip_path="$hsm_zip_file_path" - -echo "Download the client from $artifactory_url_env" -echo "Zip File Path: $zip_path" - -wget -q --show-progress "$artifactory_url_env/$zip_path" -echo "Downloaded $artifactory_url_env/$zip_path" - -FILE_NAME=${zip_path##*/} - -DIR_NAME=$hsm_local_dir_name - -has_parent=$(zipinfo -1 "$FILE_NAME" | awk '{split($NF,a,"/");print a[1]}' | sort -u | wc -l) -if test "$has_parent" -eq 1; then - echo "Zip has a parent directory inside" - dirname=$(zipinfo -1 "$FILE_NAME" | awk '{split($NF,a,"/");print a[1]}' | sort -u | head -n 1) - echo "Unzip directory" - unzip $FILE_NAME - echo "Renaming directory" - mv -v $dirname $DIR_NAME -else - echo "Zip has no parent directory inside" - echo "Creating destination directory" - mkdir "$DIR_NAME" - echo "Unzip to destination directory" - unzip -d "$DIR_NAME" $FILE_NAME -fi - -echo "Attempting to install" -cd ./$DIR_NAME && chmod +x install.sh && ./install.sh -echo "Installation complete" -cd $work_dir - -exec "$@" \ No newline at end of file diff --git a/kernel/keys-generator/pom.xml b/kernel/keys-generator/pom.xml deleted file mode 100644 index e0ac8058c26..00000000000 --- a/kernel/keys-generator/pom.xml +++ /dev/null @@ -1,351 +0,0 @@ - - 4.0.0 - - io.mosip.kernel - keys-generator - 1.2.0-rc2-SNAPSHOT - - UTF-8 - - - 11 - 11 - 3.8.0 - - - 3.0.2 - 3.1.0 - - - 3.2.0 - 2.3 - - - 2.0.2.RELEASE - 2.0.7.RELEASE - 5.0.5.RELEASE - 2.0.4.RELEASE - - - 2.0.7 - 1.5.21 - 2.9.2 - - - 3.6.2 - 3.7.0 - - - - 1.2 - 3.0.0 - 1.3 - 2.2 - 2.0.1.Final - 2.2.6 - - - 1.4.197 - 5.1.46 - 42.2.2 - 2.5.0 - 5.2.17.Final - 6.0.12.Final - - - 4.12 - 2.23.4 - 1.7.4 - 2.0.7 - - - 1.2.3 - 1.7.19 - 1.7.7 - 1.7.25 - - - 2.9.5 - 2.9.8 - 2.9.6 - 20180130 - 2.2.10 - 20180813 - 1.1.1 - - - 3.6.1 - 3.7 - 2.6 - 1.11 - 4.3 - 1.9.2 - 2.2 - 4.5.6 - 19.0 - 1.18.8 - 0.1.54 - 1.4.0 - 7.1.0 - 2.0.0 - 5.5.13 - 2.3.23 - 1.7 - 2.0 - 1.5.2 - 2.1.1 - 1.66 - 63.1 - 1.0.0 - 3.3.3 - 3.1.0 - 4.1.0-incubating - 1.11.368 - 0.2.4 - 2.3.0 - 3.0.1 - 1.9.12 - 0.6.0 - 2.0.0.AM2 - 1.8.12 - 1.4.2 - 1.4.2 - UTF-8 - - 63.1 - 1.0.0 - 3.3.3 - 3.1.0 - 4.1.0-incubating - 1.11.368 - 0.2.4 - 2.3.0 - 3.0.1 - 1.9.12 - 0.6.0 - 2.0.0.AM2 - 1.8.12 - 1.4.2 - 1.4.2 - 1.2.0-rc2-SNAPSHOT - 1.2.0-rc2-SNAPSHOT - 1.2.0-rc2-SNAPSHOT - 1.2.0-rc2-SNAPSHOT - 1.2.0-rc2-SNAPSHOT - 1.2.0-rc2-SNAPSHOT - 0.6.5 - - 0.3.0 - - - - - org.projectlombok - lombok - ${lombok.version} - - - org.springframework.boot - spring-boot-starter-web - ${spring.boot.version} - - - org.springframework.boot - spring-boot-starter-data-jpa - ${spring.boot.version} - - - org.springframework.cloud - spring-cloud-starter-config - ${spring-cloud-config.version} - - - org.postgresql - postgresql - 42.2.1 - - - io.mosip.kernel - kernel-keymanager-service - ${kernel-keymanager-service.version} - - - org.springframework.security - spring-security-config - - - lib - - - org.javassist - javassist - 3.25.0-GA - - - - - - ossrh - https://oss.sonatype.org/content/repositories/snapshots - - - ossrh - https://oss.sonatype.org/service/local/staging/deploy/maven2/ - - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring.boot.version} - - true - ZIP - - - - - build-info - repackage - - - - - - - maven-deploy-plugin - 2.8.1 - - - default-deploy - deploy - - deploy - - - - - - org.sonatype.plugins - nexus-staging-maven-plugin - 1.6.7 - true - - - default-deploy - deploy - - deploy - - - - - ossrh - https://oss.sonatype.org/ - false - - - - - org.apache.maven.plugins - maven-source-plugin - true - 2.2.1 - - - attach-sources - - jar-no-fork - - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 3.2.0 - - - attach-javadocs - - jar - - - - - none - - - - org.apache.maven.plugins - maven-gpg-plugin - 1.5 - - - sign-artifacts - verify - - sign - - - - --pinentry-mode - loopback - - - - - - - pl.project13.maven - git-commit-id-plugin - 3.0.1 - - - get-the-git-infos - - revision - - validate - - - - true - ${project.build.outputDirectory}/git.properties - - ^git.build.(time|version)$ - ^git.commit.id.(abbrev|full)$ - - full - ${project.basedir}/.git - - - - - - - scm:git:git://github.com/mosip/commons.git - scm:git:ssh://github.com:mosip/commons.git - https://github.com/mosip/commons - HEAD - - - - MPL 2.0 - https://www.mozilla.org/en-US/MPL/2.0/ - - - - - Mosip - mosip.emailnotifier@gmail.com - io.mosip - https://github.com/mosip/commons - - - Key generator - Key generator service to initialize and setup keys - https://github.com/mosip/commons - diff --git a/kernel/keys-generator/src/main/java/io/mosip/kernel/keygenerator/KeysGeneratorApplication.java b/kernel/keys-generator/src/main/java/io/mosip/kernel/keygenerator/KeysGeneratorApplication.java deleted file mode 100644 index 57eb87a05cc..00000000000 --- a/kernel/keys-generator/src/main/java/io/mosip/kernel/keygenerator/KeysGeneratorApplication.java +++ /dev/null @@ -1,34 +0,0 @@ -package io.mosip.kernel.keygenerator; - -import java.util.logging.Logger; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.CommandLineRunner; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.ConfigurableApplicationContext; - -import io.mosip.kernel.keygenerator.generator.KeysGenerator; - -@SpringBootApplication(scanBasePackages = {"io.mosip.kernel.keygenerator.*", "io.mosip.kernel.keymanagerservice.*", - "io.mosip.kernel.keymanager.*", "io.mosip.kernel.crypto.*", "io.mosip.kernel.cryptomanager.*" }) -public class KeysGeneratorApplication implements CommandLineRunner { - - private static final Logger LOGGER = Logger.getLogger(KeysGeneratorApplication.class.getName()); - - @Autowired - KeysGenerator keysGenerator; - - public static void main(String[] args) throws Exception { - ConfigurableApplicationContext run = SpringApplication.run(KeysGeneratorApplication.class, args); - SpringApplication.exit(run); - } - - @Override - public void run(String... args) throws Exception { - - LOGGER.info("Keys generation stated......" ); - keysGenerator.generateKeys(); - LOGGER.info("Keys generated." ); - } -} diff --git a/kernel/keys-generator/src/main/java/io/mosip/kernel/keygenerator/generator/KeysGenerator.java b/kernel/keys-generator/src/main/java/io/mosip/kernel/keygenerator/generator/KeysGenerator.java deleted file mode 100644 index 6570c65cb6c..00000000000 --- a/kernel/keys-generator/src/main/java/io/mosip/kernel/keygenerator/generator/KeysGenerator.java +++ /dev/null @@ -1,195 +0,0 @@ -package io.mosip.kernel.keygenerator.generator; - -import java.time.LocalDateTime; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.logging.Logger; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; - -import io.mosip.kernel.keymanagerservice.dto.KeyPairGenerateRequestDto; -import io.mosip.kernel.keymanagerservice.entity.KeyAlias; -import io.mosip.kernel.keymanagerservice.repository.KeyAliasRepository; -import io.mosip.kernel.keymanagerservice.service.KeymanagerService; - -/** - * The Class MasterKeysGenerator. - * - * @author Mahammed Taheer - */ -@SuppressWarnings("restriction") -@Component -public class KeysGenerator { - - private static final Logger LOGGER = Logger.getLogger(KeysGenerator.class.getName()); - - private static final String ROOT_APP_ID = "ROOT"; - - private static final String BLANK_REF_ID = ""; - - //private static final String MOSIP_CN = "MOSIP-"; - - private static final String DUMMY_RESP_TYPE = "CSR"; - - private static final String IDENTITY_CACHE_REF_ID = "IDENTITY_CACHE"; - - @Value("${mosip.kernel.keymanager.autogen.appids.list}") - private String appIdsList; - - /** - * Common Name for generating certificate - */ - @Value("${mosip.kernel.keymanager.certificate.default.common-name}") - private String rootCommonName; - - /** - * Organizational Unit for generating certificate - */ - @Value("${mosip.kernel.keymanager.certificate.default.organizational-unit}") - private String organizationUnit; - - /** - * Organization for generating certificate - */ - @Value("${mosip.kernel.keymanager.certificate.default.organization}") - private String organization; - - /** - * Location for generating certificate - */ - @Value("${mosip.kernel.keymanager.certificate.default.location}") - private String location; - - /** - * State for generating certificate - */ - @Value("${mosip.kernel.keymanager.certificate.default.state}") - private String state; - - /** - * Country for generating certificate - */ - @Value("${mosip.kernel.keymanager.certificate.default.country}") - private String country; - - @Value("${mosip.kernel.keymanager.autogen.basekeys.list}") - private String baseKeys; - - @Autowired - private KeyAliasRepository keyAliasRepository; - - @Autowired - KeymanagerService keymanagerService; - - @Autowired - RandomKeysGenerator randomKeysGenerator; - - public void generateKeys() throws Exception { - - String rootKeyAlias = getKeyAlias(ROOT_APP_ID, BLANK_REF_ID); - if (Objects.isNull(rootKeyAlias)) { - generateMasterKey(ROOT_APP_ID, BLANK_REF_ID, rootCommonName); - LOGGER.info("Generated ROOT Key."); - } - - List keyAppIdsList = getListKeys(); - keyAppIdsList.forEach(appId -> { - String[] strArr = appId.split(":", -1); - String applicationId = strArr[0]; - String referenceId = BLANK_REF_ID; - String commonName = rootCommonName; - if (strArr.length > 1) { - referenceId = strArr[1]; - commonName = commonName + "-" + referenceId.toUpperCase(); - } - if (referenceId.equalsIgnoreCase(IDENTITY_CACHE_REF_ID)) { - randomKeysGenerator.generateRandomKeys(applicationId, referenceId); - LOGGER.info("Generated Cache Key & Random Keys."); - } else { - String masterKeyAlias = getKeyAlias(applicationId, referenceId); - if(Objects.isNull(masterKeyAlias)) { - generateMasterKey(applicationId, referenceId, commonName); - LOGGER.info("Generated Master Key for Application ID & ReferenceId: " + appId); - } else { - LOGGER.info("Master Key Already exists for Application ID & ReferenceId: " + appId); - } - } - }); - - List baseKeysList = getBaseKeysList(); - - baseKeysList.forEach(appId -> { - String[] strArr = appId.split(":", -1); - if (strArr.length == 2) { - String applicationId = strArr[0]; - String referenceId = strArr[1]; - if (referenceId.length() != 0) { - generateBaseKey(applicationId, referenceId); - LOGGER.info("Base Key Successful. AppId: " + applicationId + ", refId: " + referenceId); - } else { - LOGGER.warning("Configured Reference Id is not valid. Configured value: " + appId); - } - } else { - LOGGER.warning("Configured Base Key is not valid. Configured value: " + appId); - } - }); - } - - private List getListKeys() { - return Stream.of(appIdsList.split(",")).map(String::trim) - .filter(appId -> !appId.equalsIgnoreCase(ROOT_APP_ID)) - .collect(Collectors.toList()); - } - - private List getBaseKeysList() { - return Stream.of(baseKeys.split(",")).map(String::trim) - .collect(Collectors.toList()); - } - - private String getKeyAlias(String applicationId, String referenceId) { - List keyAliases = keyAliasRepository.findByApplicationIdAndReferenceId(applicationId, referenceId) - .stream().sorted((alias1, alias2) -> { - return alias1.getKeyGenerationTime().compareTo(alias2.getKeyGenerationTime()); - }).collect(Collectors.toList()); - List currentKeyAliases = keyAliases.stream().filter((keyAlias) -> { - return isValidTimestamp(LocalDateTime.now(), keyAlias); - }).collect(Collectors.toList()); - - if (!currentKeyAliases.isEmpty() && currentKeyAliases.size() == 1) { - LOGGER.info("CurrentKeyAlias size is one."); - return currentKeyAliases.get(0).getAlias(); - } - - return null; - } - - private boolean isValidTimestamp(LocalDateTime timeStamp, KeyAlias keyAlias) { - return timeStamp.isEqual(keyAlias.getKeyGenerationTime()) || timeStamp.isEqual(keyAlias.getKeyExpiryTime()) - || timeStamp.isAfter(keyAlias.getKeyGenerationTime()) - && timeStamp.isBefore(keyAlias.getKeyExpiryTime()); - } - - private void generateMasterKey(String appId, String refId, String commonName){ - KeyPairGenerateRequestDto requestDto = new KeyPairGenerateRequestDto(); - requestDto.setApplicationId(appId); - requestDto.setReferenceId(refId); - requestDto.setForce(false); - requestDto.setCommonName(commonName); - String componentName = appId.equalsIgnoreCase(ROOT_APP_ID) ? "" : " (" + appId.toUpperCase() + ")"; - requestDto.setOrganizationUnit(organizationUnit + componentName); - requestDto.setOrganization(organization); - requestDto.setLocation(location); - requestDto.setState(state); - requestDto.setCountry(country); - keymanagerService.generateMasterKey(DUMMY_RESP_TYPE, requestDto); - } - - private void generateBaseKey(String appId, String refId){ - keymanagerService.getCertificate(appId, Optional.of(refId)); - } -} diff --git a/kernel/keys-generator/src/main/java/io/mosip/kernel/keygenerator/generator/RandomKeysGenerator.java b/kernel/keys-generator/src/main/java/io/mosip/kernel/keygenerator/generator/RandomKeysGenerator.java deleted file mode 100644 index 5dacfc00406..00000000000 --- a/kernel/keys-generator/src/main/java/io/mosip/kernel/keygenerator/generator/RandomKeysGenerator.java +++ /dev/null @@ -1,123 +0,0 @@ -package io.mosip.kernel.keygenerator.generator; - -import java.security.Key; -import java.security.SecureRandom; -import java.time.LocalDateTime; -import java.util.Base64; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.logging.Logger; - -import javax.crypto.Cipher; -import javax.crypto.KeyGenerator; -import javax.crypto.SecretKey; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; - -import io.mosip.kernel.core.keymanager.spi.KeyStore; -import io.mosip.kernel.core.util.DateUtils; -import io.mosip.kernel.keymanagerservice.constant.KeymanagerConstant; -import io.mosip.kernel.keymanagerservice.entity.DataEncryptKeystore; -import io.mosip.kernel.keymanagerservice.entity.KeyAlias; -import io.mosip.kernel.keymanagerservice.helper.KeymanagerDBHelper; -import io.mosip.kernel.keymanagerservice.repository.DataEncryptKeystoreRepository; - -/** - * The Class MasterKeysGenerator. - * - * @author Mahammed Taheer - */ -@SuppressWarnings("restriction") -@Component -public class RandomKeysGenerator { - - private static final Logger LOGGER = Logger.getLogger(RandomKeysGenerator.class.getName()); - - private static final String CREATED_BY = "System"; - - private static final String WRAPPING_TRANSFORMATION = "AES/ECB/NoPadding"; - - @Value("${zkcrypto.random.key.generate.count}") - private long noOfKeysRequire; - - /** - * Keystore instance to handles and store cryptographic keys. - */ - @Autowired - private KeyStore keyStore; - - @Autowired - private KeymanagerDBHelper dbHelper; - - @Autowired - DataEncryptKeystoreRepository dataEncryptKeystoreRepository; - - public void generateRandomKeys(String appId, String referenceId) { - - LocalDateTime localDateTimeStamp = DateUtils.getUTCCurrentDateTime(); - Map> keyAliasMap = dbHelper.getKeyAliases(appId, referenceId, localDateTimeStamp); - List currentKeyAlias = keyAliasMap.get(KeymanagerConstant.CURRENTKEYALIAS); - String alias = null; - if (currentKeyAlias.isEmpty()) { - LOGGER.info("Cache Master key not available, generating new key."); - alias = UUID.randomUUID().toString(); - generateAndStore(appId, referenceId, alias, localDateTimeStamp); - } else { - alias = currentKeyAlias.get(0).getAlias(); - } - try { - generate10KKeysAndStoreInDB(alias); - } catch (Exception e) { - LOGGER.warning("Error generating Random Keys."); - e.printStackTrace(); - } - } - - private void generateAndStore(String appId, String referenceId, String keyAlias, LocalDateTime localDateTimeStamp) { - keyStore.generateAndStoreSymmetricKey(keyAlias); - dbHelper.storeKeyInAlias(appId, localDateTimeStamp, referenceId, keyAlias, localDateTimeStamp.plusDays(1825)); - } - - private void generate10KKeysAndStoreInDB(String cacheMasterKeyAlias) throws Exception { - - int noOfActiveKeys = (int) dataEncryptKeystoreRepository.findAll().stream() - .filter(k->k.getKeyStatus().equals("active")).count(); - int noOfKeysToGenerate = 0; - if((noOfKeysRequire-noOfActiveKeys) > 0) { - noOfKeysToGenerate = (int) (noOfKeysRequire-noOfActiveKeys); - } - - LOGGER.info("No Of Keys To Generate:" + noOfKeysToGenerate); - - Long maxid = dataEncryptKeystoreRepository.findMaxId(); - int startIndex = maxid == null ? 0 : maxid.intValue() + 1; - - SecureRandom rand = new SecureRandom(); - KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); - Cipher cipher = Cipher.getInstance(WRAPPING_TRANSFORMATION); - Key masterKey = keyStore.getSymmetricKey(cacheMasterKeyAlias); - - for (int i = startIndex; i < noOfKeysToGenerate; i++) { - keyGenerator.init(256, rand); - SecretKey sKey = keyGenerator.generateKey(); - cipher.init(Cipher.ENCRYPT_MODE, masterKey); - byte[] wrappedKey = cipher.doFinal(sKey.getEncoded()); - String encodedKey = Base64.getEncoder().encodeToString(wrappedKey); - insertKeyIntoTable(i, encodedKey, "Active"); - LOGGER.info("Insert secrets in DB: " + i); - } - } - - private void insertKeyIntoTable(int id, String secretData, String status) throws Exception { - DataEncryptKeystore data = new DataEncryptKeystore(); - data.setId(id); - data.setKey(secretData); - data.setKeyStatus(status); - data.setCrBy(CREATED_BY); - data.setCrDTimes(LocalDateTime.now()); - dataEncryptKeystoreRepository.save(data); - } -} diff --git a/kernel/keys-generator/src/main/resources/application-local.properties b/kernel/keys-generator/src/main/resources/application-local.properties deleted file mode 100644 index b176a6b3dde..00000000000 --- a/kernel/keys-generator/src/main/resources/application-local.properties +++ /dev/null @@ -1,120 +0,0 @@ -#mosip.kernel.keymanager.softhsm.config-path=/config/softhsm-application.conf - -mosip.kernel.keymanager.softhsm.config-path=/config/softhsm-application.conf -mosip.kernel.keymanager.softhsm.keystore-type=PKCS11 -mosip.kernel.keymanager.softhsm.keystore-pass=userpin - -mosip.kernel.keymanager.certificate.default.organizational-unit=MOSIP-TECH-CENTER -mosip.kernel.keymanager.certificate.default.organization=IITB -mosip.kernel.keymanager.certificate.default.location=BANGALORE -mosip.kernel.keymanager.certificate.default.state=KA -mosip.kernel.keymanager.certificate.default.country=IN - -mosip.kernel.keymanager.softhsm.certificate.common-name=www.mosip.io -mosip.kernel.keymanager.softhsm.certificate.organizational-unit=MOSIP -mosip.kernel.keymanager.softhsm.certificate.organization=IITB -mosip.kernel.keymanager.softhsm.certificate.country=IN - -#----------------------- Crypto -------------------------------------------------- -#Crypto asymmetric algorithm name -mosip.kernel.crypto.asymmetric-algorithm-name=RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING -#Crypto symmetric algorithm name -mosip.kernel.crypto.symmetric-algorithm-name=AES/GCM/PKCS5Padding -#Keygenerator asymmetric algorithm name -mosip.kernel.keygenerator.asymmetric-algorithm-name=RSA -#Keygenerator symmetric algorithm name -mosip.kernel.keygenerator.symmetric-algorithm-name=AES -#Asymmetric algorithm key length -mosip.kernel.keygenerator.asymmetric-key-length=2048 -#Symmetric algorithm key length -mosip.kernel.keygenerator.symmetric-key-length=256 - -#Encrypted data and encrypted symmetric key separator -mosip.kernel.data-key-splitter=#KEY_SPLITTER# -#GCM tag length -mosip.kernel.crypto.gcm-tag-length=128 -#Hash algo name -mosip.kernel.crypto.hash-algorithm-name=PBKDF2WithHmacSHA512 -#Symmtric key length used in hash -mosip.kernel.crypto.hash-symmetric-key-length=256 -#No of iterations in hash -mosip.kernel.crypto.hash-iteration=10 -#Sign algo name -mosip.kernel.crypto.sign-algorithm-name=RS256 -#Certificate Sign algo name -mosip.kernel.certificate.sign.algorithm=SHA256withRSA - - -keymanager.persistence.jdbc.driver=org.postgresql.Driver -keymanager_database_url=jdbc:postgresql://localhost:30090/postgres -keymanager_database_username=postgres -keymanager_database_password= - - -licensekeymanager.persistence.jdbc.driver=org.postgresql.Driver -licensekeymanager_database_url=jdbc:postgresql://localhost:30090/postgres -licensekeymanager_database_username=postgres -licensekeymanager_database_password= - -hibernate.hbm2ddl.auto=none -hibernate.dialect=org.hibernate.dialect.PostgreSQL95Dialect -hibernate.jdbc.lob.non_contextual_creation=true -hibernate.show_sql=false -hibernate.format_sql=false -hibernate.connection.charSet=utf8 -hibernate.cache.use_second_level_cache=false -hibernate.cache.use_query_cache=false -hibernate.cache.use_structured_entries=false -hibernate.generate_statistics=false -hibernate.current_session_context_class=org.springframework.orm.hibernate5.SpringSessionContext - -auth.server.validate.url=https://dev-test.southindia.cloudapp.azure.com/v1/authmanager/authorize/admin/validateToken -auth.server.admin.validate.url=https://dev-test.southindia.cloudapp.azure.com/v1/authmanager/authorize/admin/validateToken -auth.role.prefix=ROLE_ -auth.header.name=Authorization - -mosip.kernel.pdf_owner_password=PDFADMIN -#------ -mosip.kernel.signature.signature-request-id=SIGNATURE.REQUEST -mosip.kernel.signature.signature-version-id=v1.0 - -mosip.root.key.applicationid=ROOT -mosip.sign.applicationid=KERNEL -mosip.sign.refid=SIGN -mosip.sign-certificate-refid=SIGN -mosip.signed.header=response-signature - - -#--- - -mosip.kernel.tokenid.uin.salt=zHuDEAbmbxiUbUShgy6pwUhKh9DE0EZn9kQDKPPKbWscGajMwf -mosip.kernel.tokenid.partnercode.salt=yS8w5Wb6vhIKdf1msi4LYTJks7mqkbmITk2O63Iq8h0bkRlD0d -mosip.kernel.tokenid.length=36 - -#--- -#Length of license key to be generated. -mosip.kernel.licensekey.length=16 -#List of permissions -# NOTE: ',' in the below list is used as splitter in the implementation. -# Use of ',' in the values for below key should be avoided. -# Use of spaces before and after ',' also should be avoided. -mosip.kernel.licensekey.permissions=OTP Trigger,OTP Authentication,Demo Authentication - Identity Data Match,Demo Authentication - Address Data Match,Demo Authentication - Full Address Data Match,Demo Authentication - Secondary Language Match,Biometric Authentication - FMR Data Match,Biometric Authentication - IIR Data Match,Biometric Authentication - FID Data Match,Static Pin Authentication,eKYC - limited,eKYC - Full,eKYC - No - -mosip.kernel.zkcrypto.masterkey.application.id=KERNEL -mosip.kernel.zkcrypto.masterkey.reference.id=IDENTITY_CACHE -mosip.kernel.zkcrypto.publickey.application.id=IDA -mosip.kernel.zkcrypto.publickey.reference.id=PUBLIC_KEY -mosip.kernel.zkcrypto.wrap.algorithm-name=AES/ECB/NoPadding -mosip.kernel.zkcrypto.derive.encrypt.algorithm-name=AES/ECB/PKCS5Padding - -mosip.kernel.partner.sign.masterkey.application.id=PMS - -mosip.kernel.keymanager.autogen.appids.list=ROOT,KERNEL:SIGN,PRE_REGISTRATION,REGISTRATION,REGISTRATION_PROCESSOR,ID_REPO,KERNEL:IDENTITY_CACHE - -zkcrypto.random.key.generate.count=10000 - -mosip.kernel.zkcrypto.generate.ida.publickey=true - -javax.persistence.jdbc.schema=keymgr - -mosip.kernel.keymanager.autogen.basekeys.list= \ No newline at end of file diff --git a/kernel/keys-generator/src/main/resources/bootstrap.properties b/kernel/keys-generator/src/main/resources/bootstrap.properties deleted file mode 100644 index e20820e9670..00000000000 --- a/kernel/keys-generator/src/main/resources/bootstrap.properties +++ /dev/null @@ -1,26 +0,0 @@ - -# Application name - the name appended at starting of file name to differentiate -# between different property files for different microservices -spring.application.name=keys-generator - -#Active Profile - will relate to development properties file in the server. -#If this property is absent then default profile will be activated which is -#the property file without any environment name at the end. -spring.profiles.active=dev - -# url where spring cloud config server is running -spring.cloud.config.uri=localhost - - -keymanager.persistence.jdbc.schema=keymgr - -#exposing refresh endpoint so that whenevr configuration changes in git, -#post /actuator/refresh endpoint can be called for the client microservices -#to update the configuration -management.endpoint.health.show-details=always -management.endpoints.web.exposure.include=info,health,refresh,restart - - -#disabling health check so that client doesnt try to load properties from sprint config server every -# 5 minutes (should not be done in production) -health.config.enabled=false \ No newline at end of file diff --git a/kernel/keys-migrator/Dockerfile b/kernel/keys-migrator/Dockerfile deleted file mode 100755 index 5dbcc90ede2..00000000000 --- a/kernel/keys-migrator/Dockerfile +++ /dev/null @@ -1,65 +0,0 @@ -FROM openjdk:11 -RUN apt-get update \ - && apt-get -y upgrade \ - && apt-get -y install unzip - -# can be passed during Docker build as build time environment for github branch to pickup configuration from. -ARG spring_config_label - -# can be passed during Docker build as build time environment for spring profiles active -ARG active_profile - -# can be passed during Docker build as build time environment for config server URL -ARG spring_config_url - -# can be passed during Docker build as build time environment for artifactory URL -ARG artifactory_url - -# can be passed during Docker build as build time environment for config server URL -ARG spring_config_name - -# can be passed during Docker build as build time environment for hsm client zip file path -ARG hsm_client_zip_path - -ARG hsm_local_dir=hsm-client - -ENV hsm_local_dir_name=${hsm_local_dir} - -# environment variable to pass active profile such as DEV, QA etc at docker runtime -ENV active_profile_env=${active_profile} - -# environment variable to pass github branch to pickup configuration from, at docker runtime -ENV spring_config_label_env=${spring_config_label} - -# environment variable to pass spring configuration url, at docker runtime -ENV spring_config_url_env=${spring_config_url} - -# environment variable to pass github branch to pickup configuration from, at docker runtime -ENV spring_config_name_env=${spring_config_name} - -# environment variable to pass artifactory url, at docker runtime -ENV artifactory_url_env=${artifactory_url} - -# environment variable to pass hsm client zip file path, at docker runtime -ENV hsm_zip_file_path=${hsm_client_zip_path} - -# creating folder to copy additional supporting jar files required at run-time. -#RUN mkdir /additional-jars - -ENV work_dir=/ - -ARG loader_path=${work_dir}/additional_jars/ - -RUN mkdir -p ${loader_path} - -ENV loader_path_env=${loader_path} - -ADD configure_start.sh configure_start.sh - -RUN chmod +x configure_start.sh - -ADD target/keys-migrator-*.jar keys-migrator.jar - -ENTRYPOINT [ "/configure_start.sh" ] - -CMD ["java","-jar", "-Dloader.path=${loader_path_env}", "-Dspring.cloud.config.label=${spring_config_label_env}","-Dspring.cloud.config.name=${spring_config_name_env}", "-Dspring.profiles.active=${active_profile_env}", "-Dspring.cloud.config.uri=${spring_config_url_env}", "/keys-migrator.jar"] \ No newline at end of file diff --git a/kernel/keys-migrator/configure_start.sh b/kernel/keys-migrator/configure_start.sh deleted file mode 100755 index 0cf5a80c775..00000000000 --- a/kernel/keys-migrator/configure_start.sh +++ /dev/null @@ -1,26 +0,0 @@ -#!/bin/bash - -#installs the pkcs11 libraries. -set -e - -DEFAULT_ZIP_PATH=artifactory/libs-release-local/hsm/client.zip -[ -z "$zip_file_path" ] && zip_path="$DEFAULT_ZIP_PATH" || zip_path="$zip_file_path" - -echo "Download the client from $artifactory_url_env" -echo "Zip File Path: $zip_path" - -FILE_NAME=${zip_path##*/} -DIR_NAME=${FILE_NAME%%.*} - -echo "File names is: $FILE_NAME \n" -echo "Directory name is: $DIR_NAME \n" - -wget "$artifactory_url_env/$zip_path" -echo "Downloaded $artifactory_url_env/$zip_path" - -unzip $FILE_NAME -echo "Attempting to install" -cd ./$DIR_NAME && ./install.sh -echo "Installation complete" - -exec "$@" \ No newline at end of file diff --git a/kernel/keys-migrator/pom.xml b/kernel/keys-migrator/pom.xml deleted file mode 100755 index d80dcd9a170..00000000000 --- a/kernel/keys-migrator/pom.xml +++ /dev/null @@ -1,97 +0,0 @@ - - 4.0.0 - - io.mosip.kernel - keys-migrator - 1.2.0-rc2-SNAPSHOT - - UTF-8 - - - 11 - 11 - 3.8.0 - 2.22.0 - - - 2.0.2.RELEASE - 2.0.7.RELEASE - 5.0.5.RELEASE - 2.0.4.RELEASE - 1.18.8 - 1.2.0-rc2-SNAPSHOT - - - - - org.projectlombok - lombok - ${lombok.version} - - - org.springframework.boot - spring-boot-starter-web - ${spring.boot.version} - - - org.springframework.boot - spring-boot-starter-data-jpa - ${spring.boot.version} - - - org.springframework.cloud - spring-cloud-starter-config - ${spring-cloud-config.version} - - - org.postgresql - postgresql - 42.2.1 - - - io.mosip.kernel - kernel-keymanager-service - ${kernel-keymanager-service.version} - - - org.springframework.security - spring-security-config - - - lib - - - org.javassist - javassist - 3.25.0-GA - - - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring.boot.version} - - true - ZIP - - - - - build-info - repackage - - - - - - - - - - Keys Migrator - Temporary to correct the certificates - - diff --git a/kernel/keys-migrator/src/main/java/io/mosip/kernel/migrate/MigrateBaseKeysApplication.java b/kernel/keys-migrator/src/main/java/io/mosip/kernel/migrate/MigrateBaseKeysApplication.java deleted file mode 100755 index 1ad92d907be..00000000000 --- a/kernel/keys-migrator/src/main/java/io/mosip/kernel/migrate/MigrateBaseKeysApplication.java +++ /dev/null @@ -1,44 +0,0 @@ -package io.mosip.kernel.migrate; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.CommandLineRunner; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.web.client.RestTemplate; - -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.migrate.impl.BaseKeysMigrator; -import io.mosip.kernel.keymanagerservice.logger.KeymanagerLogger; - -@SpringBootApplication(scanBasePackages = {"io.mosip.kernel.keygenerator.*", "io.mosip.kernel.keymanagerservice.*", - "io.mosip.kernel.keymanager.*", "io.mosip.kernel.crypto.*", "io.mosip.kernel.cryptomanager.*", - " io.mosip.kernel.migrate.*" }) - -public class MigrateBaseKeysApplication implements CommandLineRunner { - - private static final Logger LOGGER = KeymanagerLogger.getLogger(MigrateBaseKeysApplication.class); - - @Autowired - BaseKeysMigrator keysMigrator; - - @Bean - public RestTemplate restTemplate() { - return new RestTemplate(); - } - - - public static void main(String[] args) throws Exception { - ConfigurableApplicationContext run = SpringApplication.run(MigrateBaseKeysApplication.class, args); - SpringApplication.exit(run); - } - - @Override - public void run(String... args) throws Exception { - - LOGGER.info("Keys Migration started......" ); - keysMigrator.migrateKeys(); - LOGGER.info("Keys Migration Completed......" ); - } -} diff --git a/kernel/keys-migrator/src/main/java/io/mosip/kernel/migrate/impl/BaseKeysMigrator.java b/kernel/keys-migrator/src/main/java/io/mosip/kernel/migrate/impl/BaseKeysMigrator.java deleted file mode 100755 index f4f36f4bad3..00000000000 --- a/kernel/keys-migrator/src/main/java/io/mosip/kernel/migrate/impl/BaseKeysMigrator.java +++ /dev/null @@ -1,413 +0,0 @@ -package io.mosip.kernel.migrate.impl; - -import java.io.IOException; -import java.security.InvalidKeyException; -import java.security.Key; -import java.security.KeyFactory; -import java.security.KeyStore.PrivateKeyEntry; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.cert.X509Certificate; -import java.security.spec.PKCS8EncodedKeySpec; -import java.util.ArrayList; -import java.util.Base64; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import javax.annotation.PostConstruct; -import javax.crypto.BadPaddingException; -import javax.crypto.Cipher; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; -import javax.crypto.SecretKey; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ObjectNode; -import com.google.common.net.HttpHeaders; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.ParameterizedTypeReference; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpRequest; -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.util.UriComponentsBuilder; - -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.crypto.spi.CryptoCoreSpec; -import io.mosip.kernel.core.http.RequestWrapper; -import io.mosip.kernel.core.http.ResponseWrapper; -import io.mosip.kernel.core.keymanager.spi.KeyStore; -import io.mosip.kernel.core.util.CryptoUtil; -import io.mosip.kernel.cryptomanager.util.CryptomanagerUtils; -import io.mosip.kernel.keymanagerservice.constant.KeymanagerConstant; -import io.mosip.kernel.keymanagerservice.entity.DataEncryptKeystore; -import io.mosip.kernel.keymanagerservice.entity.KeyAlias; -import io.mosip.kernel.keymanagerservice.logger.KeymanagerLogger; -import io.mosip.kernel.keymanagerservice.repository.DataEncryptKeystoreRepository; -import io.mosip.kernel.keymanagerservice.repository.KeyAliasRepository; -import io.mosip.kernel.keymanagerservice.repository.KeyStoreRepository; -import io.mosip.kernel.keymanagerservice.service.KeymanagerService; -import io.mosip.kernel.keymanagerservice.util.KeymanagerUtil; -import io.mosip.kernel.keymigrate.dto.KeyMigrateBaseKeyRequestDto; -import io.mosip.kernel.keymigrate.dto.KeyMigrateBaseKeyResponseDto; -import io.mosip.kernel.keymigrate.dto.ZKKeyDataDto; -import io.mosip.kernel.keymigrate.dto.ZKKeyMigrateRequestDto; -import io.mosip.kernel.keymigrate.dto.ZKKeyMigrateResponseDto; -import io.mosip.kernel.keymigrate.dto.ZKKeyResponseDto; -/** - * The Class BaseKeysMigrator. - * - * @author Mahammed Taheer - */ -@Component -public class BaseKeysMigrator { - - private static final Logger LOGGER = KeymanagerLogger.getLogger(BaseKeysMigrator.class); - - private static final String ROOT_APP_ID = "ROOT"; - - private static final String BLANK_REF_ID = ""; - - private static final String KERNEL_APP_ID = "KERNEL"; - - private static final String IDENTITY_CACHE_REF_ID = "IDENTITY_CACHE"; - - private static final String PARTNER_APP_ID = "PARTNER"; - - @Value("${mosip.kernel.keymanager.autogen.appids.list}") - private String appIdsList; - - @Value("${mosip.kernel.keymanager.keymigration.auth.url}") - private String authTokenUrl; - - @Value("${mosip.kernel.keymanager.keymigration.auth.appId}") - private String authAppId; - - @Value("${mosip.kernel.keymanager.keymigration.auth.cliendId}") - private String clientId; - - @Value("${mosip.kernel.keymanager.keymigration.auth.secretKey}") - private String secretKey; - - @Value("${mosip.kernel.keymanager.keymigration.getcertificate.url}") - private String getCertifcateUrl; - - @Value("${mosip.kernel.keymanager.keymigration.uploadkey.url}") - private String uploadKeyUrl; - - @Value("${mosip.kernel.keymanager.keymigration.getzktempcertificate.url}") - private String getZKTempCertifcateUrl; - - @Value("${mosip.kernel.zkcrypto.wrap.algorithm-name}") - private String aesECBTransformation; - - @Value("${mosip.kernel.keymanager.keymigration.zkkeys.migration.batch.size}") - private int uploadBatchSize; - - @Value("${mosip.kernel.keymanager.keymigration.zkUploadkey.url}") - private String zkUploadKeyUrl; - - @Autowired - private ObjectMapper mapper; - - @Autowired - private KeyAliasRepository keyAliasRepository; - - @Autowired - KeymanagerService keymanagerService; - - @Autowired - private RestTemplate restTemplate; - - /** - * Keystore instance to handles and store cryptographic keys. - */ - @Autowired - private KeyStore keyStore; - - @Autowired - KeymanagerUtil keymanagerUtil; - - /** - * {@link KeyStoreRepository} instance - */ - @Autowired - KeyStoreRepository keyStoreRepository; - - @Autowired - DataEncryptKeystoreRepository dataEncryptKeystoreRepository; - - /** - * {@link CryptomanagerUtils} instance - */ - @Autowired - CryptomanagerUtils cryptomanagerUtil; - - - @Autowired - private CryptoCoreSpec cryptoCore; - - String token = ""; - - @SuppressWarnings("rawtypes") - @PostConstruct - public void generateToken() { - RequestWrapper requestWrapper = new RequestWrapper<>(); - ObjectNode request = mapper.createObjectNode(); - request.put("appId", authAppId); - request.put("clientId", clientId); - request.put("secretKey", secretKey); - requestWrapper.setRequest(request); - ResponseEntity response = restTemplate.postForEntity(authTokenUrl, requestWrapper, - ResponseWrapper.class); - token = response.getHeaders().getFirst("authorization"); - restTemplate.setInterceptors(Collections.singletonList(new ClientHttpRequestInterceptor() { - - @Override - public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) - throws IOException { - request.getHeaders().add(HttpHeaders.COOKIE, "Authorization=" + token); - return execution.execute(request, body); - } - })); - } - - public void migrateKeys() throws Exception { - LOGGER.info("Starting Key Manager Generated Base Keys Migration..."); - migrateKeyMgrKeys(); - LOGGER.info("Completed Key Manager Generated Base Keys Migration..."); - - LOGGER.info("Starting Partner uploaded Certificates Migration..."); - migratePartnerKeys(); - LOGGER.info("Completed Partner uploaded Certificates Migration..."); - - LOGGER.info("Starting ZK Random Keys Migration..."); - migrateZKRandomKeys(); - LOGGER.info("Completed ZK Random Keys Migration..."); - } - - private void migrateKeyMgrKeys() { - List masterKeysList = getMasterKeysList(); - masterKeysList.forEach(masterKeyAppId -> { - if (!masterKeyAppId.equals("KERNEL:IDENTITY_CACHE")) { - LOGGER.info("Started Migration for AppId: " + masterKeyAppId); - List masterKeyAlias = getKeyAlias(masterKeyAppId, BLANK_REF_ID); - masterKeyAlias.forEach(masterKeyUuidObj -> { - String masterKeyUuid = masterKeyUuidObj.getAlias(); - List baseKeys = getBaseKeysList(masterKeyUuid); - if (Objects.isNull(baseKeys) || baseKeys.size() == 0){ - LOGGER.info("Base Keys is null or Size Zero. AppId: " + masterKeyAppId + ", Uuid: " + masterKeyUuid); - } else { - LOGGER.info("Total Number of Base Keys found: " + baseKeys.size() + ", AppId: " + masterKeyAppId - + ", Uuid: " + masterKeyUuid); - PrivateKeyEntry masterKeyEntry = null; - try { - masterKeyEntry = keyStore.getAsymmetricKey(masterKeyUuid); - } catch (Exception exp ){ - LOGGER.error("Error Getting the Master Key from KeyStore. APP Id: " + masterKeyAppId); - } - if (masterKeyEntry == null) { - LOGGER.error("Error Getting the Master Key from KeyStore. Continuing with other key. Uuid: " + masterKeyUuid); - } else { - reEncryptAndUpload(masterKeyEntry, masterKeyAppId, baseKeys); - } - } - }); - } - }); - } - - private void reEncryptAndUpload(PrivateKeyEntry masterKeyEntry, String masterKeyAppId, - List baseKeys) { - PrivateKey masterKey = masterKeyEntry.getPrivateKey(); - PublicKey masterPublicKey = masterKeyEntry.getCertificate().getPublicKey(); - X509Certificate newKeyMgrCert = getMasterCertificate(masterKeyAppId); - PublicKey newKeyMgrPubKey = newKeyMgrCert.getPublicKey(); - baseKeys.forEach(baseKey -> { - String baseKeyUuid = baseKey.getAlias(); - LOGGER.info("Base Key Found for Master ID: " + masterKeyAppId + " & baseKeyUuid: " + baseKeyUuid); - try { - byte[] decryptedPrivateKey = keymanagerUtil.decryptKey(CryptoUtil.decodeBase64(baseKey.getPrivateKey()), - masterKey, masterPublicKey); - KeyFactory keyFactory = KeyFactory.getInstance(KeymanagerConstant.RSA); - PrivateKey privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(decryptedPrivateKey)); - String encryptedPrivateKey = CryptoUtil.encodeBase64(keymanagerUtil.encryptKey(privateKey, newKeyMgrPubKey)); - Optional keyAliasObj = keyAliasRepository.findById(baseKeyUuid); - uploadKeyToNewKeyMgr(keyAliasObj, encryptedPrivateKey, baseKey.getCertificateData()); - } catch (Exception e) { - LOGGER.error("Error Re-Encrypting the Base key." + e.getMessage()); - e.printStackTrace(); - } - }); - } - - private void migratePartnerKeys() { - List partnerKeyAlias = getPartnerKeyAlias(PARTNER_APP_ID); - partnerKeyAlias.forEach(partnerKeyObj -> { - String partnerKeyUuid = partnerKeyObj.getAlias(); - String refId = partnerKeyObj.getReferenceId(); - List partnerKeys = getBaseKeysList(partnerKeyUuid); - if (Objects.isNull(partnerKeys) || partnerKeys.size() == 0){ - LOGGER.info("Partner Keys is null or Size Zero. AppId: " + PARTNER_APP_ID + ", RefId: " + refId); - } else { - LOGGER.info("Total Number of Partner Keys found: " + partnerKeys.size() + ", AppId: " + PARTNER_APP_ID - + ", RefId: " + refId); - String noPrivateKey = partnerKeys.get(0).getPrivateKey(); - String certData = partnerKeys.get(0).getCertificateData(); - uploadKeyToNewKeyMgr(Optional.of(partnerKeyObj), noPrivateKey, certData); - } - }); - } - - private void uploadKeyToNewKeyMgr(Optional keyAliasObj, String encryptedPrivateKey, String certData) { - - KeyMigrateBaseKeyRequestDto reqDto = new KeyMigrateBaseKeyRequestDto(); - KeyAlias keyAlias = keyAliasObj.get(); - reqDto.setApplicationId(keyAlias.getApplicationId()); - reqDto.setReferenceId(keyAlias.getReferenceId()); - reqDto.setEncryptedKeyData(encryptedPrivateKey); - reqDto.setCertificateData(certData); - reqDto.setNotBefore(keyAlias.getKeyGenerationTime()); - reqDto.setNotAfter(keyAlias.getKeyExpiryTime()); - - RequestWrapper requestWrapper = new RequestWrapper<>(); - requestWrapper.setRequest(reqDto); - - ResponseEntity> response = restTemplate.exchange(uploadKeyUrl, - HttpMethod.POST, new HttpEntity<>(requestWrapper), - new ParameterizedTypeReference>() { - }); - LOGGER.info("Upload Response: " + response.getBody().getResponse().getStatus()); - LOGGER.info("Upload Base Key Completed. AppId: " + keyAlias.getApplicationId() + ", RefId: " + keyAlias.getReferenceId()); - } - - private List getMasterKeysList() { - return Stream.of(appIdsList.split(",")).map(String::trim) - .filter(appId -> !appId.equalsIgnoreCase(ROOT_APP_ID)) - .collect(Collectors.toList()); - } - - @SuppressWarnings({"rawtypes", "unchecked"}) - private X509Certificate getMasterCertificate(String appId) { - Map uriParams = new HashMap<>(); - UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(getCertifcateUrl) - .queryParam("applicationId", appId) - .queryParam("referenceId", BLANK_REF_ID); - - ResponseEntity response = restTemplate.exchange(builder.build(uriParams), HttpMethod.GET, null, Map.class); - String certificate = (String) ((Map) response.getBody().get("response")).get("certificate"); - return (X509Certificate) keymanagerUtil.convertToCertificate(certificate); - } - - private List getKeyAlias(String applicationId, String referenceId) { - List keyAliases = keyAliasRepository.findByApplicationIdAndReferenceId(applicationId, referenceId) - .stream().sorted((alias1, alias2) -> { - return alias1.getKeyGenerationTime().compareTo(alias2.getKeyGenerationTime()); - }).collect(Collectors.toList()); - return keyAliases; - } - - private List getPartnerKeyAlias(String applicationId) { - List keyAliases = keyAliasRepository.findByApplicationId(applicationId) - .stream().sorted((alias1, alias2) -> { - return alias1.getKeyGenerationTime().compareTo(alias2.getKeyGenerationTime()); - }).collect(Collectors.toList()); - return keyAliases; - } - - private List getBaseKeysList(String masterKeyAppId) { - List baseKeysList = keyStoreRepository.findByMasterAlias(masterKeyAppId); - return baseKeysList; - } - - private void migrateZKRandomKeys() { - List zkRandomKeys = dataEncryptKeystoreRepository.findAll(); - X509Certificate zkTempCertificate = getZKTempCertificate(); - PublicKey zkPublicKey = zkTempCertificate.getPublicKey(); - List masterKeyAlias = keyAliasRepository.findByApplicationIdAndReferenceId(KERNEL_APP_ID, IDENTITY_CACHE_REF_ID); - String zkMasterKeyAlias = masterKeyAlias.get(0).getAlias(); - Key zkMasterKey = keyStore.getSymmetricKey(zkMasterKeyAlias); - - List keyDataDtoList = new ArrayList<>(); - zkRandomKeys.forEach(zkKey -> { - int keyIndex = zkKey.getId(); - String encryptedKey = zkKey.getKey(); - byte[] decryptedZKKey = decryptRandomKey(encryptedKey, zkMasterKey); - byte[] encryptedRandomKey = cryptoCore.asymmetricEncrypt(zkPublicKey, decryptedZKKey); - String encodedKey = CryptoUtil.encodeBase64(encryptedRandomKey); - ZKKeyDataDto keyDataDto = new ZKKeyDataDto(); - keyDataDto.setKeyIndex(keyIndex); - keyDataDto.setEncryptedKeyData(encodedKey); - keyDataDtoList.add(keyDataDto); - int listSize = keyDataDtoList.size(); - if (listSize != 1 && (listSize % uploadBatchSize == 0)) { - LOGGER.info("Uploading Key List: " + listSize); - uploadZKKeyToNewKeyMgr(keyDataDtoList, false); - keyDataDtoList.clear(); - LOGGER.info("Total Completed Uploaded: " + keyIndex); - } - }); - int listSize = keyDataDtoList.size(); - LOGGER.info("Uploading Key List(final): " + listSize); - uploadZKKeyToNewKeyMgr(keyDataDtoList, true); - } - - @SuppressWarnings({"rawtypes", "unchecked"}) - private X509Certificate getZKTempCertificate() { - Map uriParams = new HashMap<>(); - UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(getZKTempCertifcateUrl); - - ResponseEntity response = restTemplate.exchange(builder.build(uriParams), HttpMethod.GET, null, Map.class); - String certificate = (String) ((Map) response.getBody().get("response")).get("certificate"); - return (X509Certificate) keymanagerUtil.convertToCertificate(certificate); - } - - private byte[] decryptRandomKey(String secretData, Key zkMasterKey) { - try { - byte[] secretDataBytes = Base64.getDecoder().decode(secretData); - Cipher cipher = Cipher.getInstance(aesECBTransformation); - - cipher.init(Cipher.DECRYPT_MODE, zkMasterKey); - return cipher.doFinal(secretDataBytes, 0, secretDataBytes.length); - } catch(NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException - | IllegalBlockSizeException | BadPaddingException | IllegalArgumentException e) { - LOGGER.error("Error Decrypting ZK Key." + e.getMessage()); - } - return null; - } - - private void uploadZKKeyToNewKeyMgr(List keyDataDtoList, boolean purgeKeyFlag) { - - ZKKeyMigrateRequestDto reqDto = new ZKKeyMigrateRequestDto(); - reqDto.setPurgeTempKeyFlag(purgeKeyFlag); - reqDto.setZkEncryptedDataList(keyDataDtoList); - - RequestWrapper requestWrapper = new RequestWrapper<>(); - requestWrapper.setRequest(reqDto); - - ResponseEntity> response = restTemplate.exchange(zkUploadKeyUrl, - HttpMethod.POST, new HttpEntity<>(requestWrapper), - new ParameterizedTypeReference>() { - }); - List responseDtoList = response.getBody().getResponse().getZkEncryptedDataList(); - - LOGGER.info("Upload Response Key Size: " + responseDtoList.size()); - for (ZKKeyResponseDto keyDto : responseDtoList) { - LOGGER.info("Upload KeyIndex: " + keyDto.getKeyIndex() + ", Status: " + keyDto.getStatusMessage()); - } - } -} diff --git a/kernel/keys-migrator/src/main/resources/application-local.properties b/kernel/keys-migrator/src/main/resources/application-local.properties deleted file mode 100755 index 5561a179c83..00000000000 --- a/kernel/keys-migrator/src/main/resources/application-local.properties +++ /dev/null @@ -1,139 +0,0 @@ -#mosip.kernel.keymanager.softhsm.config-path=/config/softhsm-application.conf - - -mosip.kernel.keymanager.hsm.keystore-type=PKCS11 - -mosip.kernel.keymanager.hsm.config-path=/opt/taheer-mos/hsm-test/hsm-files/pkcs11-softhsm.cfg -#mosip.kernel.keymanager.hsm.config-path=/hsm-files/pkcs/mosip-ks.p12 -mosip.kernel.keymanager.hsm.keystore-pass= - -mosip.kernel.keymanager.certificate.default.common-name=www.mosip.io -mosip.kernel.keymanager.certificate.default.organizational-unit=IIITB -mosip.kernel.keymanager.certificate.default.organization=mosip -mosip.kernel.keymanager.certificate.default.location=BANGALORE -mosip.kernel.keymanager.certificate.default.state=KA -mosip.kernel.keymanager.certificate.default.country=IN - -mosip.kernel.keymanager.softhsm.certificate.common-name=www.mosip.io -mosip.kernel.keymanager.softhsm.certificate.organizational-unit=MOSIP -mosip.kernel.keymanager.softhsm.certificate.organization=IITB -mosip.kernel.keymanager.softhsm.certificate.country=IN - -#----------------------- Crypto -------------------------------------------------- -#Crypto asymmetric algorithm name -mosip.kernel.crypto.asymmetric-algorithm-name=RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING -#Crypto symmetric algorithm name -mosip.kernel.crypto.symmetric-algorithm-name=AES/GCM/PKCS5Padding -#Keygenerator asymmetric algorithm name -mosip.kernel.keygenerator.asymmetric-algorithm-name=RSA -#Keygenerator symmetric algorithm name -mosip.kernel.keygenerator.symmetric-algorithm-name=AES -#Asymmetric algorithm key length -mosip.kernel.keygenerator.asymmetric-key-length=2048 -#Symmetric algorithm key length -mosip.kernel.keygenerator.symmetric-key-length=256 - -#Encrypted data and encrypted symmetric key separator -mosip.kernel.data-key-splitter=#KEY_SPLITTER# -#GCM tag length -mosip.kernel.crypto.gcm-tag-length=128 -#Hash algo name -mosip.kernel.crypto.hash-algorithm-name=PBKDF2WithHmacSHA512 -#Symmtric key length used in hash -mosip.kernel.crypto.hash-symmetric-key-length=256 -#No of iterations in hash -mosip.kernel.crypto.hash-iteration=10 -#Sign algo name -mosip.kernel.crypto.sign-algorithm-name=RS256 -#Certificate Sign algo name -mosip.kernel.certificate.sign.algorithm=SHA256withRSA - - -keymanager.persistence.jdbc.driver=org.postgresql.Driver -keymanager_database_url=jdbc:postgresql://localhost:5432/mosip_keymgr -keymanager_database_username=mosip-db -keymanager_database_password= - - -hibernate.hbm2ddl.auto=none -hibernate.dialect=org.hibernate.dialect.PostgreSQL95Dialect -hibernate.jdbc.lob.non_contextual_creation=true -hibernate.show_sql=false -hibernate.format_sql=false -hibernate.connection.charSet=utf8 -hibernate.cache.use_second_level_cache=false -hibernate.cache.use_query_cache=false -hibernate.cache.use_structured_entries=false -hibernate.generate_statistics=false -hibernate.current_session_context_class=org.springframework.orm.hibernate5.SpringSessionContext - -auth.server.validate.url=http://localhost:8091/v1/authmanager/authorize/admin/validateToken -auth.server.admin.validate.url=http://localhost:8091/v1/authmanager/authorize/admin/validateToken -auth.role.prefix=ROLE_ -auth.header.name=Authorization - -#mosip.kernel.pdf_owner_password=PDFADMIN -#------ -mosip.kernel.signature.signature-request-id=SIGNATURE.REQUEST -mosip.kernel.signature.signature-version-id=v1.0 - -mosip.root.key.applicationid=ROOT -mosip.sign.applicationid=KERNEL -mosip.sign.refid=SIGN -mosip.sign-certificate-refid=SIGN -mosip.signed.header=response-signature - - -#--- - -mosip.kernel.tokenid.uin.salt=zHuDEAbmbxiUbUShgy6pwUhKh9DE0EZn9kQDKPPKbWscGajMwf -mosip.kernel.tokenid.partnercode.salt=yS8w5Wb6vhIKdf1msi4LYTJks7mqkbmITk2O63Iq8h0bkRlD0d -mosip.kernel.tokenid.length=36 - -#--- -#Length of license key to be generated. -mosip.kernel.licensekey.length=16 -#List of permissions -# NOTE: ',' in the below list is used as splitter in the implementation. -# Use of ',' in the values for below key should be avoided. -# Use of spaces before and after ',' also should be avoided. -mosip.kernel.licensekey.permissions=OTP Trigger,OTP Authentication,Demo Authentication - Identity Data Match,Demo Authentication - Address Data Match,Demo Authentication - Full Address Data Match,Demo Authentication - Secondary Language Match,Biometric Authentication - FMR Data Match,Biometric Authentication - IIR Data Match,Biometric Authentication - FID Data Match,Static Pin Authentication,eKYC - limited,eKYC - Full,eKYC - No - -mosip.kernel.zkcrypto.masterkey.application.id=KERNEL -mosip.kernel.zkcrypto.masterkey.reference.id=IDENTITY_CACHE -mosip.kernel.zkcrypto.publickey.application.id=IDA -mosip.kernel.zkcrypto.publickey.reference.id=PUBLIC_KEY -mosip.kernel.zkcrypto.wrap.algorithm-name=AES/ECB/NoPadding -mosip.kernel.zkcrypto.derive.encrypt.algorithm-name=AES/ECB/PKCS5Padding - -mosip.kernel.partner.sign.masterkey.application.id=PMS - -mosip.kernel.partner.allowed.domains=AUTH,DEVICE,FTM - -mosip.iam.impl.basepackage=io.mosip.kernel.auth.defaultimpl -mosip.auth.adapter.impl.basepackage=io.mosip.kernel.auth.defaultadapter - -mosip.kernel.keymanager.hsm.jce.className=io.mosip.keymanager.hsm.impl.HSMKeyStoreImpl -mosip.kernel.keymanager.hsm.jce.keyStoreType=CloudHSM -mosip.kernel.keymanager.hsm.jce.keyStoreFile= -mosip.kernel.keymanager.hsm.jce.localKeyStorePwd= -mosip.kernel.keymanager.hsm.jce.partitionName=PARTITION_01 -mosip.kernel.keymanager.hsm.jce.cuUserName=keyusr -mosip.kernel.keymanager.hsm.jce.cuPassword= - - -mosip.kernel.keymanager.113nothumbprint.support=false - -mosip.kernel.keymanager.autogen.appids.list=ROOT,KERNEL:SIGN,PRE_REGISTRATION,REGISTRATION,REGISTRATION_PROCESSOR,ID_REPO,KERNEL:IDENTITY_CACHE,RESIDENT,PMS - - -mosip.kernel.keymanager.keymigration.auth.url=http://localhost:8091/v1/authmanager/authenticate/clientidsecretkey -mosip.kernel.keymanager.keymigration.auth.appId= -mosip.kernel.keymanager.keymigration.auth.cliendId= -mosip.kernel.keymanager.keymigration.auth.secretKey= - -mosip.kernel.keymanager.keymigration.getcertificate.url=http://localhost:8088/v1/keymanager/getCertificate -mosip.kernel.keymanager.keymigration.uploadkey.url=http://localhost:8088/v1/keymanager/migrateBaseKey -mosip.kernel.keymanager.keymigration.getzktempcertificate.url=http://localhost:8088/v1/keymanager/getZKTempCertificate -mosip.kernel.keymanager.keymigration.zkkeys.migration.batch.size=500 -mosip.kernel.keymanager.keymigration.zkUploadkey.url=http://localhost:8088/v1/keymanager/migrateZKKeys \ No newline at end of file diff --git a/kernel/keys-migrator/src/main/resources/bootstrap.properties b/kernel/keys-migrator/src/main/resources/bootstrap.properties deleted file mode 100755 index 060fd74fe04..00000000000 --- a/kernel/keys-migrator/src/main/resources/bootstrap.properties +++ /dev/null @@ -1,26 +0,0 @@ - -# Application name - the name appended at starting of file name to differentiate -# between different property files for different microservices -spring.application.name=keys-generator - -#Active Profile - will relate to development properties file in the server. -#If this property is absent then default profile will be activated which is -#the property file without any environment name at the end. -spring.profiles.active=local - -# url where spring cloud config server is running -spring.cloud.config.uri=localhost - - -keymanager.persistence.jdbc.schema=keymgr - -#exposing refresh endpoint so that whenevr configuration changes in git, -#post /actuator/refresh endpoint can be called for the client microservices -#to update the configuration -management.endpoint.health.show-details=always -management.endpoints.web.exposure.include=info,health,refresh,restart - - -#disabling health check so that client doesnt try to load properties from sprint config server every -# 5 minutes (should not be done in production) -health.config.enabled=false \ No newline at end of file