当前位置: 首页 > 知识库问答 >
问题:

PHP上的Amazon AWS S3浏览器上载(AWS签名版本4)

仇正平
2023-03-14

此文档似乎有问题:http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-authentication-HTTPPOST.html

我一丝不苟地遵循它,它似乎确实奏效了。我总是收到签名不匹配错误。v2授权仍然有效。让我想知道这是否是某种阿尔法阶段质量的产品。

下面是我的php代码。我试图模仿本页中的示例:http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-post-example.html

<?php

$secret = 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY';

$datenow = '20130806';
$region = 'us-east-1';
$service = 's3';
$terminator = 'aws4_request';
$policy = '{ "expiration": "2013-08-07T12:00:00.000Z",
  "conditions": [
    {"bucket": "examplebucket"},
    ["starts-with", "$key", "user/user1/"],
    {"acl": "public-read"},
    {"success_action_redirect": "http://examplebucket.s3.amazonaws.com/successful_upload.html"},
    ["starts-with", "$Content-Type", "image/"],
    {"x-amz-meta-uuid": "14365123651274"},
    ["starts-with", "$x-amz-meta-tag", ""],

    {"x-amz-credential": "AKIAIOSFODNN7EXAMPLE/'.$datenow.'/'.$region.'/'.$service.'/'.$terminator.'"},
    {"x-amz-algorithm": "AWS4-HMAC-SHA256"},
    {"x-amz-date": "'.$datenow.'T000000Z" }
  ]
}';

$policy64 = base64_encode($policy);

assert($policy64 == $policy64);
$targetPolicy64 = 'eyAiZXhwaXJhdGlvbiI6ICIyMDEzLTA4LTA3VDEyOjAwOjAwLjAwMFoiLA0KICAiY29uZGl0aW9ucyI6IFsNCiAgICB7ImJ1Y2tldCI6ICJleGFtcGxlYnVja2V0In0sDQogICAgWyJzdGFydHMtd2l0aCIsICIka2V5IiwgInVzZXIvdXNlcjEvIl0sDQogICAgeyJhY2wiOiAicHVibGljLXJlYWQifSwNCiAgICB7InN1Y2Nlc3NfYWN0aW9uX3JlZGlyZWN0IjogImh0dHA6Ly9leGFtcGxlYnVja2V0LnMzLmFtYXpvbmF3cy5jb20vc3VjY2Vzc2Z1bF91cGxvYWQuaHRtbCJ9LA0KICAgIFsic3RhcnRzLXdpdGgiLCAiJENvbnRlbnQtVHlwZSIsICJpbWFnZS8iXSwNCiAgICB7IngtYW16LW1ldGEtdXVpZCI6ICIxNDM2NTEyMzY1MTI3NCJ9LA0KICAgIFsic3RhcnRzLXdpdGgiLCAiJHgtYW16LW1ldGEtdGFnIiwgIiJdLA0KDQogICAgeyJ4LWFtei1jcmVkZW50aWFsIjogIkFLSUFJT1NGT0ROTjdFWEFNUExFLzIwMTMwODA2L3VzLWVhc3QtMS9zMy9hd3M0X3JlcXVlc3QifSwNCiAgICB7IngtYW16LWFsZ29yaXRobSI6ICJBV1M0LUhNQUMtU0hBMjU2In0sDQogICAgeyJ4LWFtei1kYXRlIjogIjIwMTMwODA2VDAwMDAwMFoiIH0NCiAgXQ0KfQ==';
// echo base64_decode($targetPolicy64);
// echo $policy64."\n".$targetPolicy64;

assert($policy64 == $targetPolicy64);

// At this point everything seems to work well. Converting the policy 
// to base64 resulted in exactly the same string with example. 
// The problem, however, happens when calculating the signature, 
// as shown below:

$targetSignature = '21496b44de44ccb73d545f1a995c68214c9cb0d41c45a17a5daeec0b1a6db047';
$signature = '';

$hash1 = hash_hmac(
    'sha256',
    $datenow,
    "AWS4".$secret,
    true
);

$hash2 = hash_hmac(
    'sha256',
    $region,
    $hash1,
    true
);

$hash3 = hash_hmac(
    'sha256',
    $service,
    $hash2,
    true
);

$signingKey = hash_hmac(
    'sha256',
    $terminator,
    $hash3,
    true
);

$signature = base64_encode(hash_hmac(
    'sha256',
    $policy64,
    $signingKey,
    true
));


echo $signature."\n".$targetSignature;
// This assertion never passed.
assert($signature == $targetSignature);

我认为这是示例的问题所在,所以我尝试使用完全相同的方法创建一个示例浏览器上载页面,但也不起作用。

在这里运行签名签名代码:PHPhash_hmac不匹配AWS签名4示例但是,工作,所以我怀疑问题是在签名创建期间,还是?

请帮助,任何人。

共有1个答案

陆正德
2023-03-14
<?php

// Fill These In!
define('S3_BUCKET', '');
define('S3_KEY',    '');
define('S3_SECRET', '');
define('S3_REGION', '');        // S3 region name: http://amzn.to/1FtPG6r
define('S3_ACL',    'private'); // File permissions: http://amzn.to/18s9Gv7
// Stop Here

$algorithm = "AWS4-HMAC-SHA256";
$service = "s3";
$date = gmdate('Ymd\THis\Z');
$shortDate = gmdate('Ymd');
$requestType = "aws4_request";
$expires = '86400'; // 24 Hours
$successStatus = '201';

$scope = [
    S3_KEY,
    $shortDate,
    S3_REGION,
    $service,
    $requestType
];
$credentials = implode('/', $scope);

$policy = [
    'expiration' => gmdate('Y-m-d\TG:i:s\Z', strtotime('+6 hours')),
    'conditions' => [
        ['bucket' => S3_BUCKET],
        ['acl' => S3_ACL],
        [
            'starts-with',
            '$key',
            ''
        ],
        ['success_action_status' => $successStatus],
        ['x-amz-credential' => $credentials],
        ['x-amz-algorithm' => $algorithm],
        ['x-amz-date' => $date],
        ['x-amz-expires' => $expires],
    ]
];
$base64Policy = base64_encode(json_encode($policy));

// Signing Keys
$dateKey = hash_hmac('sha256', $shortDate, 'AWS4' . S3_SECRET, true);
$dateRegionKey = hash_hmac('sha256', S3_REGION, $dateKey, true);
$dateRegionServiceKey = hash_hmac('sha256', $service, $dateRegionKey, true);
$signingKey = hash_hmac('sha256', $requestType, $dateRegionServiceKey, true);

// Signature
$signature = hash_hmac('sha256', $base64Policy, $signingKey);

?>

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Direct Upload Example</title>
        <style>
            .progress {
                position: relative;
                width: 100%;
                height: 15px;
                background: #C7DA9F;
                border-radius: 10px;
                overflow: hidden;
            }
            .bar {
                position: absolute;
                top: 0; left: 0;
                width: 0; height: 15px;
                background: #85C220;
            }
            .bar.red { background: tomato; }
        </style>
    </head>
    <body>

        <!-- Direct Upload to S3 -->
        <!-- URL prefix (//) means either HTTP or HTTPS (depending on which is being currently used) -->
        <form action="//<?php echo S3_BUCKET . "." . $service . "-" . S3_REGION; ?>.amazonaws.com"
              method="POST"
              enctype="multipart/form-data"
              class="direct-upload">

            <!-- Note: Order of these is Important -->
            <input type="hidden" name="key" value="${filename}">
            <input type="hidden" name="acl" value="<?php echo S3_ACL; ?>">
            <input type="hidden" name="success_action_status" value="<?php echo $successStatus; ?>">
            <input type="hidden" name="policy" value="<?php echo $base64Policy; ?>">

            <input type="hidden" name="X-amz-algorithm" value="<?php echo $algorithm; ?>">
            <input type="hidden" name="X-amz-credential" value="<?php echo $credentials; ?>">
            <input type="hidden" name="X-amz-date" value="<?php echo $date; ?>">
            <input type="hidden" name="X-amz-expires" value="<?php echo $expires; ?>">
            <input type="hidden" name="X-amz-signature" value="<?php echo $signature; ?>">

            <input type="file" name="file">

            <!-- Progress Bar to show upload completion percentage -->
            <div class="progress"><div class="bar"></div></div>

        </form>

        <!-- Used to Track Upload within our App -->
        <form action="server.php" method="POST">
            <input type="hidden" name="upload_original_name" id="upload_original_name">
            <label for="upload_custom_name">Name:</label><br />
            <input type="text" name="upload_custom_name" id="upload_custom_name"><br />
            <input type="submit" value="Save"/>
        </form>

        <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
        <script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
        <script src="fileupload/jquery.fileupload.js"></script>
        <script>
            $(document).ready(function () {
                $('.direct-upload').each(function () {
                    var form = $(this);
                    form.fileupload({
                        url: form.attr('action'),
                        type: 'POST',
                        datatype: 'xml',
                        add: function (event, data) {

                            // Message on unLoad.
                            // Shows 'Are you sure you want to leave message', just to confirm.
                            window.onbeforeunload = function () {
                                return 'You have unsaved changes.';
                            };

                            // Actually submit to form, sending the data.
                            data.submit();
                        },
                        progress: function (e, data) {
                            // This is what makes everything really cool, thanks to that callback
                            // you can now update the progress bar based on the upload progress.
                            var percent = Math.round((data.loaded / data.total) * 100);
                            $('.bar').css('width', percent + '%');
                        },
                        fail: function (e, data) {
                            // Remove the 'unsaved changes' message.
                            window.onbeforeunload = null;
                            $('.bar').css('width', '100%').addClass('red');
                        },
                        done: function (event, data) {
                            window.onbeforeunload = null;
                            // Fill the name field with the file's name.
                            $('#upload_original_name').val(data.originalFiles[0].name);
                            $('#upload_custom_name').val(data.originalFiles[0].name);
                        }
                    });
                });
            });
        </script>
    </body>
</html>

(https://www.designedbyaturtle.co.uk/2015/direct-upload-to-s3-using-aws-signature-v4-php/)

为我工作

 类似资料:
  • 我在一个网站上工作,用户应该能够上传视频文件到AWS。为了避免不必要的流量,我希望用户直接上传到AWS(而不是通过API服务器)。为了不在JavaScript中公开我的密钥,我正在尝试在API中生成一个签名。但是,当我尝试上传时,它确实会告诉我签名不匹配。 对于签名生成,我一直在使用http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-Using

  • 我需要直接从浏览器上传一个文件到S3。开始时,我创建了一个脚本,该脚本正在工作,但为了授权,我需要将我的凭据accessKeyId和secretAccessKey放入其中,这是不安全的。 我发现我可以使用“授权签名”进行授权 这看起来不错,但我找不到在upload()方法中将此授权头放在请求的何处。 我的授权标头示例: 授权:AWS4-HMAC-SHA256凭证=/20151016//s3/AWS

  • 我试图上传一个图像使用预先签名的网址 我得到了一个类似的url https://s3.eu-west-1.amazonaws.com/bucket/folder/access.JPG?AWSAccessKeyId=xxxx 我已经尝试上传文件与内容类型图像/jpg,多部分/表单数据。 尝试生成没有文件类型和上传的网址。 尝试了放后法 但似乎什么都不管用 错误总是: 我们计算的请求签名与您提供的签名

  • 我们正在构建基于java的GUI以将非常大的文件上传到S3桶。我们从API获取预先签名的URL,然后点击此URL上传我们的文件。 现在,由于文件大小非常大(10 GB),我们希望显示用户数据传输统计数据(例如,传输了多少数据、传输速率等)。 重要提示-我们没有AWS ID-KEY来访问bucket,所以我们不能使用AWS SDK。 任何一个指针都会很有帮助,我们将不胜感激。

  • 我在Ubuntu Server中设置了一个Selenium Grid,在Ubuntu Desktop中设置了一个Hub,在Ubuntu Desktop中设置了一个Node。Node上的GoogleChrome版本是。我创建会话的python代码是 但是当我传递时,它会出错 硒。常见的例外情况。WebDriverException:消息:转发新会话时出错,找不到:功能{browserName:chr

  • 本文向大家介绍javascript 获取浏览器版本,包括了javascript 获取浏览器版本的使用技巧和注意事项,需要的朋友参考一下 工作中需要通过JS去获取当前使用的浏览器的名字以及版本号,网上大堆资料都有一个关键词是 navigator.appName,但是这个方法获取的浏览器的名字只有两种要么是IE要么就是Netscap,倒是可以用来判断是否使用了IE,但是我想获取具体的浏览器产品名字比如