Search code examples
amazon-web-servicesencryptionutf-8amazon-kms

Encrypt value using AWS KMS - Can I have encrypted value in UTF8?


I can successfully encrypt the value using the following code:

    final static Charset ENCODING = StandardCharsets.ISO_8859_1;

    var awsCreds = AwsBasicCredentials.create(KEY, SECRET_KEY);
    kmsClient = KmsClient.builder().credentialsProvider(StaticCredentialsProvider.create(awsCreds)).region(Region.US_EAST_1).build();

    var sdkBytesString = SdkBytes.fromString(stringToEncrypt, ENCODING);
    var encryptRequest = EncryptRequest.builder().keyId(KEY_ARN).plaintext(sdkBytesString).build();

    var encryptResponse = this.kmsClient.encrypt(encryptRequest);

    var result = encryptResponse.ciphertextBlob().asString(ENCODING);

In the result I can see encrypted value.

BUT The problem is that I need this value in UTF8 not ISO_8859_1. When trying to get ciphertextBlob in UTF8 - getting conversion error:

Blockquote java.io.UncheckedIOException: Cannot encode string.

I need to save the string in UTF-8 DB and to send this encrypted string to another service that accepts UTF-8 strings\

Could you please advise how to get UTF-8 string after encryption?


Solution

  • Actually Base64 encrypting solves the problem:

    https://github.com/amazon-archives/realworld-serverless-application/blob/master/backend/src/main/java/software/amazon/serverless/apprepo/api/impl/pagination/EncryptedTokenSerializer.java#L51