首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我是否应该在散列密码时将盐保存在某个地方?

问我是否应该在散列密码时将盐保存在某个地方?
EN

Stack Overflow用户
提问于 2011-02-16 01:33:40
回答 5查看 1.3K关注 0票数 1
代码语言:javascript
复制
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“每次都是不同的。这是由盐中包含的随机因素引起的。我的问题是,我是不是应该把盐存起来?或者我在代码中定义了一个常量盐?

谢谢!

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2011-02-16 01:51:19

我一直是盐的GUID和散列的SHA512的粉丝。CPU时间不是问题,因为它只在身份验证期间使用。

但是,是的,您需要存储散列,以便可以将其附加到传入的密码。

storedpassword =哈希(salt+password)

如果你忘记了盐,你就不能比较它们的值。

票数 0
EN

Stack Overflow用户

发布于 2011-02-16 01:35:39

如果您使用的是不同的盐,那么您将需要在数据库中存储散列密码和盐。如果盐是相同的盐,您还可以选择将盐存储在app.config / web.config文件中。

票数 1
EN

Stack Overflow用户

发布于 2011-02-16 01:35:43

你应该把盐保存在某个地方,因为当你再次计算散列时,你需要使用相同的盐。但是,您不希望使用常量,因为这会降低salt的有效性。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5007185

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档