Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating Hashes using .NET Core

I need to Generate Random Unique hashes to be used in password reset links in .Net Core. In ASP.NET Identity, I found this to be helpful, I am wondering if RNGCryptoServiceProvider still assures the randomness of the hashes generated.

 using (RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider())
            {
                var data = new byte[4];
                for (int i = 0; i < 10; i++)
                {
                    //filled with an array of random numbers
                    rngCsp.GetBytes(data);
                    //this is converted into a character from A to Z
                    var randomchar = Convert.ToChar(
                        //produce a random number 
                        //between 0 and 25
                        BitConverter.ToUInt32(data, 0) % 26
                        //Convert.ToInt32('A')==65
                                              + 65
                    );
                    token.Append(randomchar);
                }
            }

What is the best way to achieve that using .net core and using which classes?

like image 755
Hussein Salman Avatar asked Oct 28 '16 16:10

Hussein Salman


1 Answers

RNGCryptoServiceProvider is not in .NET Core. Use RandomNumberGenerator.Create() to get an instance of a CSPRNG that will work on the correct platform. Its API is the same as RNGCryptoServiceProvider, except that GetNonZeroBytes is missing (which I'd argue shouldn't have even been there).

On Windows, this will boil down to BCryptGenRandom in CNG, and on Linux it will use OpenSSL.

like image 62
vcsjones Avatar answered Oct 24 '22 16:10

vcsjones