Last active
May 26, 2016 14:33
-
-
Save shaisachs/8625fab97bf8dc4d981196c3b5e148c7 to your computer and use it in GitHub Desktop.
UrlTokenEncode a GUID
This file contains 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
drop function dbo.convertPaddingToCount; | |
go | |
create function dbo.convertPaddingToCount(@input varchar(1000)) | |
returns varchar(1000) | |
as | |
begin | |
if (LEN(@input) < 1) | |
return ''; | |
declare @answer varchar(1000); | |
declare @count int; | |
declare @ind int; | |
set @count = 0; | |
set @ind = LEN(@input); | |
while @ind >= 1 | |
begin | |
if SUBSTRING(@input, @ind, 1) = '=' | |
begin | |
set @count = @count + 1; | |
set @ind = @ind - 1; | |
end | |
else | |
begin | |
break | |
end | |
end | |
if (@count > 0) | |
begin | |
set @answer = SUBSTRING(@input, 1, LEN(@input) - @count) + CONVERT(varchar(5), @count) | |
end | |
else | |
begin | |
set @answer = @input; | |
end | |
return @answer; | |
end; | |
go | |
drop function dbo.urlTokenEncode; | |
go | |
-- algorithm reverses the steps at http://stackoverflow.com/questions/21657024/is-there-a-java-equivalent-for-cs-httpserverutility-urltokendecode | |
-- and ports to T-SQL, obviously | |
create function dbo.urlTokenEncode(@input uniqueidentifier) | |
returns varchar(3000) | |
as | |
begin | |
declare @answer varchar(3000); | |
declare @encoded varchar(3000); | |
-- technique due to http://stackoverflow.com/questions/5082345/base64-encoding-in-sql-server-2005-t-sql | |
SELECT @encoded = | |
CAST(N'' AS XML).value( | |
'xs:base64Binary(xs:hexBinary(sql:column("bin")))' | |
, 'VARCHAR(MAX)' | |
) | |
FROM ( | |
SELECT CAST(@input AS VARBINARY(MAX)) AS bin | |
) AS bin_sql_server_temp; | |
set @answer = @encoded; | |
-- convert padding characters to a count | |
set @answer = dbo.convertPaddingToCount(@encoded); | |
-- transform url-unsafe characters to url-safe | |
set @answer = REPLACE(@answer, '+', '-'); | |
set @answer = REPLACE(@answer, '=', ''); | |
set @answer = REPLACE(@answer, '/', '_'); | |
return @answer; | |
end; | |
go |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment