简体   繁体   中英

How to have a Javascript client create a secure UUID?

Is it possible for a Javascript client create a UUID that cannot be faked?

For example, suppose one of the solutions from Create GUID / UUID in JavaScript? were used to generate a UUID and send a create request with UUID to the server. Is it possible for the server to check that the UUID was indeed created by the Javascript function and not by some other function?

One idea is to use a checksum, but the UUID generation and checksum code would be visible to a "hacker". They could simply modify the Javascript function and then add the checksum.

So, are there any good solutions to this problem?

You shouldn't care about who created the UUID. The server should only check if the UUID sent by the client respects the UUID format and perhaps check if somehow the same UUID was used already (this depends on your needs).

That is unless your UUID value is used as a secret (eg an activation number). In this case, the value shouldn't be generated client-side and the server should keep track of the values it generated.

You can do some basic sanity checks like length or format, but what you are actually asking is "Given a number can I check that it was generated by a particular random number generator?". If the random number generator is truly random then the answer has to be "no", since if I can back-track from the answer to the function that easily then it's not very random.

Combining the IP address with the User-Agent from the front-end:

const getUUID = (
    service='https://api.ipify.org/?format=json',
    key='ip'
) => { 
    return new Promise(
        (resolve, reject) => {
          fetch(service)
          .then((r) => r.json())
          .then((j) => {
              let r = /\D+/g
              let h = String(
                  window.navigator.userAgent.replace(r, ''
                  ) * j[key].replace(r, '')
              ).replace(r, '').replace('0', '').split('')
              let g = () => Math.floor(h.shift() * 0x10000)
              resolve(
              g() + g() + '-' + g() + '-' + g() + '-' + g() + '-' + g() + g() + g())
          }).catch((e) => reject('failed to create UUID'))
        }
    )
}

// Excute it
getUUID().then((d) => console.log(d)).catch((e) => console.warn(e))

Validating it from the back-end by getting the requesting IP address, User-Agent from headers and applying the same logic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM