所以我最近为密码相关方法创建了一个静态类,并且必须创建一个生成安全盐的方法。
最初我实现了 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;
}
还有一个附带问题,我快速浏览了一圈,实际上找不到RNGCryptoServiceProvider
的C#
实现的散列函数到底是什么。有人知道吗?
最佳答案
为什么盐的长度对您如此重要?我不认为有任何真正的安全隐患,因为盐的唯一真正要求是它是随机的和不可猜测的。
换句话说,去争取吧。
编辑:这是使用 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/