How to generate a RNGCryptoServiceProvider-like number in TSQL

▼魔方 西西 提交于 2020-02-25 05:50:19

问题


Does anyone know of a way to generate a RNGCryptoServiceProvider-like random number in T-SQL without having to register any .NET Assemblies?


回答1:


SELECT CHECKSUM(NEWID()) gives you a 32 signed integer based on GUIDs. You can use this as base: it's pretty much the best SQL way

You can use it to seed RAND (because RAND is the same for all rows in a single select.

SELECT RAND(CHECKSUM(NEWID()))

A signed 64 bit integer:

SELECT CAST(CHECKSUM(NEWID()) as bigint) * CAST(CHECKSUM(NEWID()) as bigint)

With some playing around you could cast and/or concatenate to get binary("multiples of 4") etc to build up a byte array... I've not used the RAND thingy though to emulate directly




回答2:


If you have to generate cryptographycally secure random numbers (like salts for hashing) then you should use the CLR functions. Checksum, guids and the like are not secure for crypto operations.

The easiest solution is to use a CLR scalar function that invokes RNGCryptoServiceProvider.

Note that many of the SQL Server crpto functions like EncryptByKey are already salting the input using cryptographically secure generated salts (except for EncryptByKey on RC4 algorithm, that is broken in SQL).



来源:https://stackoverflow.com/questions/1521835/how-to-generate-a-rngcryptoserviceprovider-like-number-in-tsql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!