在c#中使用salt加密密码 [英] Encrypting the password using salt in c#

查看:57
本文介绍了在c#中使用salt加密密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为此搜索了一些代码,但发现了一些带有预定义盐的代码.我想为每个用户自动生成盐并将盐值存储在表中.谢谢我是编程新手请帮忙

I searched for some code for doing that, but found some with pre defined salt. I want to auto generate the salt for each user and store the salt value in the table. Thanks I am new to programming please help

推荐答案

(按照建议,我已经用应该更安全的方法替换了我之前的盐生成方法)

生成随机盐:

public static string GenerateRandomSalt(RNGCryptoServiceProvider rng, int size)
{
    var bytes = new Byte[size];
    rng.GetBytes(bytes);
    return Convert.ToBase64String(bytes);
}

var rng = new RNGCryptoServiceProvider();
var salt1 = GenerateRandomSalt(rng, 16);
var salt2 = GenerateRandomSalt(rng, 16);
// etc.

RNGCryptoServiceProvider 用于生成加密强随机值",使其比标准的 Random 类更适合在这里使用.无论您如何生成盐,您都可以使用您选择的算法将其附加到您的密码和哈希中:

RNGCryptoServiceProvider is used to generate "cryptographically strong random values," making it more suitable for use here than the standard Random class. However you generate the salt, you can then append it to your password and hash using your algorithm of choice:

var salt = GenerateRandomSalt(rng, 16);
var hashedPassword = DoPasswordHashing(password + salt);

然而,值得指出的是,正确进行用户身份验证可能比看起来更困难.Eric Lippert 几年前写了一系列关于此的博客文章:http://blogs.msdn.com/b/ericlippert/archive/2005/01/28/you-want-salt-with-that-part-one-security-vs-obscurity.aspx

However, it's worth pointing out that doing user authentication correctly can be a more difficult problem than it seems. Eric Lippert wrote a series of blog articles about this several years ago: http://blogs.msdn.com/b/ericlippert/archive/2005/01/28/you-want-salt-with-that-part-one-security-vs-obscurity.aspx

这篇关于在c#中使用salt加密密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆