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

AWS KMS: Derive an ECDH Secret and Apply HKDF-SHA256

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.

Demonstrates both peers in one process using a NIST P-256 KEY_AGREEMENT KMS key and a fresh local EC private key. Retrieves the KMS public key through authenticated KMS and compares both shared secrets. For a remote peer, validate/authenticate its public key and bind identities and protocol transcript into KDF context. HKDF extract/expand derives one 32-byte key; communicate the public salt and context to the other party. No secret is printed. This is not a complete authenticated exchange protocol.

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

DescribeKey | DeriveSharedSecret | GetPublicKey

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")
body.Clear
success = body.UpdateString("KeyId", keyId)
If success <> True Then
    Log("Could not set KeyId.")
    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.DescribeKey")
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("KeyMetadata.Arn"))
Dim stringMatch5 As Boolean = stringCompare.ContentsEqual("", True)
If (result.JsonTypeOf("KeyMetadata.Arn") <> 1) Or (stringMatch5 = True) Then
    Log("Missing or invalid KeyMetadata.Arn.")
    Return
End If

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

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

stringCompare.SetString(result.StringOf("KeyMetadata.KeySpec"))
Dim stringMatch8 As Boolean = stringCompare.ContentsEqual("ECC_NIST_P256", True)
If stringMatch8 <> True Then
    Log("Unexpected KeyMetadata.KeySpec.")
    Return
End If

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

stringCompare.SetString(result.StringOf("KeyMetadata.KeyUsage"))
Dim stringMatch10 As Boolean = stringCompare.ContentsEqual("KEY_AGREEMENT", True)
If stringMatch10 <> True Then
    Log("Unexpected KeyMetadata.KeyUsage.")
    Return
End If

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

stringCompare.SetString(result.StringOf("KeyMetadata.KeyState"))
Dim stringMatch12 As Boolean = stringCompare.ContentsEqual("Enabled", True)
If stringMatch12 <> True Then
    Log("Unexpected KeyMetadata.KeyState.")
    Return
End If

keyId = result.StringOf("KeyMetadata.Arn")
'  This example controls the peer key locally; authenticate remote peer keys separately.
Dim ecc As ChilkatEcc
ecc.Initialize
Dim prng As ChilkatPrng
prng.Initialize
Dim peerPrivate As ChilkatPrivateKey
peerPrivate.Initialize("peerPrivate")
Dim peerPublic As ChilkatPublicKey
peerPublic.Initialize
Dim peerDer As ChilkatBinData
peerDer.Initialize
success = ecc.GenKey("secp256r1", prng, peerPrivate)
If success <> True Then
    Log("Could not generate peer key.")
    Return
End If

success = peerPrivate.ToPublicKey(peerPublic)
If success <> True Then
    Log("Could not get peer public key.")
    Return
End If

success = peerPublic.GetDerBd(False, peerDer)
If success <> True Then
    Log("Could not encode SPKI peer key.")
    Return
End If

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

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

success = body.UpdateString("PublicKey", peerDer.GetEncoded("base64"))
If success <> True Then
    Log("Could not set PublicKey.")
    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.DeriveSharedSecret")
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 stringMatch13 As Boolean = stringCompare.ContentsEqual("", True)
If (result.JsonTypeOf("KeyId") <> 1) Or (stringMatch13 = True) Then
    Log("Missing or invalid KeyId.")
    Return
End If

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

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

stringCompare.SetString(result.StringOf("KeyAgreementAlgorithm"))
Dim stringMatch16 As Boolean = stringCompare.ContentsEqual("ECDH", True)
If stringMatch16 <> True Then
    Log("Unexpected KeyAgreementAlgorithm.")
    Return
End If

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

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

If shared.NumBytes <> 32 Then
    Log("Unexpected byte length for SharedSecret.")
    Return
End If

body.Clear
success = body.UpdateString("KeyId", keyId)
If success <> True Then
    Log("Could not set KeyId.")
    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.GetPublicKey")
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 stringMatch18 As Boolean = stringCompare.ContentsEqual("", True)
If (result.JsonTypeOf("KeyId") <> 1) Or (stringMatch18 = True) Then
    Log("Missing or invalid KeyId.")
    Return
End If

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

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

stringCompare.SetString(result.StringOf("KeySpec"))
Dim stringMatch21 As Boolean = stringCompare.ContentsEqual("ECC_NIST_P256", True)
If stringMatch21 <> True Then
    Log("Unexpected KeySpec.")
    Return
End If

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

stringCompare.SetString(result.StringOf("KeyUsage"))
Dim stringMatch23 As Boolean = stringCompare.ContentsEqual("KEY_AGREEMENT", True)
If stringMatch23 <> True Then
    Log("Unexpected KeyUsage.")
    Return
End If

Dim kmsPublic As ChilkatPublicKey
kmsPublic.Initialize
success = kmsPublic.LoadBase64(result.StringOf("PublicKey"))
If success <> True Then
    Log("Could not load KMS public key.")
    Return
End If

Dim peerSecret As String = ecc.SharedSecretENC(peerPrivate, kmsPublic, "base64")
If ecc.LastMethodSuccess <> True Then
    Log("Local ECDH failed.")
    Return
End If

Dim localShared As ChilkatBinData
localShared.Initialize
success = localShared.AppendEncoded(peerSecret, "base64")
If success <> True Then
    Log("Could not decode local shared secret.")
    Return
End If

If shared.ContentsEqual(localShared) <> True Then
    Log("ECDH secrets did not match.")
    Return
End If

'  RFC 5869 HKDF-SHA256, one 32-byte output block. Salt is public and random.
Dim salt As String = prng.GenRandom(32, "base64")
If prng.LastMethodSuccess <> True Then
    Log("Could not generate salt.")
    Return
End If

Dim hkdf As ChilkatCrypt2
hkdf.Initialize("hkdf")
hkdf.MacAlgorithm = "hmac"
hkdf.HashAlgorithm = "sha256"
hkdf.EncodingMode = "base64"
success = hkdf.SetMacKeyEncoded(salt, "base64")
If success <> True Then
    Log("Could not set HKDF salt.")
    Return
End If

Dim prk As String = hkdf.MacBdENC(shared)
If hkdf.LastMethodSuccess <> True Then
    Log("HKDF extract failed.")
    Return
End If

success = hkdf.SetMacKeyEncoded(prk, "base64")
If success <> True Then
    Log("Could not set HKDF PRK.")
    Return
End If

Dim info As ChilkatBinData
info.Initialize
success = info.AppendString("chilkat-kms-ecdh-v1", "utf-8")
If success <> True Then
    Log("Could not set KDF context.")
    Return
End If

success = info.AppendEncoded("01", "hex")
If success <> True Then
    Log("Could not append HKDF block counter.")
    Return
End If

Dim derivedKey As String = hkdf.MacBdENC(info)
If hkdf.LastMethodSuccess <> True Then
    Log("HKDF expand failed.")
    Return
End If

success = shared.SecureClear
If success <> True Then
    Log("Could not clear shared secret buffer.")
    Return
End If

success = localShared.SecureClear
If success <> True Then
    Log("Could not clear local secret buffer.")
    Return
End If

Log("ECDH secrets matched and a 32-byte application key was derived.")