类型错误:不是一个缓冲Node.js加密,aws-sdk



我正在尝试为上传到amazon 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);
};

也遇到了同样的问题,下面是我的工作代码:

我使用下面的函数来计算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错误!

最新更新