C# AWS KMS: Encrypt

Back to Index

Encrypts plaintext into ciphertext by using a customer master key (CMK). The Encrypt operation has two primary use cases: You can encrypt up to 4 kilobytes (4096 bytes) of arbitrary data such as an RSA key, a database password, or other sensitive information.

Documentation: https://docs.aws.amazon.com/kms/latest/APIReference/API_Encrypt.html

CURL Command

curl -X POST https://kms.us-west-2.amazonaws.com/ \
  -H "Content-Type: application/x-amz-json-1.1" \
  -H "X-Amz-Target: TrentService.Encrypt" \
  -d '{
  "Plaintext": "VGhpcyBpcyBEYXkgMSBmb3IgdGhlIEludGVybmV0Cg==",
  "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab"
}'

C# Example

Chilkat.Rest rest = new Chilkat.Rest();
bool success;

Chilkat.AuthAws authAws = new Chilkat.AuthAws();
authAws.AccessKey = "AWS_ACCESS_KEY";
authAws.SecretKey = "AWS_SECRET_KEY";
authAws.Region = "us-west-2";
authAws.ServiceName = "kms";
rest.SetAuthAws(authAws);

//  URL: https://kms.us-west-2.amazonaws.com/
bool bTls = true;
int port = 443;
bool bAutoReconnect = true;
success = rest.Connect("kms.us-west-2.amazonaws.com",port,bTls,bAutoReconnect);
if (success != true) {
    Debug.WriteLine("ConnectFailReason: " + Convert.ToString(rest.ConnectFailReason));
    Debug.WriteLine(rest.LastErrorText);
    return;
}

//  See the Online Tool for Generating JSON Creation Code
Chilkat.JsonObject json = new Chilkat.JsonObject();
json.UpdateString("Plaintext","VGhpcyBpcyBEYXkgMSBmb3IgdGhlIEludGVybmV0Cg==");
json.UpdateString("KeyId","1234abcd-12ab-34cd-56ef-1234567890ab");

rest.AddHeader("Content-Type","application/x-amz-json-1.1");
rest.AddHeader("X-Amz-Target","TrentService.Encrypt");

Chilkat.StringBuilder sbRequestBody = new Chilkat.StringBuilder();
json.EmitSb(sbRequestBody);
Chilkat.StringBuilder sbResponseBody = new Chilkat.StringBuilder();
success = rest.FullRequestSb("POST","/",sbRequestBody,sbResponseBody);
if (success != true) {
    Debug.WriteLine(rest.LastErrorText);
    return;
}

int respStatusCode = rest.ResponseStatusCode;
if (respStatusCode >= 400) {
    Debug.WriteLine("Response Status Code = " + Convert.ToString(respStatusCode));
    Debug.WriteLine("Response Header:");
    Debug.WriteLine(rest.ResponseHeader);
    Debug.WriteLine("Response Body:");
    Debug.WriteLine(sbResponseBody.GetAsString());
    return;
}

Chilkat.JsonObject jsonResponse = new Chilkat.JsonObject();
jsonResponse.LoadSb(sbResponseBody);

//  See the Online Tool for Generating JSON Parse Code

string CiphertextBlob = jsonResponse.StringOf("CiphertextBlob");
string KeyId = jsonResponse.StringOf("KeyId");

Sample JSON Response Body

{
  "CiphertextBlob": "AQICAHjoEH04sk1K+PYPm8oEByfcBJmWf06ddnLEJvRVILZQCgG3csOqp04O/sKCF5M22euDAAAAfTB7BgkqhkiG9w0BBwagbjBsAgEAMGcGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQM8RGyAL7quN8r1RSUAgEQgDqar9XmazINNj6yWUDDfR0P89tP5yEvoyDmc7UfrA4GKp3ClANaHQgWqR1KidmfU2lVMfnJbVUOuuNB",
  "KeyId": "arn:aws:kms:us-west-2:954491834127:key/1234abcd-12ab-34cd-56ef-1234567890ab"
}