使用RNGCryptoServiceProvider生成随机字符串 [英] using RNGCryptoServiceProvider to generate random string

查看:113
本文介绍了使用RNGCryptoServiceProvider生成随机字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此代码生成具有给定长度的随机字符串

public string RandomString(int length)
{
    const string valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    StringBuilder res = new StringBuilder();
    Random rnd = new Random();
    while (0 < length--)
    {
        res.Append(valid[rnd.Next(valid.Length)]);
    }
    return res.ToString();
}

但是,我读到RNGCryptoServiceProviderRandom类更安全.如何实现此功能的RNGCryptoServiceProvider.就像此函数一样,它应该使用valid字符串.

解决方案

由于RNGRandomNumberGenerator仅返回字节数组,因此您必须这样做:

static string RandomString(int length)
{
    const string valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    StringBuilder res = new StringBuilder();
    using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
    {
        byte[] uintBuffer = new byte[sizeof(uint)];

        while (length-- > 0)
        {
            rng.GetBytes(uintBuffer);
            uint num = BitConverter.ToUInt32(uintBuffer, 0);
            res.Append(valid[(int)(num % (uint)valid.Length)]);
        }
    }

    return res.ToString();
}

但是请注意,这有一个缺陷,62个有效字符等于5,9541963103868752088061235991756位(log(62)/log(2)),因此它不会在32位数字(uint)上平均分配./p>

这有什么后果? 结果,随机输出将不一致.值较低的字符更有可能出现(只是很小的一部分,但仍然会发生).

更准确地说,有效数组的前4个字符出现的可能性高0,00000144354999199840239435286%.

为避免这种情况,您应该使用将数组长度平均分配为64的数组(请考虑使用

However, I read that RNGCryptoServiceProvideris more secure than Random class. How can I implement RNGCryptoServiceProvider to this function. It should use valid string just like this function.

Since RNGRandomNumberGenerator only returns byte arrays, you have to do it like this:

static string RandomString(int length)
{
    const string valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    StringBuilder res = new StringBuilder();
    using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
    {
        byte[] uintBuffer = new byte[sizeof(uint)];

        while (length-- > 0)
        {
            rng.GetBytes(uintBuffer);
            uint num = BitConverter.ToUInt32(uintBuffer, 0);
            res.Append(valid[(int)(num % (uint)valid.Length)]);
        }
    }

    return res.ToString();
}

Note however that this has a flaw, 62 valid characters is equal to 5,9541963103868752088061235991756 bits (log(62) / log(2)), so it won't divide evenly on a 32 bit number (uint).

What consequences does this have? As a result, the random output won't be uniform. Characters which are lower in value will occur more likely (just by a small fraction, but still it happens).

To be more precise, the first 4 characters of a valid array are 0,00000144354999199840239435286 % more likely to occur.

To avoid this, you should use array lengths that will divide evenly into 64 (Consider using Convert.ToBase64String on the output instead, since you can cleanly match 64 bits to 6 bytes.

这篇关于使用RNGCryptoServiceProvider生成随机字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆