C#密码加密 [英] C# Password Encryption

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

问题描述

我发现了一些code网上,对工作相当好什么,我试图做的。我需要的东西,将加密密码,将其保存到数据库,并轻松检索。下面code做几乎所有我所期待的。

I found some code online that works fairly well for what I am trying to do. I need something that will encrypt a password, save it to a database, and retrieve with ease. The below code does almost everything I am looking for.

        string UserName = txtUser.Text;
        string password = txtPass.Text;

        string encrKey = "keyvalue";
        byte[] byteKey = { };
        byte[] IV = {25, 47, 60, 88, 99, 106, 125, 139};
        byteKey = Encoding.UTF8.GetBytes(encrKey.Substring(0, 8));
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        byte[] inputArray = Encoding.UTF8.GetBytes(password);

        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byteKey, IV), CryptoStreamMode.Write);
        cs.Write(inputArray, 0, inputArray.Length);
        cs.FlushFinalBlock();
        password = Convert.ToBase64String(ms.ToArray());

        SqlCommand cmd = new SqlCommand("INSERT INTO USers (UserName, Password) VALUES (@UserName, @Password)", myConnection);
        cmd.CommandType = CommandType.Text;

        cmd.Parameters.AddWithValue("@UserName", UserName);
        cmd.Parameters.AddWithValue("@Password", password);

        SqlDataReader rdr = cmd.ExecuteReader();

这是我遇到的问题是,code错误,出来的时候,密码是8个字符或更长。我得到这个错误:

The issue that I am running into is the code errors out when the password is 8 characters or longer. I get this error:

System.Security.Cryptography.CryptographicException:指定的关键不是这个算法有效的大小。对CryptoStream的线产生的错误。

System.Security.Cryptography.CryptographicException: Specified key is not a valid size for this algorithm. The error is generated on the Cryptostream line.

我是否需要使用不同的类型,我的钥匙?

Do I need to use a different type for my keys?

推荐答案

最常见的做法是不是在数据库中,但散列它来加密口令。结果
当用户试图登录,你把他的密码输入,哈希,并与存储在你的数据库的哈希值。

The common practice is not to encrypt a password in the database but to hash it.
When the user attempts to login, you take his typed password, hash it and compare to the hash stored in your db.

行业标准散列算法SHA-1,这是readly提供.NET。

The industry standard hashing algorithm is SHA-1, which is readly available in .NET.

有关更大的安全性,你在你的散列使用盐。

For even greater security you use a "Salt" in your hashing.

您可以阅读更多关于它在这里:腌制密码:最佳实践

You can read more about it here: Salting Your Password: Best Practices?

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

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