我正在生成一个随机的 20 字节长数组,并希望将其转换为字符串,以便将其用作 API 调用的随机令牌。但是,当我将其转换回字节数组(仅用于测试)时,与原始数组相比,我得到了不同的数组。
这是我的代码:
var rand = new Random();
string generateId(){
byte[] bytes_buff = new byte[20];
rand.NextBytes(bytes_buff);
foreach (byte b in bytes_buff)
Console.Write("{0, 5}", b);
Console.WriteLine();
string converted = System.Text.Encoding.UTF8.GetString(bytes_buff);
foreach (char character in converted)
Console.Write("{0, 5}", character);
Console.WriteLine();
byte[] recoded = System.Text.Encoding.UTF8.GetBytes(converted);
foreach (byte b in recoded)
Console.Write("{0, 5}", b);
Console.WriteLine();
return converted;
}
它会产生以下输出:
162 108 161 7 212 200 169 171 205 89 240 122 194 173 223 253 57 148 125 76
? l ? ? ? ? ? Y ? z - ? ? 9 ? } L
239 191 189 108 239 191 189 7 239 191 189 200 169 239 191 189 239 191 189 89 239 191 189 122 194 173 239 191 189 239 191 189 57 239 191 189 125 76
我意识到,对于大于 127 的数字,
getString()
会转换为“?”字符和 getByte()
代表“?”转换回三个字节 239 191 189。
现在从这篇文章我了解到UTF-8不是一对一映射的,但是我们应该如何生成字符串形式的令牌并通过互联网发送它们呢? UTF-8 不是互联网上的标准编码吗?
另外,如果我们无法涵盖标记中每个字符的所有 0-255 范围,那么这些字符的实际范围是多少? (a-z、A-Z、0-9 等)
任何解释表示赞赏。预先感谢!
您可以使用多种不同的方法来生成令牌,这些方法不一定包括直接转换为 UTF-8。一个简单的
GUID.ToString(string)
和 GUID.TryParseExact(string, string, GUID)
可能会以尽可能少的努力为您提供足够好的代币。当今公共 API 的行业标准似乎正在使用 JWT 令牌。
就我个人而言,我只需要在一个项目中启用 JWT(一个 asp.net core Web Api,如果这很重要),但它相当简单且易于集成。