0
votes

I am trying to multi-part upload a file using Amazon S3 Server side encryption(KMS). I am getting a little confused whether I do need the KMS key in my code anywhere and if so, then how do I add it to the Java code?

--Update private static void saveMultipartData(String clientRegion, String bucketName, String awsFilePath, File file) { AmazonS3 s3client = AmazonS3Client.builder() .withRegion(clientRegion) .withCredentials(new AWSStaticCredentialsProvider(credentials)) .build();

    ObjectMetadata objectMetadata = new ObjectMetadata();
    PutObjectRequest putRequest = null;
    try {
        try {
            putRequest = new PutObjectRequest(bucketName,
                    awsFilePath,
                    new FileInputStream(file),
                    objectMetadata);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // Upload the object and check its encryption status.
        putRequest.putCustomRequestHeader("x-amz-server-side-encryption","aws:kms");
        putRequest.putCustomRequestHeader("x-amz-server-side-encryption-aws-kms-key-id","<<keyID>>");

        TransferManager tm = TransferManagerBuilder.standard().withMinimumUploadPartSize(100L).withMultipartUploadThreshold(100L)
                .withS3Client(s3client)
                .build();
        Upload upload = tm.upload(putRequest);

        upload.waitForCompletion();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
1

1 Answers

2
votes

While you don't need to have the KMS key in your code, your code does need to be able to access the key. What I am implying is that you, for example, use an environment variable to pass this value in- that way the key is hidden. Once you have the key, doing a multi-part upload can be performed as this:

InitiateMultipartUploadRequest initRequest = new
                InitiateMultipartUploadRequest(bucketName, keyName);
        initRequest.putCustomRequestHeader("x-amz-server-side-encryption", "aws:kms");
        initRequest.putCustomRequestHeader("x-amz-server-side-encryption-aws-kms-key-id", kmsKey);