我正在尝试使用表单使用Meteor将文件上传到s3存储桶。我正在关注这个亚马逊article。在"签署您的S3 POST表格",接近结尾,我需要将字符串编码为base64,但我一直无法找到这样做的方法。谁能告诉我怎么做?请注意,首先需要对字符串进行编码然后进行签名。这是它在python中完成的方式:
import base64
import hmac, hashlib
policy = base64.b64encode(policy_document)
signature = base64.b64encode(hmac.new(AWS_SECRET_ACCESS_KEY, policy, hashlib.sha1).digest())
答案 0 :(得分:9)
你可以在没有NodeJS加密模块的情况下做到这一点,创建一个看起来有点像打破方向盘的包给我,所以我想出了这个:
if (Meteor.isServer) {
Meteor.methods({
'base64Encode':function(unencoded) {
return new Buffer(unencoded || '').toString('base64');
},
'base64Decode':function(encoded) {
return new Buffer(encoded || '', 'base64').toString('utf8');
},
'base64UrlEncode':function(unencoded) {
var encoded = Meteor.call('base64Encode',unencoded);
return encoded.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
},
'base64UrlDecode':function(encoded) {
encoded = encoded.replace(/-/g, '+').replace(/_/g, '/');
while (encoded.length % 4)
encoded += '=';
return Meteor.call('base64Decode',encoded);
}
console.log(Meteor.call('base64Encode','abc'));
});
这是基于John Hurliman在https://gist.github.com/jhurliman/1250118找到的base64.js注意,这将像服务器上的魅力一样工作,但是为了将它移植到客户端,您已经使用存储的回调函数调用方法结果作为会话变量。
答案 1 :(得分:2)
您需要NodeJS加密模块来执行这些任务。
首先在meteor项目的根目录下创建一个“packages”目录,然后创建一个“my-package”目录。 在其中,您需要两个文件:“package.js”和“my-package.js”。
package.js应如下所示:
Package.describe({
summary:"MyPackage doing amazing stuff with AWS."
});
Package.on_use(function(api){
// add your package file to the server app
api.add_files("my-package.js","server");
// what we export outside of the package
// (this is important : packages have their own scope !)
api.export("MyPackage","server");
});
my-package.js应如下所示:
var crypto=Npm.require("crypto");
MyPackage={
myFunction:function(arguments){
// here you can use crypto functions !
}
};
您可能需要的功能是crypto.createHmac。 以下是我在base64中编码JSON安全策略的示例代码,然后使用它在我自己的应用程序中生成安全签名:
encodePolicy:function(jsonPolicy){
// stringify the policy, store it in a NodeJS Buffer object
var buffer=new Buffer(JSON.stringify(jsonPolicy));
// convert it to base64
var policy=buffer.toString("base64");
// replace "/" and "+" so that it is URL-safe.
return policy.replace(/\//g,"_").replace(/\+/g,"-");
},
encodeSignature:function(policy){
var hmac=crypto.createHmac("sha256",APP_SECRET);
hmac.update(policy);
return hmac.digest("hex");
}
这将允许您在Meteor应用程序的服务器端调用MyPackage.myFunction。 最后但不是最后,不要忘记“meteor add my-package”以便使用它!
答案 2 :(得分:2)
您可以使用meteor-crypto-base64包。
CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse('Hello, World!'));
//"SGVsbG8sIFdvcmxkIQ=="