在SQL中创建base64编码的字符串

时间:2018-09-20 12:10:35

标签: sql sql-server asp.net-mvc-5 asp.net-identity

我正在尝试制作一个SQL脚本来为基于Web的应用程序创建一个管理员用户,但是我遇到了一些麻烦。

您看到我正在使用Microsoft.AspNet.Identity,它会为64base编码字符串(我认为)的用户创建ID,例如:h231hj4f-bae1-nfwe-m24n-k954bd8s0l1r

但是我创建的每个字符串看起来都不尽如人意,当我尝试登录时会抛出错误

  

Base-64 char数组的长度无效。

这是我到目前为止所拥有的:

DECLARE @RandomLength2 int;
/*Generate random number between 42 and 38*/
SET @RandomLength2 = (SELECT ROUND(((42-38-1) * RAND() + 38), 0));

DECLARE @generatedId2 nvarchar(42);
/*Generate string of 42 chars*/
SET @generatedId2 = (
SELECT
c1 AS [text()]
FROM
(
SELECT TOP (@RandomLength2) c1
FROM
  (
VALUES
  ('A'), ('B'), ('C'), ('D'), ('E'), ('F'), ('G'), ('H'), ('I'), ('J'),
  ('K'), ('L'), ('M'), ('N'), ('O'), ('P'), ('Q'), ('R'), ('S'), ('T'),
  ('U'), ('V'), ('W'), ('X'), ('Y'), ('Z'), ('0'), ('1'), ('2'), ('3'),
  ('4'), ('5'), ('6'), ('7'), ('8'), ('9')  
  ) AS T1(c1)
ORDER BY ABS(CHECKSUM(NEWID()))
) AS T2
FOR XML PATH('')
);

DECLARE @base64GeneratedSecurityStamp nvarchar(max)
/*generate base64 char string with the generatedString*/
SET @base64GeneratedSecurityStamp = (SELECT LOWER(
CAST(N'' AS XML).value(
      'xs:base64Binary(xs:hexBinary(sql:column("bin")))'
    , 'VARCHAR(MAX)'
))
FROM (
SELECT CAST(@generatedId2 AS VARBINARY(MAX)) AS bin
) AS bin_sql_server_temp);

SELECT @base64GeneratedSecurityStamp;

生成类似uqbuaeeawaaxadyasabqaemarqazaekawqbeaeoanabwadcargbvae4amabmaesatwbcaduavwbhae0awga5afiauwa4adia

的内容

编辑

我做了一些调整,现在我创建一个32个字符的随机字符串,而不是随机生成,并使用子字符串使用'-'将字符串分成多个部分。

这会生成类似vxnlckdl-ynj1-wtlc-5hyw-=qgbuafma-sgbo-e8at-bzae-aoaa5aegaqqb的字符串

DECLARE @RandomLength2 int;

SET @RandomLength2 = (SELECT ROUND(((42-38-1) * RAND() + 38), 0));

DECLARE @generatedId2 nvarchar(32);

SET @generatedId2 = (
SELECT
c1 AS [text()]
FROM
(
SELECT TOP (32) c1
FROM
  (
VALUES
  ('A'), ('B'), ('C'), ('D'), ('E'), ('F'), ('G'), ('H'), ('I'), ('J'),
  ('K'), ('L'), ('M'), ('N'), ('O'), ('P'), ('Q'), ('R'), ('S'), ('T'),
  ('U'), ('V'), ('W'), ('X'), ('Y'), ('Z'), ('0'), ('1'), ('2'), ('3'),
  ('4'), ('5'), ('6'), ('7'), ('8'), ('9')  
  ) AS T1(c1)
ORDER BY ABS(CHECKSUM(NEWID()))
) AS T2
FOR XML PATH('')
);

DECLARE @base64GeneratedSecurityStamp nvarchar(max)

SET @base64GeneratedSecurityStamp = (SELECT LOWER(
CAST(N'' AS XML).value(
      'xs:base64Binary(xs:hexBinary(sql:column("bin")))'
    , 'VARCHAR(MAX)'
))
FROM (
SELECT CAST(@generatedId2 AS VARBINARY(MAX)) AS bin
) AS bin_sql_server_temp);

SET @base64GeneratedSecurityStamp = ((SUBSTRING(@base64GeneratedSecurityStamp, 1, 8) +'-'+ SUBSTRING(@base64GeneratedSecurityStamp, 9, 4) +'-'+ SUBSTRING(@base64GeneratedSecurityStamp, 14, 4) +'-'+ SUBSTRING(@base64GeneratedSecurityStamp, 19, 4) +'-'+ SUBSTRING(@base64GeneratedSecurityStamp, 24, 12)));

SELECT @base64GeneratedSecurityStamp;

0 个答案:

没有答案