I am trying to include some crypto.js libraries in a meteor js app (meteor version 0.6.4.1).
When I copy and paste the contents into the server/main.js file it works fine, but this makes it very un-readable.
When I put the libraries in separate files in the server directory (I also tried placing them in the lib directory) I get the error ReferenceError: CryptoJS is not defined
.
gist of server/main.js:
Meteor.methods({
encrypt:function(bundleID){
return CryptoJS.HmacSHA256(string, 'something');
}
});
I also tried changing the first line of the hmac-sha256.js file from
var CryptoJS=CryptoJS||function(h,s){...
to:
CryptoJS=CryptoJS||function(h,s){...
to make it global, but this also did not work. How do I include this library properly?
I am trying to include some crypto.js libraries in a meteor js app (meteor version 0.6.4.1).
When I copy and paste the contents into the server/main.js file it works fine, but this makes it very un-readable.
When I put the libraries in separate files in the server directory (I also tried placing them in the lib directory) I get the error ReferenceError: CryptoJS is not defined
.
gist of server/main.js:
Meteor.methods({
encrypt:function(bundleID){
return CryptoJS.HmacSHA256(string, 'something');
}
});
I also tried changing the first line of the hmac-sha256.js file from
var CryptoJS=CryptoJS||function(h,s){...
to:
CryptoJS=CryptoJS||function(h,s){...
to make it global, but this also did not work. How do I include this library properly?
In your application dir create folder 'packages/cryptojs' and put there files:
packages / cryptojs / package.js:
Package.describe({
summary: "CryptoJS"
});
Package.on_use(function (api, where) {
api.add_files(['hmac-sha256.js'], ['client','server']);
api.add_files(['enc-base64-min.js'], ['client','server']);
});
You need to modify hmac-sha256.js by changing beginning of line 7 from:
var CryptoJS=CryptoJS||function(h,s){
to:
CryptoJS=function(h,s){
After that, you can use it:
var hash = CryptoJS.HmacSHA256("Message", "secret");
var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
console.log(hashInBase64)
Example source
I followed as parhelium's guide, but still not work, then I found new way to fix this issue: Just replace line 7 in hmac-sha512.js to this one to globalize CryptoJS object:
this.CryptoJS=this.CryptoJS
Fix the same for other cryptojs. To use with Base64, you must make sure the base64.js is loaded after other libraries.
The reason this is happening is due to the variable scoping in meteor. Try putting the cryptojs library files in /server/patibility
. This way the cryptojs library can be accessed in other files.
You could also get it working without putting it in /patibility
by removing the var
used in the cryptojs source files. The thing is if you do this its harder to keep the files up to date.