package com.example.util import com.amazonaws.regions.Regions import com.amazonaws.services.kms.model.DecryptRequest import com.amazonaws.services.kms.AWSKMSClientBuilder; import com.amazonaws.services.kms.model.EncryptRequest; import java.nio.ByteBuffer import java.nio.charset.StandardCharsets import java.util.* class CryptoHandler { private val kmsClient = AWSKMSClientBuilder .standard() .withRegion(Regions.US_EAST_1) .build(); fun encrypt(data: String, tenantUUID: String): String? { val plaintext: ByteBuffer = ByteBuffer.wrap(data.toByteArray()) // Substitute Key ID or Key Alias or Key ARN, when using Key Alias, prefix it with "alias/" val req: EncryptRequest = EncryptRequest().withKeyId("").withPlaintext(plaintext) val ciphertext: ByteBuffer = kmsClient.encrypt(req).getCiphertextBlob() val base64EncodedValue: ByteArray = Base64.getEncoder().encode(ciphertext.array()) val value = String(base64EncodedValue, StandardCharsets.UTF_8) return value } fun decrypt(encryptedData: String?, tenantUUID: String): String? { val base64DecodedData: ByteBuffer = ByteBuffer.wrap(Base64.getDecoder().decode(encryptedData)) // Substitute Key ID or Key Alias or Key ARN, when using Key Alias, prefix it with "alias/" val decryptRequest = DecryptRequest().withKeyId("").withCiphertextBlob(base64DecodedData) val decryptResponse = kmsClient.decrypt(decryptRequest) return String(decryptResponse.plaintext.array(), StandardCharsets.UTF_8) } }