Generating Good Random Numbers by Using the .NET Framework

Generating Good Random Numbers by Using the .NET Framework

If you must create cryptographically secure random numbers, you should not use code like the code below, which uses a linear congruence function, just like the C run-time rand function:

// Generate a new encryption key. byte[] key = new byte[16]; new Random().NextBytes(key);

Rather, you should use code like the following sample code in C#, which fills a 32-byte buffer with cryptographically string random data. (Refer to Chapter 6, Cryptographic Foibles, for more information on random numbers.)

using System.Security.Cryptography; try { byte[] b = new byte[32]; new RNGCryptoServiceProvider().GetBytes(b); for (int i = 0; i < b.Length; i++) Console.Write( {0} , b[i].ToString( x )); } catch(CryptographicException e) { Console.WriteLine(e.ToString()); }

The RNGCryptoServiceProvider class calls into CryptoAPI and CryptGenRandom to generate its random data. The same code in Visual Basic .NET looks like this:

Dim b(32) As Byte Dim i As Short Try Dim r As New RNGCryptoServiceProvider() r.GetBytes(b) For i = 0 To b.Length - 1 Console.Write( {0}", b(i).ToString( x )) Next Catch e As CryptographicException Console.WriteLine(e.ToString) End Try



Writing Secure Code
Writing Secure Code, Second Edition
ISBN: 0735617228
EAN: 2147483647
Year: 2005
Pages: 153

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net