使用NodeJS为Google Cloud Storage创建签名的URL [英] Creating signed URLs for Google Cloud Storage using NodeJS
本文介绍了使用NodeJS为Google Cloud Storage创建签名的URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试为Google Cloud Storage中的私人存储文件创建签名;这样我就可以分发一个限时链接.
I'm trying to create a signature for a privately stored file in Google Cloud Storage; so that I can distribute a time-limited link.
目前正在这样做,并且签名太短了……我要去哪里错了?
Currently doing this and it makes a signature that's too short ... where am I going wrong?
var crypto = require("crypto");
var ttl = new Date().getTime() + 3600;
var id = 'the_target_file.txt';
var bucketName = 'bucket_name';
var POLICY_JSON = "GET\n" + "\n" + "\n" + ttl + "\n" + '/' + bucketName + '/' + id;
// stringify and encode the policy
var stringPolicy = JSON.stringify(POLICY_JSON);
var base64Policy = Buffer(stringPolicy, "utf-8").toString("base64");
// sign the base64 encoded policy
var privateKey = "MY_PRIVATE_KEY";
var sha256 = crypto.createHmac("sha256", privateKey);
var signature = sha256.update(new Buffer(base64Policy, "utf-8")).digest("base64");
console.log ( signature );
推荐答案
意识到我做错了...我在对策略字符串进行哈希处理而不是对其进行签名. 现在,下面的代码为我提供了正确的输出.
Realised what I was doing wrong ... I was hashing the policy string instead of signing it. The below code now gives me the correct output.
var crypto = require("crypto");
var fs = require("fs");
var expiry = new Date().getTime() + 3600;
var key = 'the_target_file';
var bucketName = 'bucket_name';
var accessId = 'my_access_id';
var stringPolicy = "GET\n" + "\n" + "\n" + expiry + "\n" + '/' + bucketName + '/' + key;
var privateKey = fs.readFileSync("gcs.pem","utf8");
var signature = encodeURIComponent(crypto.createSign('sha256').update(stringPolicy).sign(privateKey,"base64"));
var signedUrl = "https://" + bucketName + ".commondatastorage.googleapis.com/" + key +"?GoogleAccessId=" + accessId + "&Expires=" + expiry + "&Signature=" + signature;
console.log(signedUrl);
出于完整性考虑,...这是一个执行相同功能的PHP版本,我用来检查结果
For completeness ... here is a PHP version that does the same thing, which I used to check my results
$expiry = time() + 3600;
$key = 'the_target_file';
$bucketName = 'bucket_name';
$accessId = 'my_access_id';
$stringPolicy = "GET\n\n\n".$expiry."\n/".$bucketName."/".$key;
$fp = fopen('gcs.pem', 'r');
$priv_key = fread($fp, 8192);
fclose($fp);
$pkeyid = openssl_get_privatekey($priv_key,"password");
if (openssl_sign( $stringPolicy, $signature, $pkeyid, 'sha256' )) {
$signature = urlencode( base64_encode( $signature ) );
echo 'https://'.$bucketName.'.commondatastorage.googleapis.com/'.
$key.'?GoogleAccessId='.$accessId.'&Expires='.$expiry.'&Signature='.$signature;
}
这篇关于使用NodeJS为Google Cloud Storage创建签名的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文