0
\$\begingroup\$

Is the following a cryptographically secure way to generate a random token? Does it have any of the predictability risks that are theoretically associated with using a GUID as a token?

using System;
using System.Security.Cryptography;

namespace myApp
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] bytes = new byte[32];
            using (var rng = new RNGCryptoServiceProvider()) {
                rng.GetBytes(bytes);
            }

            string hexToken = BitConverter.ToString(bytes).Replace("-", "").ToLower();
            Console.WriteLine(hexToken);
        }
    }
}
\$\endgroup\$
2
\$\begingroup\$

What is there to say about it?

The code generates 32 random bytes, fed by a good Cryptographically Secure Random Number Generator, seeded by the operating system. Then it converts to just lowercase hexadecimals.

There is only a very small chance that a CryptographicException is thrown by the random number generator, but if it happens it is currently not caught.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.