node.js hash string?

后端 未结 11 2373
暗喜
暗喜 2020-12-02 03:49

I have a string that I want to hash. What\'s the easiest way to generate the hash in node.js?

The hash is for versioning, not security.

11条回答
  •  猫巷女王i
    2020-12-02 04:15

    sha256("string or binary");
    

    I experienced issue with other answer. I advice you to set encoding argument to binary to use the byte string and prevent different hash between Javascript (NodeJS) and other langage/service like Python, PHP, Github...

    If you don't use this code, you can get a different hash between NodeJS and Python...

    How to get the same hash that Python, PHP, Perl, Github (and prevent an issue) :

    NodeJS is hashing the UTF-8 representation of the string. Other languages (like Python, PHP or PERL...) are hashing the byte string.

    We can add binary argument to use the byte string.

    Code :

    const crypto = require("crypto");
    
    function sha256(data) {
        return crypto.createHash("sha256").update(data, "binary").digest("base64");
        //                                               ------  binary: hash the byte string
    }
    
    sha256("string or binary");
    

    Documentation:

    • crypto.createHash(algorithm[, options]): The algorithm is dependent on the available algorithms supported by the version of OpenSSL on the platform.
    • hash.digest([encoding]): The encoding can be 'hex', 'latin1' or 'base64'. (base 64 is less longer).

    You can get the issue with : sha256("\xac"), "\xd1", "\xb9", "\xe2", "\xbb", "\x93", etc...

    • Other languages (like PHP, Python, Perl...) and my solution with .update(data, "binary") :

        sha1("\xac") //39527c59247a39d18ad48b9947ea738396a3bc47
      
    • Nodejs by default (without binary) :

        sha1("\xac") //f50eb35d94f1d75480496e54f4b4a472a9148752
      

提交回复
热议问题