RNGCryptoServiceProvider 已过时
RNGCryptoServiceProvider is obsolete
我需要使用随机数字和字母生成令牌。但是,错误消息告诉我使用 RandomNumberGenerator,它只会给我随机数,这无济于事。
错误信息
'RNGCryptoServiceProvider' is obsolete: 'RNGCryptoServiceProvider is obsolete. To generate a random number, use one of the RandomNumberGenerator static methods instead.'
当前使用的代码
private static string RandomString()
{
int length = 256;
const string valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
StringBuilder res = new StringBuilder();
using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
byte[] uintBuffer = new byte[sizeof(uint)];
while (length-- > 0)
{
rng.GetBytes(uintBuffer);
uint num = BitConverter.ToUInt32(uintBuffer, 0);
res.Append(valid[(int)(num % (uint)valid.Length)]);
}
}
return res.ToString();
}
如何更改上面的代码以使用未过时的包?
您可以这样使用 RandomNumberGenerator
:
var randomNumber = new byte[32];
string refreshToken = "";
using (var rng = RandomNumberGenerator.Create())
{
rng.GetBytes(randomNumber);
refreshToken = Convert.ToBase64String(randomNumber);
}
结果示例:fHu4SOyv03PhHvqWx5WGmI5xQFnH00CmLCV3IYJd5Dw=
只需根据您的情况进行调整即可。
我需要使用随机数字和字母生成令牌。但是,错误消息告诉我使用 RandomNumberGenerator,它只会给我随机数,这无济于事。
错误信息
'RNGCryptoServiceProvider' is obsolete: 'RNGCryptoServiceProvider is obsolete. To generate a random number, use one of the RandomNumberGenerator static methods instead.'
当前使用的代码
private static string RandomString()
{
int length = 256;
const string valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
StringBuilder res = new StringBuilder();
using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
byte[] uintBuffer = new byte[sizeof(uint)];
while (length-- > 0)
{
rng.GetBytes(uintBuffer);
uint num = BitConverter.ToUInt32(uintBuffer, 0);
res.Append(valid[(int)(num % (uint)valid.Length)]);
}
}
return res.ToString();
}
如何更改上面的代码以使用未过时的包?
您可以这样使用 RandomNumberGenerator
:
var randomNumber = new byte[32];
string refreshToken = "";
using (var rng = RandomNumberGenerator.Create())
{
rng.GetBytes(randomNumber);
refreshToken = Convert.ToBase64String(randomNumber);
}
结果示例:fHu4SOyv03PhHvqWx5WGmI5xQFnH00CmLCV3IYJd5Dw=
只需根据您的情况进行调整即可。