dmhamilt's avatar

AWS S3 Turn Server Side Encryption (SSE) when uploading

I am trying to upload a file and turn on SSE with Amazon AWS

$request->file('upload')->store("files/{$this->user->id}");

Is there a way to pass this in the headers x-amz-server-side-encryption ?

AWS states it needs to be in the headers to turn on encryption.

http://docs.aws.amazon.com/AmazonS3/latest/dev/SSEUsingRESTAPI.html

I have also started to play around with writing my own interface but I am not familiar with how to tie this into my fileController. This looks like it needs to go in the view on a form.

        $client = new \Aws\S3\S3Client([
            'version' => 'latest',
            'region' => env('AWS_REGION'),
        ]);
        $bucket = env('AWS_BUCKET');

        // Set some defaults for form input fields
        $formInputs = ['acl' => 'public-read'];

        // Construct an array of conditions for policy
        $options = [
            ['acl' => 'public-read'],
            ['bucket' => $bucket],
            ['starts-with', '$key', 'user/eric/'],
        ];

        // Optional: configure expiration time string
        $expires = '+2 hours';

        $postObject = new \Aws\S3\PostObjectV4(
            $client,
            $bucket,
            $formInputs,
            $options,
            $expires
        );

        // Get attributes to set on an HTML form, e.g., action, method, enctype
        $formAttributes = $postObject->getFormAttributes();

        // Get form input fields. This will include anything set as a form input in
        // the constructor, the provided JSON policy, your AWS Access Key ID, and an
        // auth signature.
        $formInputs = $postObject->getFormInputs();

How do I use this and where do I place the x-amz-server-side-encryption?

0 likes
1 reply
dmhamilt's avatar
dmhamilt
OP
Best Answer
Level 2

The trick is to create an AWS client and then use putObject to store the file.

http://docs.aws.amazon.com/aws-sdk-php/v3/api/api-s3-2006-03-01.html#putobject

$filename=$request->file('upload')->getFilename();
        $file_ext=$request->file('upload')->clientExtension();
        $path="files/".$this->user->customer->id.'/'.$filename.'_'.str_random(15).'.'. $file_ext;

        $client = new \Aws\S3\S3Client([
            'version' => 'latest',
            'region' => env('AWS_REGION'),
        ]);

        $result = $client->putObject([
            'ACL' => 'private',
            'Bucket' => env('AWS_BUCKET'), // REQUIRED
            'Key' => $path, // REQUIRED
            'ServerSideEncryption' => 'AES256',
            'SourceFile'=> $request->file('upload'),
            'StorageClass' => 'STANDARD',

        ]);
2 likes

Please or to participate in this conversation.