Amazon S3: Upload with SSE-KMS and Verify Encryption
See more S3 - REST Examples
Supply a KMS key ARN in the same region as the bucket. PUT requests SSE-KMS and stores a full-object SHA-256 checksum for use by the checksum-verification example. HEAD checks the algorithm and key ARN using the returned version ID when available and the written ETag. Write-only encryption headers are removed before HEAD. This is server-side encryption; plaintext is sent over HTTPS and S3 encrypts it at rest.
Requires s3:PutObject, kms:GenerateDataKey, and permission to read the resulting object metadata. Subsequent downloads can need kms:Decrypt; IAM and KMS key policies must both permit the operation. Use the full key ARN to avoid alias/account ambiguity. Encryption does not make an object public or replace access control. The selected key can overwrite an unversioned object or create a new version. KMS requests can incur charges.
For general purpose S3 buckets, using regional HTTPS endpoints and AWS Signature Version 4. Directory buckets (S3 Express), access points, Outposts, and other AWS partitions need their own endpoint/authentication rules. Use a bucket name without dots for these virtual-hosted TLS examples; see the path-style example for dotted names.
Provide current IAM credentials in a private qa_data/aws/s3.json file with string fields access_key, secret_key, and session_token for temporary credentials. Prefer short-lived role credentials. This file is explicitly loaded; these examples do not discover profiles or refresh credentials. Keep it outside public content and source control. The session token is included in the signed request. TLS certificate verification is enabled on the Socket used by Rest.
Transport success and HTTP success are different. Keep full diagnostics private; signed requests and presigned URLs can contain credentials or grant access. For retryable reads use bounded backoff with jitter. Before retrying a write with an uncertain outcome, check the resource state. Keep keys, upload IDs, version IDs, ETags, and large sizes as strings.
Chilkat Dart Downloads
import 'package:chilkat/chilkat.dart';
void main() {
var success = false;
// StringBuilder compares text by value in every generated language.
final textCompare = CkStringBuilder();
// Assumes Chilkat is unlocked. See Global Unlock Sample.
success = false;
// Private configuration, not a file in public web content or source control.
// Load current IAM credentials authorized for the S3 operation.
final credentials = CkJsonObject();
credentials.strict = true;
try {
credentials.loadFile('qa_data/aws/s3.json');
} on ChilkatException {
print('Could not load private AWS credentials.');
return;
}
textCompare.clear();
textCompare.setString(credentials.stringOf('access_key'));
final sameText1 = textCompare.contentsEqual('', true);
if ((credentials.jsonTypeOf('access_key') != 1) || (sameText1)) {
print('Missing or invalid access_key.');
return;
}
textCompare.clear();
textCompare.setString(credentials.stringOf('secret_key'));
final sameText2 = textCompare.contentsEqual('', true);
if ((credentials.jsonTypeOf('secret_key') != 1) || (sameText2)) {
print('Missing or invalid secret_key.');
return;
}
// General purpose bucket in the commercial AWS partition.
final region = 'us-west-2';
final bucketName = 'amzn-s3-demo-bucket';
final endpoint = CkStringBuilder();
try {
endpoint.append(bucketName);
} on ChilkatException {
print('Could not build text.');
return;
}
try {
endpoint.append('.');
} on ChilkatException {
print('Could not build text.');
return;
}
try {
endpoint.append('s3.');
} on ChilkatException {
print('Could not build text.');
return;
}
try {
endpoint.append(region);
} on ChilkatException {
print('Could not build text.');
return;
}
try {
endpoint.append('.amazonaws.com');
} on ChilkatException {
print('Could not build text.');
return;
}
final aws = CkAuthAws();
aws.accessKey = credentials.stringOf('access_key');
aws.secretKey = credentials.stringOf('secret_key');
aws.region = region;
aws.serviceName = 's3';
aws.signatureVersion = 4;
final rest = CkRest();
rest.connectTimeoutMs = 20000;
rest.idleTimeoutMs = 60000;
try {
rest.setAuthAws(aws);
} on ChilkatException {
print('Could not configure AWS signing.');
return;
}
// Temporary credentials require this token in every signed query.
// Keep request URLs private. Do not clear this parameter between requests.
if (credentials.hasMember('session_token')) {
if (credentials.jsonTypeOf('session_token') != 1) {
print('session_token must be a string.');
return;
}
textCompare.clear();
textCompare.setString(credentials.stringOf('session_token'));
final sameText3 = textCompare.contentsEqual('', true);
if (!sameText3) {
try {
rest.addQueryParam('X-Amz-Security-Token', credentials.stringOf('session_token'));
} on ChilkatException {
print('Could not prepare the request.');
return;
}
}
}
// Connect to the SAME hostname used for TLS verification and request signing.
final connection = CkSocket();
connection.requireSslCertVerify = true;
connection.maxReadIdleMs = 60000;
connection.maxSendIdleMs = 60000;
try {
connection.connect(endpoint.getAsString(), 443, true, 20000);
} on ChilkatException {
print('TLS connection failed; inspect diagnostics privately.');
return;
}
try {
rest.useConnection(connection, true);
} on ChilkatException {
print('Could not attach the TLS connection.');
return;
}
final xml = CkXml();
xml.strict = true;
// Supply an unencoded object key, not a URL. Preserve slashes in the key.
final objectKey = 'documents/example.txt';
final objectPath = CkStringBuilder();
try {
objectPath.append(objectKey);
} on ChilkatException {
print('Could not build text.');
return;
}
try {
objectPath.encode('url_rfc3986', 'utf-8');
} on ChilkatException {
print('Could not encode the object key.');
return;
}
final restoredSlashes = objectPath.replace('%2F', '/');
try {
objectPath.prepend('/');
} on ChilkatException {
print('Could not prepare the request.');
return;
}
final kmsKeyArn = 'arn:aws:kms:us-west-2:123456789012:key/11111111-2222-3333-4444-555555555555';
try {
rest.addHeader('x-amz-server-side-encryption', 'aws:kms');
} on ChilkatException {
print('Could not prepare the request.');
return;
}
try {
rest.addHeader('x-amz-server-side-encryption-aws-kms-key-id', kmsKeyArn);
} on ChilkatException {
print('Could not prepare the request.');
return;
}
try {
rest.addHeader('Content-Type', 'text/plain; charset=utf-8');
} on ChilkatException {
print('Could not prepare the request.');
return;
}
final requestBody = 'Encrypted at rest by S3.\n';
final digest = CkCrypt2();
digest.charset = 'utf-8';
digest.hashAlgorithm = 'sha256';
digest.encodingMode = 'base64';
final String checksumBase64;
try {
checksumBase64 = digest.hashStringENC(requestBody);
} on ChilkatException {
print('Could not calculate the content checksum.');
return;
}
try {
rest.addHeader('x-amz-checksum-sha256', checksumBase64);
} on ChilkatException {
print('Could not prepare the request.');
return;
}
final String responseBody;
try {
responseBody = rest.fullRequestString('PUT', objectPath.getAsString(), requestBody);
} on ChilkatException {
print('Request did not complete; inspect diagnostics privately.');
return;
}
if (rest.responseStatusCode != 200) {
print('S3 HTTP status: ${rest.responseStatusCode}');
success = true;
try {
xml.loadXml(responseBody);
} on ChilkatException {
success = false;
}
textCompare.clear();
textCompare.setString(xml.tag);
final sameText4 = textCompare.contentsEqual('Error', true);
if ((success) && (sameText4)) {
print('S3 error code: ${xml.getChildContent('Code')}');
}
// Keep signed headers, credentials, URLs, and full diagnostics private.
// A timeout may leave a write's outcome uncertain. Check before retrying.
return;
}
final writtenEtag = rest.responseHdrByName('ETag');
textCompare.clear();
textCompare.setString(writtenEtag);
final sameText5 = textCompare.contentsEqual('', true);
if ((!rest.lastMethodSuccess) || (sameText5)) {
print('Missing response header: ETag');
return;
}
var writtenVersion = '';
try {
writtenVersion = rest.responseHdrByName('x-amz-version-id');
} on ChilkatException {
writtenVersion = '';
}
try {
rest.removeHeader('x-amz-server-side-encryption');
} on ChilkatException {
print('Could not prepare the request.');
return;
}
try {
rest.removeHeader('x-amz-server-side-encryption-aws-kms-key-id');
} on ChilkatException {
print('Could not prepare the request.');
return;
}
try {
rest.removeHeader('x-amz-checksum-sha256');
} on ChilkatException {
print('Could not prepare the request.');
return;
}
try {
rest.removeHeader('Content-Type');
} on ChilkatException {
print('Could not prepare the request.');
return;
}
textCompare.clear();
textCompare.setString(writtenVersion);
final sameText6 = textCompare.contentsEqual('', true);
if (!sameText6) {
try {
rest.addQueryParam('versionId', writtenVersion);
} on ChilkatException {
print('Could not prepare the request.');
return;
}
}
// Also protect the mutable null version and unversioned objects with the ETag.
try {
rest.addHeader('If-Match', writtenEtag);
} on ChilkatException {
print('Could not prepare the request.');
return;
}
try {
rest.sendReqNoBody('HEAD', objectPath.getAsString());
} on ChilkatException {
print('Could not send HEAD request.');
return;
}
final statusCode = rest.readResponseHeader();
if (statusCode < 0) {
print('Could not read the response header.');
return;
}
if (statusCode != 200) {
print('HEAD did not return HTTP 200. A 403 is not proof that an object is missing.');
return;
}
// HEAD has no response body; do not call a body-reading method.
final encryption = rest.responseHdrByName('x-amz-server-side-encryption');
textCompare.clear();
textCompare.setString(encryption);
final sameText7 = textCompare.contentsEqual('', true);
if ((!rest.lastMethodSuccess) || (sameText7)) {
print('Missing response header: x-amz-server-side-encryption');
return;
}
final actualKey = rest.responseHdrByName('x-amz-server-side-encryption-aws-kms-key-id');
textCompare.clear();
textCompare.setString(actualKey);
final sameText8 = textCompare.contentsEqual('', true);
if ((!rest.lastMethodSuccess) || (sameText8)) {
print('Missing response header: x-amz-server-side-encryption-aws-kms-key-id');
return;
}
textCompare.clear();
textCompare.setString(encryption);
final sameText9 = textCompare.contentsEqual('aws:kms', true);
textCompare.clear();
textCompare.setString(actualKey);
final sameText10 = textCompare.contentsEqual(kmsKeyArn, true);
if ((!sameText9) || (!sameText10)) {
print('Upload returned success, but encryption metadata did not match the requested KMS key.');
return;
}
print('Upload and SSE-KMS encryption metadata verified.');
}