Spot the web RSS 2.0
# Tuesday, January 15, 2008

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

Tuesday, January 15, 2008 2:56:38 PM (Jerusalem Standard Time, UTC+02:00)  #    Comments [0] - Trackback
.Net | Programming | Visual Studio
Comments are closed.
Navigation
Archive
<February 2012>
SunMonTueWedThuFriSat
2930311234
567891011
12131415161718
19202122232425
26272829123
45678910
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2012
Guy Levin
Sign In
Statistics
Total Posts: 63
This Year: 0
This Month: 0
This Week: 0
Comments: 14
Themes
All Content © 2012, Guy Levin