class Program
{
static void Main(string[] args)
{
Console.WriteLine("Sergio");
Console.WriteLine(HashString("Sergio"));
Console.WriteLine(HashString("Sergio"));
Console.WriteLine(HashString("Sergio"));
Console.ReadKey();
}
public static string HashString(string value)
{
int minSaltSize = 4;
int maxSaltSize = 8;
Random random = new Random();
int saltSize = random.Next(minSaltSize, maxSaltSize);
byte[] saltBytes = new byte[saltSize];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetNonZeroBytes(saltBytes);
//Convert the string value into a byte array.
UTF8Encoding utf8Encoder = new UTF8Encoding();
byte[] plainTextBytes = utf8Encoder.GetBytes(value);
//Allocate an array to hold the text bytes and the salt bytes.
byte[] plainTextWithSaltBytes = new Byte[saltBytes.Length + plainTextBytes.Length];
for (int i = 0; i < plainTextBytes.Length; i++)
{
plainTextWithSaltBytes[i] = plainTextBytes[i];
}
for (int i = 0; i < saltBytes.Length; i++)
{
plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i];
}
HashAlgorithm hash = new SHA256Managed();
byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);
string hashedValue = Convert.ToBase64String(hashBytes);
return hashedValue;
}
}我的代码的结果是散列的"Sergio“每次都是不同的。这是由盐中包含的随机因素引起的。我的问题是,我是不是应该把盐存起来?或者我在代码中定义了一个常量盐?
谢谢!
发布于 2011-02-16 01:51:19
我一直是盐的GUID和散列的SHA512的粉丝。CPU时间不是问题,因为它只在身份验证期间使用。
但是,是的,您需要存储散列,以便可以将其附加到传入的密码。
storedpassword =哈希(salt+password)
如果你忘记了盐,你就不能比较它们的值。
发布于 2011-02-16 01:35:39
如果您使用的是不同的盐,那么您将需要在数据库中存储散列密码和盐。如果盐是相同的盐,您还可以选择将盐存储在app.config / web.config文件中。
发布于 2011-02-16 01:35:43
你应该把盐保存在某个地方,因为当你再次计算散列时,你需要使用相同的盐。但是,您不希望使用常量,因为这会降低salt的有效性。
https://stackoverflow.com/questions/5007185
复制相似问题