Home > Enterprise >  RNGCryptoServiceProvider is obsolete
RNGCryptoServiceProvider is obsolete

Time:05-30

I need to generate a token using random numbers and letters. However, the error message is telling me to use RandomNumberGenerator which will only give me random numbers which will not help.

error messsage

'RNGCryptoServiceProvider' is obsolete: 'RNGCryptoServiceProvider is obsolete. To generate a random number, use one of the RandomNumberGenerator static methods instead.'

Code currently used

    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();
    }

How do I change the code above to use a package that is not out of date?

CodePudding user response:

You can use RandomNumberGenerator like this:

var randomNumber = new byte[32];
string refreshToken = "";

using (var rng = RandomNumberGenerator.Create())
{
     rng.GetBytes(randomNumber);
     refreshToken = Convert.ToBase64String(randomNumber);
}

Example of result: fHu4SOyv03PhHvqWx5WGmI5xQFnH00CmLCV3IYJd5Dw=

Just adjust this to your case.

  • Related