Created
August 15, 2018 05:48
-
-
Save radzserg/9675e6c11a3c552598551e9780646403 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| namespace vendori\helpers; | |
| use Yii; | |
| use CJSON; | |
| class S3DirectUpload | |
| { | |
| public static function signData($fileName) | |
| { | |
| $resourceManager = Yii::app()->resourceManager; | |
| $bucket = $resourceManager->bucket; | |
| $algorithm = 'AWS4-HMAC-SHA256'; | |
| $expiration = gmdate('Y-m-d\TG:i:s\Z', strtotime('+1 hour')); | |
| $date = gmdate("Ymd\THis\Z"); | |
| $key = $resourceManager->basePath . 'document/' . md5($fileName . mt_rand()) . "/{$fileName}"; | |
| $credentials = $resourceManager->key . '/' . date('Ymd') . '/' . $resourceManager->region . '/s3/aws4_request'; | |
| $acl = 'private'; | |
| $policy = [ | |
| 'expiration' => $expiration, | |
| 'conditions' => [ | |
| ['bucket' => $bucket], | |
| //['starts-with', 'document/'], | |
| ['starts-with', '$key', ''], | |
| ['starts-with', '$Content-Type', ''], | |
| ['acl' => $acl], | |
| ['success_action_status' => '201'], | |
| // ['success_action_redirect' => $redirectAction], | |
| ['x-amz-credential' => $credentials], | |
| ['x-amz-algorithm' => $algorithm], | |
| ['x-amz-date' => $date], | |
| ['x-amz-server-side-encryption' => 'AES256'] | |
| ] | |
| ]; | |
| $encodedPolicy = base64_encode(CJSON::encode($policy)); | |
| return [ | |
| 'acl' => $acl, | |
| 'key' => $key, | |
| //'success_action_redirect' => $redirectAction, | |
| 'policy' => $encodedPolicy, | |
| 'x-amz-algorithm' => $algorithm, | |
| 'x-amz-credential' => $credentials, | |
| 'x-amz-date' => $date, | |
| 'x-amz-server-side-encryption' => 'AES256', | |
| 'x-amz-signature' => S3DirectUpload::generateSignature($encodedPolicy) | |
| ]; | |
| } | |
| private static function generateSignature($encodedPolicy) | |
| { | |
| $resourceManager = Yii::app()->resourceManager; | |
| $dateKey = hash_hmac('sha256', date('Ymd'), "AWS4" . $resourceManager->secret, true); | |
| $dateRegionKey = hash_hmac('sha256', $resourceManager->region, $dateKey, true); | |
| $dateRegionServiceKey = hash_hmac('sha256', 's3', $dateRegionKey, true); | |
| $signingKey = hash_hmac('sha256', 'aws4_request', $dateRegionServiceKey, true); | |
| return hash_hmac('sha256', $encodedPolicy, $signingKey); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment