Sample code for 30+ languages & platforms
B4X Requires Chilkat v11.6.0+

AWS KMS: ReEncrypt Between Keys and Encryption Contexts

See more AWS KMS Examples

Uses the current AWS KMS API. Configure the region and keep credentials in private qa_data/aws/kms.json, with nonempty string fields access_key and secret_key. The examples do not obtain or refresh credentials. Keep diagnostics private; they may contain credentials or sensitive key data. Create the output directory before running file-writing examples.

Uses the AWS JSON 1.1 protocol with TrentService targets, service kms, HTTPS certificate verification, and Signature Version 4. When using temporary credentials, also provide a nonempty session_token; this Rest example includes it in the signed query on each request. Never log that URL. The endpoint shown is for the commercial AWS partition; use the appropriate endpoint for other partitions. Failures stop the sample; production retry policies should use bounded backoff with jitter and reconcile uncertain writes.

Where a key is required, set string key_id to its fixed key ARN in the configured region. Additional named fields and input files are described below. Keep output files private when they contain plaintext or policies. The code does not automatically retry mutations, refresh credentials, or create output directories. A successful request can precede propagation of a state change. Discard sensitive objects promptly; clearing one buffer does not erase copies held in strings, JSON, or runtime memory.

Uses a symmetric ENCRYPT_DECRYPT key and the case-sensitive context Application=ChilkatKmsExamples. Context is visible metadata, not a place for secrets. AWS must receive the exact same context on decryption. The sample handles binary data; UTF-8 text can be stored in the same input file. Direct symmetric Encrypt accepts up to 4096 bytes; larger data should use envelope encryption.

Set destination_key_id to another symmetric key ARN. ReEncrypt changes the context to Application=ChilkatKmsExamplesV2 without returning plaintext. Decrypt the new blob with the destination ARN and new context. Authorization uses kms:ReEncryptFrom on the source and kms:ReEncryptTo on the destination.

API actions used: kms:ReEncrypt. IAM permissions and key policies must allow the actual resources; grant and multi-Region workflows can need permissions in more than one region/account.

ReEncrypt

Chilkat B4X Downloads

B4X
Dim success As Boolean = False

Dim stringCompare As ChilkatStringBuilder
stringCompare.Initialize
'  Assumes Chilkat is unlocked. See Global Unlock Sample.
'  Keep this credentials file outside public web content and source control.
Dim credentials As ChilkatJsonObject
credentials.Initialize
credentials.Strict = True
success = credentials.LoadFile("qa_data/aws/kms.json")
If success <> True Then
    Log("Could not load private KMS configuration.")
    Return
End If

stringCompare.SetString(credentials.StringOf("access_key"))
Dim stringMatch1 As Boolean = stringCompare.ContentsEqual("", True)
If (credentials.JsonTypeOf("access_key") <> 1) Or (stringMatch1 = True) Then
    Log("Missing or invalid access_key.")
    Return
End If

stringCompare.SetString(credentials.StringOf("secret_key"))
Dim stringMatch2 As Boolean = stringCompare.ContentsEqual("", True)
If (credentials.JsonTypeOf("secret_key") <> 1) Or (stringMatch2 = True) Then
    Log("Missing or invalid secret_key.")
    Return
End If

Dim region As String = "us-west-2"
Dim endpoint As ChilkatStringBuilder
endpoint.Initialize
endpoint.Append("kms.")
endpoint.Append(region)
endpoint.Append(".amazonaws.com")
Dim aws As ChilkatAuthAws
aws.Initialize
aws.AccessKey = credentials.StringOf("access_key")
aws.SecretKey = credentials.StringOf("secret_key")
aws.Region = region
aws.ServiceName = "kms"
aws.SignatureVersion = 4
Dim rest As ChilkatRest
rest.Initialize("rest")
rest.ConnectTimeoutMs = 20000
rest.IdleTimeoutMs = 60000
rest.VerboseLogging = False
success = rest.SetAuthAws(aws)
If success <> True Then
    Log("Could not configure AWS signing.")
    Return
End If

If credentials.HasMember("session_token") = True Then
    stringCompare.SetString(credentials.StringOf("session_token"))
    Dim stringMatch3 As Boolean = stringCompare.ContentsEqual("", True)
    If (credentials.JsonTypeOf("session_token") <> 1) Or (stringMatch3 = True) Then
        Log("Missing or invalid session_token.")
        Return
    End If

End If

Dim connection As ChilkatSocket
connection.Initialize("connection")
connection.RequireSslCertVerify = True
connection.MaxReadIdleMs = 60000
connection.MaxSendIdleMs = 60000
success = connection.Connect(endpoint.GetAsString, 443, True, 20000)
If success <> True Then
    Log("TLS connection failed; inspect diagnostics privately.")
    Return
End If

success = rest.UseConnection(connection, True)
If success <> True Then
    Log("Could not attach TLS connection.")
    Return
End If

'  Keep connection alive while Rest uses it.
Dim body As ChilkatJsonObject
body.Initialize
Dim result As ChilkatJsonObject
result.Initialize
result.Strict = True
Dim responseJson As String
stringCompare.SetString(credentials.StringOf("key_id"))
Dim stringMatch4 As Boolean = stringCompare.ContentsEqual("", True)
If (credentials.JsonTypeOf("key_id") <> 1) Or (stringMatch4 = True) Then
    Log("Missing or invalid key_id.")
    Return
End If

Dim keyId As String = credentials.StringOf("key_id")
stringCompare.SetString(credentials.StringOf("destination_key_id"))
Dim stringMatch5 As Boolean = stringCompare.ContentsEqual("", True)
If (credentials.JsonTypeOf("destination_key_id") <> 1) Or (stringMatch5 = True) Then
    Log("Missing or invalid destination_key_id.")
    Return
End If

Dim destinationKeyId As String = credentials.StringOf("destination_key_id")
Dim ciphertext As ChilkatBinData
ciphertext.Initialize
success = ciphertext.LoadFile("qa_output/kms_ciphertext.bin")
If success <> True Then
    Log("Could not load qa_output/kms_ciphertext.bin.")
    Return
End If

If (ciphertext.NumBytes = 0) Or (ciphertext.NumBytes > 6144) Then
    Log("Input byte length is outside the sample limit.")
    Return
End If

body.Clear
success = body.UpdateString("SourceKeyId", keyId)
If success <> True Then
    Log("Could not set SourceKeyId.")
    Return
End If

success = body.UpdateString("DestinationKeyId", destinationKeyId)
If success <> True Then
    Log("Could not set DestinationKeyId.")
    Return
End If

success = body.UpdateString("CiphertextBlob", ciphertext.GetEncoded("base64"))
If success <> True Then
    Log("Could not set CiphertextBlob.")
    Return
End If

success = body.UpdateString("SourceEncryptionAlgorithm", "SYMMETRIC_DEFAULT")
If success <> True Then
    Log("Could not set SourceEncryptionAlgorithm.")
    Return
End If

success = body.UpdateString("DestinationEncryptionAlgorithm", "SYMMETRIC_DEFAULT")
If success <> True Then
    Log("Could not set DestinationEncryptionAlgorithm.")
    Return
End If

success = body.UpdateString("SourceEncryptionContext.Application", "ChilkatKmsExamples")
If success <> True Then
    Log("Could not set SourceEncryptionContext.Application.")
    Return
End If

success = body.UpdateString("DestinationEncryptionContext.Application", "ChilkatKmsExamplesV2")
If success <> True Then
    Log("Could not set DestinationEncryptionContext.Application.")
    Return
End If

success = rest.ClearAllQueryParams
If success <> True Then
    Log("Could not clear previous query parameters.")
    Return
End If

'  Keep the JSON operation body separate from authentication parameters.
'  Include STS credentials in the signed query; never log the request URL.
If credentials.HasMember("session_token") = True Then
    success = rest.AddQueryParam("X-Amz-Security-Token", credentials.StringOf("session_token"))
    If success <> True Then
        Log("Could not set session token.")
        Return
    End If

End If

success = rest.AddHeader("X-Amz-Target", "TrentService.ReEncrypt")
If success <> True Then
    Log("Could not set operation.")
    Return
End If

success = rest.AddHeader("Content-Type", "application/x-amz-json-1.1")
If success <> True Then
    Log("Could not set content type.")
    Return
End If

responseJson = rest.FullRequestString("POST", "/", body.Emit)
If rest.LastMethodSuccess <> True Then
    Log("KMS request did not complete; inspect diagnostics privately. Reconcile any write before retrying.")
    Return
End If

If rest.ResponseStatusCode <> 200 Then
    Log("KMS HTTP status: " & rest.ResponseStatusCode)
    success = result.Load(responseJson)
    If success = True Then
        If result.JsonTypeOf("__type") = 1 Then
            Log("AWS error code: " & result.StringOf("__type"))
        End If

    End If

    Log("AWS request ID: " & rest.ResponseHdrByName("x-amzn-RequestId"))
    '  Do not print full bodies, headers, credentials, key material, or tokens.
    Return
End If

success = result.Load(responseJson)
If success <> True Then
    Log("Expected a well-formed JSON response.")
    Return
End If

stringCompare.SetString(result.StringOf("KeyId"))
Dim stringMatch6 As Boolean = stringCompare.ContentsEqual("", True)
If (result.JsonTypeOf("KeyId") <> 1) Or (stringMatch6 = True) Then
    Log("Missing or invalid KeyId.")
    Return
End If

stringCompare.SetString(result.StringOf("KeyId"))
Dim stringMatch7 As Boolean = stringCompare.ContentsEqual(destinationKeyId, True)
If stringMatch7 <> True Then
    Log("Unexpected destination key.")
    Return
End If

stringCompare.SetString(result.StringOf("SourceKeyId"))
Dim stringMatch8 As Boolean = stringCompare.ContentsEqual("", True)
If (result.JsonTypeOf("SourceKeyId") <> 1) Or (stringMatch8 = True) Then
    Log("Missing or invalid SourceKeyId.")
    Return
End If

stringCompare.SetString(result.StringOf("SourceKeyId"))
Dim stringMatch9 As Boolean = stringCompare.ContentsEqual(keyId, True)
If stringMatch9 <> True Then
    Log("Response belongs to another key; use a fixed key ARN in configuration.")
    Return
End If

stringCompare.SetString(result.StringOf("CiphertextBlob"))
Dim stringMatch10 As Boolean = stringCompare.ContentsEqual("", True)
If (result.JsonTypeOf("CiphertextBlob") <> 1) Or (stringMatch10 = True) Then
    Log("Missing or invalid CiphertextBlob.")
    Return
End If

Dim reencrypted As ChilkatBinData
reencrypted.Initialize
success = reencrypted.AppendEncoded(result.StringOf("CiphertextBlob"), "base64")
If success <> True Then
    Log("Invalid base64 CiphertextBlob.")
    Return
End If

If reencrypted.NumBytes = 0 Then
    Log("Unexpected byte length for CiphertextBlob.")
    Return
End If

success = reencrypted.WriteFile("qa_output/kms_reencrypted.bin")
If success <> True Then
    Log("Could not write qa_output/kms_reencrypted.bin.")
    Return
End If

Log("Example completed.")