Search code examples
javascalaamazon-web-servicesencryptionamazon-kms

How to decrypt AWS KMS cipher with AWS Encryption SDK with Java or AWSKmsClient


I want to use AWSKmsClient or AWS Encryption SDK with Java to decrypt the message I have encrypted using AWS CLI

I have created an encrypted message using:
aws kms encrypt --key-id 123421-4032-412c-4321-eds42d1a1b432 --plaintext MyText --output text --query CiphertextBlob
It generates something like this for me: ADCCAHhJotXoy8910T/Pd8PXVaF/Xkg+9NrF9QTy/XlW7rTtUAH6zACj9MbEY1cS7526GfscAAAAZjBkBgkqhkiG9w0BBwagVzBVAgEAMFAGCSqGSIb3DQEHATAeBglghkgBZDEEAS4wEQQMGmYHb67SV66h/eE0AgEQgCONMNda4kVsSi9sPAXXts2F0N/mwjSlIB2ngJcAyxymnltrHQ==

I want to pass this to my scala-spark code and decrypt it either with AWSKmsClient or AWS Encryption SDK with Java.

Based on this link it seems there some difference between AWS Encryption SDK and AWS KMS :

The AWS Encryption SDK for Java is not meant to be compatible with the aws kms command line tool. In short, the AWS Encryption SDK leverages KMS to provide more versatile encryption functionality than KMS alone

I can not manage to do it with AWSKmsClient either, am I missing something? is there a better way to achieve this?


Solution

  • I have managed to use AWSKMSClient

    import java.nio.charset.StandardCharsets
    
    import com.amazonaws.services.kms.{AWSKMS, AWSKMSClientBuilder}
    import com.amazonaws.services.kms.model.DecryptRequest
    import java.nio.ByteBuffer
    import com.google.common.io.BaseEncoding
    
    object KMSUtils {
    
      val keyId = "arn:aws:kms:us-east-1:{Account ID}:key/{KEY ID}"
    
      def decrypt(base64EncodedValue: String): String = {
        val kmsClient: AWSKMS = AWSKMSClientBuilder.standard.build
    
        val textDecoded: ByteBuffer = ByteBuffer.wrap(BaseEncoding.base64().decode(base64EncodedValue))
    
        val req : DecryptRequest = new DecryptRequest().withCiphertextBlob(textDecoded)
        val plainText : ByteBuffer = kmsClient.decrypt(req).getPlaintext
    
        val printable = StandardCharsets.UTF_8.decode(plainText).toString
    
        return printable
      }
    
    }