C# 如何在从 Web 应用程序输入的数据库中以加密格式存储密码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10695954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to store password in encrypted format in database entered from web application?
提问by Syed Yunus
In my application there is a password field. When user enters password it should encrypt that password and store into database. When user login into that application then password should fetch from database and decryption should take place.
在我的应用程序中有一个密码字段。当用户输入密码时,它应该加密该密码并存储到数据库中。当用户登录该应用程序时,应从数据库中获取密码并进行解密。
Is it possible??
是否可以??
采纳答案by npinti
You could take a look at thislink which could get you started in the right direction.
你可以看看这个链接,它可以让你朝着正确的方向开始。
That being said however, it is the usual practice to store the hash value of the password itself rather than an encrypted version of the password. The hashing will allow you to check if the user has entered the correct password (by comparing the hash value you have in your database with the hash value of whatever the user entered) without the need of knowing what is the actual password.
尽管如此,通常的做法是存储密码本身的哈希值而不是密码的加密版本。散列将允许您检查用户是否输入了正确的密码(通过将您在数据库中的散列值与用户输入的任何散列值进行比较),而无需知道实际密码是什么。
The advantage of this is that it is usually simpler and more secure since you do not need to encrypt/decrypt any values. The drawback of using hashing is that you can never sendthe users their passwords (if you are planning to provide some sort of 'forgot my password' functionality) but rather you will have to reset it to a new, random one.
这样做的好处是它通常更简单、更安全,因为您不需要加密/解密任何值。使用散列的缺点是您永远无法向用户发送他们的密码(如果您打算提供某种“忘记密码”功能),而是必须将其重置为新的随机密码。
回答by Chris Moutray
ASP.NET SQL Server membership provider gives you this feature when you configure the passwordFormat="Hashed"ASP.NET password hashing and password salt
当您配置ASP.NET 密码散列和密码盐时,ASP.NET SQL Server 成员资格提供程序为您提供此功能passwordFormat="Hashed"
But it you're looking to roll your own then you'll want to research into Salted Password. For example Hash and salt passwords in C#
但是,如果您希望自己动手,那么您将需要研究 Salted Password。例如C# 中的哈希和盐密码
回答by kuldeep verma
You can Create SQLCLR UDF in SQL SERVER , There are Two main Method I used to Save Password in Encrpted Format .
您可以在 SQL SERVER 中创建 SQLCLR UDF,我使用两种主要方法以加密格式保存密码。
Pwdencryp()t encrypts a password, returning the encrypted string. This is used when you set a password, and the encrypted password is stored in the master..syslogins table.
Pwdencryp()t 加密密码,返回加密的字符串。这在您设置密码时使用,加密后的密码存储在 master..syslogins 表中。
http://msdn.microsoft.com/en-us/library/dd822791(v=sql.105).aspx
http://msdn.microsoft.com/en-us/library/dd822791(v=sql.105).aspx
Pwdcompare() accepts a clear password and an encrypted one, and checks whether they match by encrypting the clear password and comparing the two. When you type your password to log into SQL Server, this routine is called.
Pwdcompare() 接受明文密码和加密密码,并通过对明文密码进行加密并比较两者来检查它们是否匹配。当您键入密码登录 SQL Server 时,将调用此例程。
回答by JayOnDotNet
The simplest way to get hash password is as follow.
FormsAuthentication.HashPasswordForStoringInConfigFile("value of string", FormsAuthPasswordFormat.MD5.ToString());
获取哈希密码的最简单方法如下。
FormsAuthentication.HashPasswordForStoringInConfigFile("value of string", FormsAuthPasswordFormat.MD5.ToString());
回答by Sabry
If you do not wish to use the ASP.NET Membership and Role providers, this might be useful to you :
如果您不想使用 ASP.NET Membership 和 Role 提供程序,这可能对您有用:
/// <summary>
/// Decrypts the specified encryption key.
/// </summary>
/// <param name="encryptionKey">The encryption key.</param>
/// <param name="cipherString">The cipher string.</param>
/// <param name="useHashing">if set to <c>true</c> [use hashing].</param>
/// <returns>
/// The decrypted string based on the key
/// </returns>
public static string Decrypt(string encryptionKey, string cipherString, bool useHashing)
{
byte[] keyArray;
//get the byte code of the string
byte[] toEncryptArray = Convert.FromBase64String(cipherString);
System.Configuration.AppSettingsReader settingsReader =
new AppSettingsReader();
if (useHashing)
{
//if hashing was used get the hash code with regards to your key
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(encryptionKey));
//release any resource held by the MD5CryptoServiceProvider
hashmd5.Clear();
}
else
{
//if hashing was not implemented get the byte code of the key
keyArray = UTF8Encoding.UTF8.GetBytes(encryptionKey);
}
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
//set the secret key for the tripleDES algorithm
tdes.Key = keyArray;
//mode of operation. there are other 4 modes.
//We choose ECB(Electronic code Book)
tdes.Mode = CipherMode.ECB;
//padding mode(if any extra byte added)
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tdes.CreateDecryptor();
byte[] resultArray = cTransform.TransformFinalBlock(
toEncryptArray, 0, toEncryptArray.Length);
//Release resources held by TripleDes Encryptor
tdes.Clear();
//return the Clear decrypted TEXT
return UTF8Encoding.UTF8.GetString(resultArray);
}
/// <summary>
/// Encrypts the specified to encrypt.
/// </summary>
/// <param name="toEncrypt">To encrypt.</param>
/// <param name="useHashing">if set to <c>true</c> [use hashing].</param>
/// <returns>
/// The encrypted string to be stored in the Database
/// </returns>
public static string Encrypt(string encryptionKey, string toEncrypt, bool useHashing)
{
byte[] keyArray;
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
System.Configuration.AppSettingsReader settingsReader =
new AppSettingsReader();
//If hashing use get hashcode regards to your key
if (useHashing)
{
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(encryptionKey));
//Always release the resources and flush data
// of the Cryptographic service provide. Best Practice
hashmd5.Clear();
}
else
keyArray = UTF8Encoding.UTF8.GetBytes(encryptionKey);
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
//set the secret key for the tripleDES algorithm
tdes.Key = keyArray;
//mode of operation. there are other 4 modes.
//We choose ECB(Electronic code Book)
tdes.Mode = CipherMode.ECB;
//padding mode(if any extra byte added)
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tdes.CreateEncryptor();
//transform the specified region of bytes array to resultArray
byte[] resultArray =
cTransform.TransformFinalBlock(toEncryptArray, 0,
toEncryptArray.Length);
//Release resources held by TripleDes Encryptor
tdes.Clear();
//Return the encrypted data into unreadable string format
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
Using the two above methods you could encrypt the password string as it is being saved to the database and decrypt it on retrieval.
使用上述两种方法,您可以在将密码字符串保存到数据库时对其进行加密,并在检索时对其进行解密。
回答by user5076813
The simple way to do this is as follows:
这样做的简单方法如下:
string hashedpassword= FormsAuthentication.HashPasswordForStoringInConfigFile("your password", "SHA1");

