How to generate random SHA1 hash to use as ID in node.js?

后端 未结 4 1619
有刺的猬
有刺的猬 2020-12-04 04:45

I am using this line to generate a sha1 id for node.js:

crypto.createHash(\'sha1\').digest(\'hex\');

The problem is that it\'s returning th

4条回答
  •  不思量自难忘°
    2020-12-04 05:20

    Do it in the browser, too !

    EDIT: this didn't really fit into the flow of my previous answer. I'm leaving it here as a second answer for people that might be looking to do this in the browser.

    You can do this client side in modern browsers, if you'd like

    // str byteToHex(uint8 byte)
    //   converts a single byte to a hex string 
    function byteToHex(byte) {
      return ('0' + byte.toString(16)).slice(-2);
    }
    
    // str generateId(int len);
    //   len - must be an even number (default: 40)
    function generateId(len = 40) {
      var arr = new Uint8Array(len / 2);
      window.crypto.getRandomValues(arr);
      return Array.from(arr, byteToHex).join("");
    }
    
    console.log(generateId())
    // "1e6ef8d5c851a3b5c5ad78f96dd086e4a77da800"
    
    console.log(generateId(20))
    // "d2180620d8f781178840"

    Browser requirements

    Browser    Minimum Version
    --------------------------
    Chrome     11.0
    Firefox    21.0
    IE         11.0
    Opera      15.0
    Safari     5.1
    

提交回复
热议问题