Last active
March 2, 2019 04:42
-
-
Save kspearrin/0a2599d8ebf6532b3f8a8db133724d58 to your computer and use it in GitHub Desktop.
T-SQL Cryptographically Secure Random String Function using CRYPT_GEN_RANDOM()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Helper view so that you can call CRYPT_GEN_RANDOM in your function | |
CREATE VIEW [dbo].[SecureRandomBytes] | |
AS | |
SELECT [RandBytes] = CRYPT_GEN_RANDOM(2) | |
GO | |
-- Function for generating secure random string | |
CREATE FUNCTION [dbo].[SecureRandomString](@sLength tinyint) | |
RETURNS varchar(200) | |
AS | |
BEGIN | |
declare @randomString varchar(200) | |
declare @counter tinyint | |
declare @nextChar char(1) | |
declare @rnd as float | |
declare @bytes binary(2) | |
set @counter = 1 | |
set @randomString = '' | |
while @counter <= @sLength | |
begin | |
select @bytes = [RandBytes] from [dbo].[SecureRandomBytes] | |
select @rnd = cast(cast(cast(@bytes as int) as float) / 65535 as float) | |
select @nextChar = char(48 + convert(int, (122-48+1) * @rnd)) | |
if ascii(@nextChar) not in (58,59,60,61,62,63,64,91,92,93,94,95,96) | |
begin | |
select @randomString = @randomString + @nextChar | |
set @counter = @counter + 1 | |
end | |
end | |
return @randomString | |
END | |
GO | |
-- Use it | |
SELECT [dbo].[SecureRandomString](10) -- ywqNromLZh | |
GO | |
SELECT [dbo].[SecureRandomString](20) -- kgJO75bhuCsomYygXlhD | |
GO | |
SELECT [dbo].[SecureRandomString](30) -- llBtfrhPk0MjaZGtLXPKLhopf9rrjG | |
GO | |
-- Clean up | |
DROP VIEW [dbo].[SecureRandomBytes] | |
GO | |
DROP FUNCTION [dbo].[SecureRandomString] | |
GO |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment