I am generating a token using something this
SET @Token = CAST(CRYPT_GEN_RANDOM(16) AS UNIQUEIDENTIFIER)
The token will be visible in the URL and should be unique.
Is a good idea use it?
The "GUID" you produce this way is not a true GUID, because the bits in the GUID reserved to indicate the variant and version of the GUID will also be random. In practice, most tools don't care about or look at the bits of a GUID at all, but it is just about conceivable that some system or future version will have a problem with a GUID bit pattern that isn't valid. A collision is not something you have to fear, given that the remaining bits are random on your end, but this is still ugly.
For (cryptographically) random GUIDs, you want a GUID with version 4, variant 1. Four bits indicate the version and two indicate variant 1, leaving 122 random bits, which should be plenty. Setting these bits correctly in T-SQL is not intuitive, but doable:
SELECT CONVERT(UNIQUEIDENTIFIER,
CRYPT_GEN_RANDOM(7) +
-- Set version = 4
CONVERT(BINARY(1), (CRYPT_GEN_RANDOM(1) & 15) | 64) +
-- Set variant = 1
CONVERT(BINARY(1), (CRYPT_GEN_RANDOM(1) & 63) | 128) +
CRYPT_GEN_RANDOM(7)
)
The position of the bits and the bytes is not intuitive, because SQL Server's encoding for them is weird.
Also consider the following alternatives:
NEWID() for a token where there is little to no concern that an attacker might guess the next value, or security will not be compromised if they do. Remember, this typically requires at least the ability to generate a block of GUIDs at will, and at worst access to the memory of the machine generating the GUIDs. The former can be rate limited and the latter means it's probably game over anyway.SELECT CONVERT(CHAR(32), CRYPT_GEN_RANDOM(16), 2) (convert back with SELECT CONVERT(BINARY(16), @s, 2)). A string is even easier to pass around than a GUID, so it's hard to see why you'd absolutely need a GUID here. You also get 6 whole bits of randomness back. A BINARY(16) column is the same size as UNIQUEIDENTIFIER, so storage is not the issue either. (But you may wish to consider using a string column anyway, to leave open room for new token formats in the future.)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With