c# - 修剪盐的安全风险

标签 c# hash cryptography base64 salt

所以我最近为密码相关方法创建了一个静态类,并且必须创建一个生成安全盐的方法。

最初我实现了 RNGCryptoServiceProvider 并将 n 个字节存入一个数组,我将其转换为 base64 并返回。

问题是输出长度,转换后当然比 n ( which makes sense ) 长。

为了解决这个问题,我将函数更改为下面的方法,我只是想知道通过修剪 base64 字符串是否会引发任何安全风险?

/// <summary>
/// Generates a salt for use with the Hash method.
/// </summary>
/// <param name="length">The length of string to generate.</param>
/// <returns>A cryptographically secure random salt.</returns>
public static string GenerateSalt(int length)
{
    // Check the length isn't too short.
    if (length < MIN_LENGTH)
    {
        throw new ArgumentOutOfRangeException("length", "Please increase the salt length to meet the minimum acceptable value of " + MIN_LENGTH + " characters.");
    }

    // Calculate the number of bytes required.
    // https://en.wikipedia.org/wiki/Base64#Padding
    // http://stackoverflow.com/questions/17944/how-to-round-up-the-result-of-integer-division
    int bytelen = ((3 * length) + 4 - 1) / 4;

    // Create our empty salt array.
    byte[] bytes = new byte[bytelen];

    // Where we'll put our generated salt.
    string salt;

    // Generate a random secure salt.
    using (RNGCryptoServiceProvider randcrypto = new RNGCryptoServiceProvider())
    {
        // Fill our array with random bytes.
        randcrypto.GetBytes(bytes);

        // Get a base64 string from the random byte array.
        salt = GetBase64(bytes);
    }

    // Trim the end off only if we need to.
    if (salt.Length > length)
    {
        // Substring is the fastest method to use.
        salt = salt.Substring(0, length);
    }

    // Return the salt.
    return salt;
}

还有一个附带问题,我快速浏览了一圈,实际上找不到RNGCryptoServiceProviderC# 实现的散列函数到底是什么。有人知道吗?

最佳答案

为什么盐的长度对您如此重要?我不认为有任何真正的安全隐患,因为盐的唯一真正要求是它是随机的和不可猜测的。

换句话说,去争取吧。

编辑:这是使用 Linq 的另一种方法。

Random random = new Random();
int length = 25; // Whatever length you want
char[] keys = "ABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890!£$%^&*()".ToCharArray(); // whatever chars you want
var salt = Enumerable
    .Range(1, length) // equivalent to the loop bit, for(i.. ) 
    .Select(k => keys[random.Next(0, keys.Length - 1)])  // generate a new random char 
    .Aggregate("", (e, c) => e + c); // join them together into a string

关于c# - 修剪盐的安全风险,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12068973/

相关文章:

c# - 映射平台特定的互操作类型

c# - TabIndex 无法正常工作

php - PHP hash() 默认支持 WHIRLPOOL 吗?

java - 获取 ruby​​ 的 "RSA/ECB/OAEPWithSHA-256AndMGF1Padding"组合

c# - Unity 拦截 (AOP) 嵌套虚拟属性

c# - Javascript 函数不会从代码隐藏中调用

ruby - 访问嵌套哈希值

php - 使用返回 0 的查询行比较 mysql 密码哈希(不工作)

ios - 如何覆盖 NSManagedObjects 的 hash 和 isEqual?

c - 嵌入式系统中的aes ctr 128位解密