在C#中生成精确的随机数据量

时间:2012-09-26 12:03:49

标签: c# string random byte

我需要一种方法来生成精确数量的伪随机(字符串)数据。例如,我想编写一个方法,该方法接受生成的字节数的参数,并返回该精确大小的字符串。

我原本打算每个字节只需生成1个字符,但显然字符不再是一个字节。

感谢任何帮助!

4 个答案:

答案 0 :(得分:3)

我建议使用RNGCryptoServiceProvider它可以生成任意数量的随机字节。然后,您可以将其转换为字符串(例如,使用byte64编码或其他方法)。

请务必将using System.Security.Cryptography;添加到文件中。

public class RandomService : IDisposable
{
    private readonly RNGCryptoServiceProvider rngCsp;

    public CryptoService()
    {
        rngCsp = new RNGCryptoServiceProvider();            
    }

    public byte[] GetRandomBytes(int length)
    {
        var bytes = new byte[length];
        rngCsp.GetBytes(bytes);
        return bytes;
    }

    public string GetRandomString(int length)
    {
        var numberOfBytesForBase64 = (int) Math.Ceiling((length*3)/4.0);
        string base64String = Convert.ToBase64String(GetRandomBytes(numberOfBytesForBase64)).Substring(0, length); //might be longer because of padding            
        return base64String.Replace('+', '_').Replace('/', '-'); //we don't like these base64 characters
    }

    public void Dispose()
    {
        rngCsp.Dispose();
    }
}

答案 1 :(得分:2)

您可以参加Random课程,转换为byte[]然后ToString()

答案 2 :(得分:1)

char[] UsableChars = { 'a', 'b', 'c', '1', ...., `☺` };
Random r = new Random();

int wantedSize = 12;

string s = new string (Enumerable.Range(0, wantedSize)
    .Select((i) =>  UsableChars[r.Next(UsableChars.Length)]).ToArray());

答案 3 :(得分:0)

如果您使用一组有限的字符,您可以选择那些最终为单字节代码的字符,无论使用何种编码。

public byte[] CreateFiller(int length, Random rnd) {
  string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  return Encoding.UTF8.GetBytes(Enumerable.Range(0, length).Select(i => chars[rnd.Next(chars.Length)]).ToArray());
}

// only use the overload that creates a Random object itself if you use it once, not in a loop
public byte[] CreateFiller(int length) {
  return CreateFiller(length, new Random());
}