For a long time I have been looking for a really easy way to create a cryptographically random string in c#. I knew it had to be simple but I just had not spend the time to dig one up. Specifically I was looking for a quick and easy way to get a string that was acceptable for use as a Token for session use.
using System;using System.Security.Cryptography;
namespace ConsoleApplication1{ class Program { static void Main(string[] args) { byte[] random = new Byte[128]; //Tell it how long you want it to be RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); rng.GetNonZeroBytes(random); // The array is now filled with cryptographically strong random bytes.
Console.WriteLine(System.Convert.ToBase64String(random)); Console.ReadKey(); } }}
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.