为什么 RNGCryptoServiceProvider 值总是以等号结尾?
这是我的方法:
public static string GenerateRandomString(int bytes)
{
var rng = new RNGCryptoServiceProvider();
var randomBytes = new byte[bytes];
rng.GetBytes(randomBytes);
return Convert.ToBase64String(randomBytes);
}
生成的每个值:
即:
Qcr6OgNxkGzVebNl00Dtk7yCaz64owUx7pKEhl1Ogn4=
IGFLQB0OrReDB3P6nuZgqZIkTwTtch9Fk3Rx/DL4CgI=
UAJwLwIPYEJ9SzMAK/EMiUJ/DHhmfy6UVMM5MU6Dcpg=
总是以“=”结尾 - 这是为什么?
我将此作为密码重置电子邮件的随机字符串发送,但 Microsoft Outlook 出现问题,无法拾取链接末尾的=。有谁知道解决这个问题的方法而无需简单地砍掉字符串的最后一个字符?
Here is my method:
public static string GenerateRandomString(int bytes)
{
var rng = new RNGCryptoServiceProvider();
var randomBytes = new byte[bytes];
rng.GetBytes(randomBytes);
return Convert.ToBase64String(randomBytes);
}
Every value generated:
i.e.:
Qcr6OgNxkGzVebNl00Dtk7yCaz64owUx7pKEhl1Ogn4=
IGFLQB0OrReDB3P6nuZgqZIkTwTtch9Fk3Rx/DL4CgI=
UAJwLwIPYEJ9SzMAK/EMiUJ/DHhmfy6UVMM5MU6Dcpg=
always ends with "=" - why is this?
I'm sending this as a random string for a password reset email and am having issues with Microsoft Outlook not picking up the = at the end of the link. Is anyone aware of a way around this without simply chopping off the last character of the string?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它与返回的字节数有关。 = 用作 base64 的填充。
编辑
使用您的算法,我使用 1 到 20 个字节生成字符串,每行打印 1 个结果。正如您所看到的,某些字符串以等号结尾,而其他字符串则不然。
编辑 #2
我意识到我解释了 = 出现的原因,但从未建议使用其他方法来生成 URL 参数。一种这样的方法是 System.Web.HttpServerUtility.UrlTokenEncode()将字节数组转换为 url 友好格式的方法。要将字符串转换回字节数组,请使用 System.Web.HttpServerUtility .UrlTokenDecode() 方法。
It has to do with the number of bytes returned. The = is used as padding for base64.
EDIT
Using your algorithm I generated strings using between 1 and 20 bytes, printing 1 result per line. As you can see, some strings end with equal signs, others do not.
EDIT #2
I realized that I explained why the = occurs, but never suggested another way to generate your URL parameter. One such way is the System.Web.HttpServerUtility.UrlTokenEncode() method which converts an array of bytes to an url-friendly format. To convert the string back to an array of bytes, use the System.Web.HttpServerUtility.UrlTokenDecode() method.