AWS Developer Blog

Generating Amazon S3 Pre-signed URLs with SSE-S3 (Part 3)

by Hanson Char | on | in Java | Permalink | Comments |  Share

As mentioned in Part 1 and Part 2 of this blog, there are fundamentally four ways you can generate Amazon S3 pre-signed URLs using server-side encryption (SSE). We demonstrated how you could do so with SSE-KMS (server-side encryption with AWS Key Management Service).

In this blog, I will provide further sample code that shows how you can generate and consume pre-signed URLs for SSE-S3 (server-side encryption with Amazon S3-managed keys). The code samples assume the version of the AWS SDK for Java to be 1.9.31 or later.

Server-Side Encryption with Amazon S3-Managed Keys (SSE-S3)

Here’s how to generate a pre-signed PUT URL using SSE-S3:


AmazonS3Client s3 = ...;
String myExistingBucket = ... // an existing bucket
String myKey = ...    // target S3 key
// Generate a pre-signed PUT URL for use with SSE-S3
GeneratePresignedUrlRequest genreq = new GeneratePresignedUrlRequest(
    myExistingBucket, myKey, HttpMethod.PUT);
genreq.setSSEAlgorithm(SSEAlgorithm.getDefault());
URL puturl = s3.generatePresignedUrl(genreq);
System.out.println("Pre-signed PUT URL with SSE-S3: " + puturl);

Here’s how to make use of the generated pre-signed PUT URL via the Apache HttpClient (4.3):


File fileToUpload = ...;
HttpPut putreq = new HttpPut(URI.create(puturl.toExternalForm()));
// AES256 is currently the only supported algorithm for SSE-S3
putreq.addHeader(new BasicHeader(Headers.SERVER_SIDE_ENCRYPTION,
    SSEAlgorithm.AES256.getAlgorithm()));
putreq.setEntity(new FileEntity(fileToUpload));
CloseableHttpClient httpclient = HttpClients.createDefault();
httpclient.execute(putreq);

Here’s how to generate a pre-signed GET URL for use with SSE-S3:


GeneratePresignedUrlRequest genreq = new GeneratePresignedUrlRequest(
    BUCKET, KEY, HttpMethod.GET);
URL geturl = s3.generatePresignedUrl(genreq);
System.out.println("Pre-signed GET URL for SSE-S3: " + geturl);

(Note in particular that generating a pre-signed GET URL for an S3 object encrypted using SSE-S3 is as simple as generating a regular pre-signed URL!)

Here’s how to make use of the generated pre-signed GET URL via the Apache HttpClient (4.3):


HttpGet getreq = new HttpGet(URI.create(geturl.toExternalForm()));
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse res = httpclient.execute(getreq);
InputStream is = res.getEntity().getContent();
String actual = IOUtils.toString(is);

In Part 4 and 5, I will provide code examples to show how you can generate and consume pre-signed URLs using server-side encryption with customer-provided encryption keys (SSE-C).

Enjoy!