随机字符串|密码盐建议

本文关键字:密码 字符串 随机 | 更新日期: 2023-09-27 18:03:13

如果我们比较我下面的方法和RCIX的方法在这个问题的答案中,哪个更有效,为什么?

private string RandomString(int length = 25)
{
    const string chars = "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ0123456789#@%&";
    StringBuilder sbSalt = new StringBuilder();
    for (int i = 0; i < length; i++)
    {
        int inx = 0;
        inx = rnd.Next(0, chars.Length);
        sbSalt.Append(chars[inx]);
    }
    return sbSalt.ToString();
}
private Random rnd = new Random();

我用"aAbBcC…"而不是"abc…abc…"的原因是为了增加每个字母的小写字母和大写字母之间随机化的机会,因为它们彼此相邻。

还有,对于密码盐,是最好保留重复的字符,还是我应该确保每个字符在每个盐中只遇到一次?然后,如果我允许重复字符,则可以生成的盐组合量更大。

提前感谢!

更新# 1:

我意识到,如果我再次调用RandomString函数,它将返回完全相同的随机字符串,所以为了解决这个问题,我只将rnd声明为new Random一次,将其移出函数。

随机字符串|密码盐建议

The reason I did "aAbBcC..." instead of "abc...ABC..." was to increase the chances of randomization between the lower and capital case of each letter since they are next to each other.这将不会增加大小写之间的随机性。

你可以用骰子来测试,数字的位置不会改变偶数和奇数的几率。

efficiency将取决于您如何定义它。你希望你的代码可读性更好还是更差?你需要高性能吗?可维护性?

一般情况下,我不会更喜欢其中一个。

Is it best to keep duplicate characters or should I make sure that each character is only encountered once per salt?

实际上,如果允许双字符,排列的数量会增加。

这意味着字符串在暴力攻击中将更难被破解。

如果您正在使用此盐进行加密技术,最好使用框架的库。如GetBytes():

http://msdn.microsoft.com/en-us/library/system.security.cryptography.rngcryptoserviceprovider.aspx

盐的主要用途是使加密更难被字典攻击。

我确实喜欢在密钥本身上创建污垢,到目前为止,它非常有效,因为我在WCF服务上每秒运行几百个加密/解密:

// sKey being the encryption key
// adding dirt to the string to make it harder to guess using a dictionary attack.
byte[] Dirt = Encoding.ASCII.GetBytes(sKey.Length.ToString());
// The Key will be generated from the specified Key and dirt.
PasswordDeriveBytes FinalKey = new PasswordDeriveBytes(sKey, Dirt);
// to use : FinalKey.GetBytes(16)