Skip to content

Instantly share code, notes, and snippets.

@faheemsharif-me
Created August 23, 2022 03:47
Show Gist options
  • Select an option

  • Save faheemsharif-me/766af2c04218715aceb5d771a9d494f9 to your computer and use it in GitHub Desktop.

Select an option

Save faheemsharif-me/766af2c04218715aceb5d771a9d494f9 to your computer and use it in GitHub Desktop.
KMS Encryption/Decryption - Encryption and Decryption of KMS using Kotlin
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("<place_key_id_here>").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("<place_key_id_here>").withCiphertextBlob(base64DecodedData)
val decryptResponse = kmsClient.decrypt(decryptRequest)
return String(decryptResponse.plaintext.array(), StandardCharsets.UTF_8)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment