Skip to content

Instantly share code, notes, and snippets.

@piyusht007
Created March 28, 2018 11:41
Show Gist options
  • Save piyusht007/33a60c32a9ab0156f9aa473701827ddf to your computer and use it in GitHub Desktop.
Save piyusht007/33a60c32a9ab0156f9aa473701827ddf to your computer and use it in GitHub Desktop.
Generating Amazon S3 Pre-signed URLs with Server Side Encryption - KMS
public class PresignedLinkGenerator {
private static final int EXPIRATION_TIME_IN_MILLISECONDS = 1000 * 60 * 60; // 1 hour
private static final String SIGNER_TYPE = "AWSS3V4SignerType";
private String KmsKeyARN = "<EncryptionKeyARN>";
public URL generatePresignedLink(final String bucketName, final String objectKey, final HttpMethod httpMethod) throws Exception {
final Region currentRegion = Regions.getCurrentRegion() == null ? Region.getRegion(Regions.US_WEST_2) : Regions.getCurrentRegion();
final AmazonS3 s3client = AmazonS3ClientBuilder.standard()
.withClientConfiguration(new ClientConfiguration().withSignerOverride(SIGNER_TYPE))
.withRegion(currentRegion.getName())
.build();
URL url;
try {
final Date expiration = new Date();
long milliSeconds = expiration.getTime();
milliSeconds += EXPIRATION_TIME_IN_MILLISECONDS;
expiration.setTime(milliSeconds);
final GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName,
objectKey);
generatePresignedUrlRequest.setMethod(httpMethod);
generatePresignedUrlRequest.setExpiration(expiration);
if (httpMethod != HttpMethod.GET) {
generatePresignedUrlRequest.setSSEAlgorithm(SSEAlgorithm.KMS.getAlgorithm());
generatePresignedUrlRequest.setKmsCmkId(KmsKeyARN);
generatePresignedUrlRequest.setContentType("application/octet-stream");
}
url = s3client.generatePresignedUrl(generatePresignedUrlRequest);
} catch (AmazonClientException e) {
throw e;
}
return url;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment