Search code examples
javaamazon-s3encryptionrequest-headersamazon-kms

How do I set a request header(x-amz-server-side-encryption : aws:kms) while saving file to S3 in Java code?


Below is the code that I have for uploading files to S3 using KMS server side encryption. However I am getting the exception "Server Side Encryption with AWS KMS managed key requires HTTP header x-amz-server-side-encryption : aws:kms";

Not sure where to place the header in the Java code to save file.

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

            ObjectMetadata objectMetadata = new ObjectMetadata();
            //objectMetadata.setHeader("x-amz-server-side-encryption" , "aws:kms");

            objectMetadata.setSSEAlgorithm(ObjectMetadata.AES_256_SERVER_SIDE_ENCRYPTION);

            PutObjectRequest putRequest = null;
            try {
                putRequest = new PutObjectRequest(bucketName,
                        awsFilePath,
                        new FileInputStream(file),
                        objectMetadata).withSSEAwsKeyManagementParams(new SSEAwsKeyManagementParams("arn:aws:kms:<<key>>"));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

            // Upload the object and check its encryption status.
            PutObjectResult putResult = s3client.putObject(putRequest);
            printEncryptionStatus(putResult);
        }

Solution

  • I got the answer by some hit and trials... -- putRequest.putCustomRequestHeader("x-amz-server-side-encryption","aws:kms");