HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlMajor

Securely generate a UNIQUEIDENTIFIER in SQL Server

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
uniqueidentifiersqlgenerateserversecurely

Problem

I intend to be using a UNIQUEIDENTIFIER as an access key that users can use to access certain data. The key will act as a password in that sense.

I need to generate multiple such identifiers as part of an INSERT...SELECT statement. For architectural reasons I want to generate the identifiers server-side in this case.

How can I generate a securely random UNIQUEIDENTIFIER? Note, that NEWID would not be random enough as it does not promise any security properties at all. I'm looking for the SQL Server equivalent of System.Security.Cryptography.RandomNumberGenerator because I need unguessable IDs. Anything based on CHECKSUM, RAND or GETUTCDATE would also not qualify.

Solution

SELECT CAST(CRYPT_GEN_RANDOM(16) AS UNIQUEIDENTIFIER)


Should do the trick I would have thought.

CRYPT_GEN_RANDOM


Returns a cryptographic random number generated by the Crypto API
(CAPI).

Code Snippets

SELECT CAST(CRYPT_GEN_RANDOM(16) AS UNIQUEIDENTIFIER)

Context

StackExchange Database Administrators Q#39239, answer score: 27

Revisions (0)

No revisions yet.