Search code examples
node.jscryptojs

What is the shortest hash with Nodejs crypto


What is the shortest string hash algo in the nodejs crypto module? Is there anything similar to crc32, which produces 8-character string , but unfortunately is not natively supported by crypto (I know that there are external modules, but I'm limited to built-in crypto). Hash collision probabilities is not important for my application (cache bursting).


Solution

  • You can use a XOF hash function like shake256 which supports the outputLength option (in bytes):

    const crypto = require("crypto");
    
    function createHash(data, len) {
        return crypto.createHash("shake256", { outputLength: len })
          .update(data)
          .digest("hex");
    }
    
    console.log(createHash("foo", 2))
    // 1af9
    console.log(createHash("foo", 8))
    // 1af97f7818a28edf