In the development, often need to use random strings, or hash strings, node environment can be very convenient to use the crypto module, in the front-end environment should be how to use it?

  1. Use Math. The random

    Math.random() returns a floating-point number before 0-1

    From this property, we can generate a pseudorandom number, which is then converted to a hex string

    Math.random().toString(36).slice(2)
    Copy the code

    Random string generated

    h4pl2m80b2
    Copy the code

    If you want to generate only contains a string of hexadecimal characters, the toString parameters can be changed to 16 can attach MDN about Number. In the prototype. ToString ([radix])

    Radix: Specifies the radix (from 2 to 36) to be used for numeric to string conversions. If the RADIX parameter is not specified, the default value is 10.

    That means you can convert from binary to 36; Note that the size and length of the random number generated by math. random are not controllable, so the length of the random string generated is not controllable. Use Crypto objects if you want to generate strings of a specific length, as shown below.

  2. Use Windows. Crypto

    Crypto objects are natively supported in browsers, but unlike the Crypto in Node.js, we need to use the getRandomValues() method, which accepts TypeArray, Usually just use Uint8Array, the length of the generated string can be controlled by the length of the TypeArray, and then use crypto.getrandomValues () to fill in the random number

    Array.prototype.map.call(window.crypto.getRandomValues(new Uint8Array(16)), (item) = > item.toString(16)).join(' ')
    Copy the code

    Random string generated

    7f130fad88e443d12d9699573a3e12
    Copy the code

More content

Front-end development to the full stack, the current technical stack is Node.js, Python, daily research C, C++ and Rust, diligently eat system development and network design ~

Never too old to learn, never too old to write

Come on, workers