我正在尝试为上传到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);
};
答案 0 :(得分:2)
刚刚遇到同样的问题,所以这是我的工作代码:
我使用以下函数计算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
错误,以防它未定义!