Untitled
unknown
plain_text
a month ago
2.8 kB
3
Indexable
Never
package com.kmbl.offercreation.config; import java.net.URI; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.kms.KmsClient; @Configuration public class KmsConfig { @Value("${amazon.kms.endpoint}") private String amazonKmsEndpoint; @Value("${amazon.kms.region}") private String awsRegion; @Bean public KmsClient getKmsClient() { return KmsClient.builder() .region(Region.of(awsRegion)) .endpointOverride(URI.create(amazonKmsEndpoint)) .credentialsProvider(DefaultCredentialsProvider.create()) .build(); } } package com.kmbl.offercreation.helper; import java.nio.ByteBuffer; import java.util.Base64; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import jakarta.annotation.PostConstruct; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.services.kms.KmsClient; import software.amazon.awssdk.services.kms.model.EncryptRequest; import software.amazon.awssdk.services.kms.model.EncryptResponse; @Component public class KmsHelper { @Autowired public KmsClient kmsClient; @Autowired private Map<String, String> secretsMap; private String amazonKmsKeyId; @PostConstruct public void loadAwsSecrets() { this.amazonKmsKeyId = secretsMap.get("amazon_kms_key_id"); } public String encryptData(String dataToEncrypt) { if(dataToEncrypt.isEmpty()) return ""; EncryptRequest encryptRequest = EncryptRequest.builder().keyId(amazonKmsKeyId) .plaintext(SdkBytes.fromByteBuffer(ByteBuffer.wrap(dataToEncrypt.getBytes()))).build(); EncryptResponse encryptResponse = kmsClient.encrypt(encryptRequest); SdkBytes encryptedData = encryptResponse.ciphertextBlob(); return Base64.getEncoder().encodeToString(encryptedData.asByteArray()); } public String decryptData(String dataToDecrypt) { if (Objects.isNull(dataToDecrypt) || dataToDecrypt.isEmpty()) return ""; SdkBytes alreadyEncryptedData = SdkBytes .fromByteBuffer(ByteBuffer.wrap(Base64.getDecoder().decode(dataToDecrypt))); DecryptRequest decryptRequest = DecryptRequest.builder().ciphertextBlob(alreadyEncryptedData).build(); DecryptResponse decryptResponse = kmsClient.decrypt(decryptRequest); SdkBytes decryptedSdkBytes = decryptResponse.plaintext(); return new String(decryptedSdkBytes.asByteArray(), StandardCharsets.UTF_8); } }
Leave a Comment