Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What encoding should I use to properly generate an ETag with crypto in nodeJS?

In my nodeJS app, I'd like to generate ETags for all the content that I return to the client. I need the ETag to be based off the actual content of the file instead of the date, so that the same file across different node processes has the same ETag.

Right now, I am doing the following:

var fs = require('fs'), crypto = require('crypto');
fs.readFile(pathToFile, function(err, buf){
  var eTag = crypto.createHash('md5').update(buf).digest('hex');
  res.writeHead(200, {'ETag': '"' + eTag + '"','Content-Type':contentType});
  res.end(buf);
});

I am not sure what encodings I should be using for the different crypto functions in order to have a proper system in place. Should I be using something other than hex? Should I get the fs.readFile call to return a hex encoded buffer? If so, will doing so impact the content returned to users?

Best, and Thanks,
Sami

like image 798
thisissami Avatar asked Nov 10 '12 23:11

thisissami


People also ask

How is ETag generated?

Generating ETag ValueIt can be created and updated manually or can be auto-generated. Common methods of its auto-generation include using a hash of the resource's content or just a hash of the last modification timestamp. The generated hash should be collision-free.

What is crypto in node JS How do you cipher the secure information in node JS?

Crypto is a module in Node. js which deals with an algorithm that performs data encryption and decryption. This is used for security purpose like user authentication where storing the password in Database in the encrypted form. Crypto module provides set of classes like hash, HMAC, cipher, decipher, sign, and verify.

What is ETag in node JS?

The ETag (or entity tag) HTTP response header is an identifier for a specific version of a resource.


1 Answers

You're doing it fine. There is no reason to encode the file in any special format, and using hex for the output is pretty standard. The requirements, loosely speaking, are:

  • the same document should always return the same ETag
  • any changes in the document causes a change in ETag
  • the ETag data should fit neatly into an HTTP header
like image 176
slashingweapon Avatar answered Oct 21 '22 08:10

slashingweapon