Csharp/CSharp Tutorial/Security/RandomNumberGenerator

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Cryptographically sound random numbers

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;

public class MainClass
{
    public static void Main()
    {
        RandomNumberGenerator rng = RandomNumberGenerator.Create();
        byte[] b = new byte[1];
        rng.GetBytes(b);
        Console.WriteLine(b[0]);
    }
}
191

Generate 32 bytes of random data

using System;
using System.Security.Cryptography;
class MainClass
{
    public static void Main() {
        byte[] number = new byte[32];
        
        RandomNumberGenerator rng = RandomNumberGenerator.Create();
        
        
        rng.GetBytes(number);
        
        // Display the random number.
        Console.WriteLine(BitConverter.ToString(number));
    }
}
B9-33-DA-50-FB-D0-A7-7A-6D-7C-12-A7-47-A5-FE-45-F0-E0-DC-87-AE-27-CE-C0-76-D5-85-5C-DF-7D-4A-82