Skip to content

Instantly share code, notes, and snippets.

@akirattii
Created April 20, 2018 06:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akirattii/258b5ac39ec18b215f9c900ee62da6b1 to your computer and use it in GitHub Desktop.
Save akirattii/258b5ac39ec18b215f9c900ee62da6b1 to your computer and use it in GitHub Desktop.
NodeJS: How to create a shorthash, but NOT smart way!
/**
* Create a short hash to **roughly** specify the accessed user's identity.
* The generated hash could be immutable only when either user's IP address and access date are same.
*
* CAUTION:
* NEVER use it for generate unique ID, it could NOT be unique!
*/
const crypto = require("crypto");
var text = "2018/04/01 xxx.xxx.xxx.xxx"; // "<Date> <IP>"
console.log(shorthash(text)); // "TVBXCl"
var text = "2018/04/01 yyy.yyy.yyy.yyy"; // "<Date> <IP>"
console.log(shorthash(text)); // "vG0Nto"
function shorthash(s, len = 6) {
const b64 = crypto.createHash("md5").update(s, "binary").digest("base64");
return b64.substring(0, len);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment