そのため、最近、パスワード関連のメソッドの静的クラスを作成し、安全なソルトを生成するメソッドを作成する必要がありました。
最初にRNGCryptoServiceProvider
、nバイトを実装して配列にファイルし、base64に変換して返しました。
問題は、出力の長さで、変換後はもちろんnよりも長くなることでした(これは理にかなっています)。
これを修正するために、関数を以下の方法に変更しました。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;
}
C#
また、副次的な質問として、私はざっと見て回っていましたが、実際の実装のハッシュ関数が実際に何であるかを見つけることができませんでしたRNGCryptoServiceProvider
。誰もが手に負えないことを知っていますか?