【问题标题】:TypeError: Not a buffer node.js crypto, aws-sdkTypeError:不是缓冲区 node.js 加密,aws-sdk
【发布时间】:2014-10-15 09:02:13
【问题描述】:

我正在尝试创建一个用于上传到亚马逊 s3 的 S3 策略...但是在对策略进行编码时,我收到一个类型错误:不是缓冲区。我正在使用加密版本:0.0.3 和 aws-sdk 版本:2.0.0-rc.19

这之前有效,所以我认为它可能与 aws-sdk 的更新有关...

这里是代码。注释将显示错误发生的位置:

createS3Policy = function(contentType, callback) {
    var date = new Date();
    var s3Policy = {
        'expiration': getExpiryTime(),
        'conditions': [
            ['starts-with', '$key', 'shimmy-assets/'],
            {'bucket': S3_BUCKET},
            {'acl': 'public-read'},
            ['starts-with', '$Content-Type', contentType],
            {'success_action_status' : '201'}
        ]
    };

    // stringify and encode the policy
    var stringPolicy = JSON.stringify(s3Policy);
    console.log('string policy: ' + stringPolicy);
    var base64Policy = new Buffer(stringPolicy, 'utf-8').toString('base64');

    // sign the base64 encoded policy
    // NOT A BUFFER ERROR HERE
    var signature = crypto.createHmac('sha1', AWS_SECRET_KEY).update(new Buffer(base64Policy, 'utf-8')).digest('base64');          

    // build the results object
    var s3Credentials = {
        s3Policy: base64Policy,
        s3Signature: signature,
        AWSAccessKeyId: AWS_ACCESS_KEY
    };

    // send it back
    callback(s3Credentials);
};

【问题讨论】:

标签: node.js amazon-web-services amazon-s3


【解决方案1】:

刚刚遇到同样的问题,所以这是我的工作代码:

我使用下面的函数来计算hmac;

function hmac(algorithm, key, text, encoding) {
    var hmac = crypto.createHmac(algorithm, key);

    hmac.setEncoding(encoding);
    hmac.write(text);
    hmac.end();

    return hmac.read();
};

所以我的签名是:

var signature = hmac(
    'sha1',
    secretAccessKey, //Line A
    new Buffer(JSON.stringify(policy)).toString('base64')), //Line B
    'base64');

确保 A 行和 B 行没有未定义。即使 secretAccessKey 是一个字符串,它也会抛出 NOT A BUFFER 错误,以防它未定义!

【讨论】:

    猜你喜欢
    • 2014-06-26
    • 1970-01-01
    • 2019-01-17
    • 1970-01-01
    • 2019-09-10
    • 2017-07-22
    • 2013-06-15
    • 2019-07-15
    • 2023-03-04
    相关资源
    最近更新 更多