简体   繁体   English

如何防止特殊字符在C#中生成令牌

[英]how to prevent special characters at generating a token in c#

i generate a token which converts the datetime in bytes. 我生成一个令牌,该令牌将日期时间转换为字节。 Here is how i generate the token: 这是我生成令牌的方式:

public string generateToken()
    {
        byte[] time = BitConverter.GetBytes(DateTime.UtcNow.ToBinary());
        byte[] key = new Guid().ToByteArray();
        string token = Convert.ToBase64String(time.Concat(key).ToArray());
        return token;
    }

This is how it looks like when the token is generated: 这是生成令牌时的样子:

chas42Sbo9AAAAAAAAAAAAAAAAAAAAA chas42Sbo9AAAAAAAAAAAAAAAAAAAAA

but on some days it generates special characters,too. 但有时也会生成特殊字符。 like in this example: 像这个例子:

chs2BiT/z0gAAAAAAAAAAAAAAAAAAAAA chs2BiT / z0gAAAAAAAAAAAAAAAAAAAAAAAA

i parse the result in a link to redirect to another page 我在链接中解析结果以重定向到另一个页面

http://test.com/abo.aspx?chas42Sbo9AAAAAAAAAAAAAAAAAAAAA http://test.com/abo.aspx?chas42Sbo9AAAAAAAAAAAAAAAAAAAAAAAA

with the special characters it looks like this: 具有特殊字符,看起来像这样:

http://test.com/abo.aspx?chs2BiT/z0gAAAAAAAAAAAAAAAAAAAAA http://test.com/abo.aspx?chs2BiT/z0gAAAAAAAAAAAAAAAAAAAAAAAA

and this doesnt work. 这是行不通的。

is it possible to generate a token but without special characters? 是否可以生成令牌但没有特殊字符?

This is how Base64 is defined: 这是Base64的定义方式:

The base-64 digits in ascending order from zero are the uppercase characters "A" to "Z", the lowercase characters "a" to "z", the numerals "0" to "9", and the symbols "+" and "/". 从零开始升序的64位基数是大写字符“ A”到“ Z”,小写字符“ a”到“ z”,数字“ 0”到“ 9”以及符号“ +”和“ “ /”。 The valueless character, "=", is used for trailing padding. 无值字符“ =”用于尾随填充。

So you can't use Convert.ToBase64String if you don't want / character to appear in your token. 因此,如果您不希望/字符出现在令牌中,则不能使用Convert.ToBase64String

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM