如何在sql数据库中存储密码,是否需要转换用户输入的密码?我尝试将文本框中的密码保存为数据库中存储为空/空的表单中的密码模式。当我将密码模式禁用为文本时,工作正常。
发布于 2011-12-25 13:44:34
以加密格式存储密码将是一种很好的做法。您可以使用md5散列算法对其进行加密。以下是对字符串进行散列处理的示例代码
using System;
using System.Text;
using System.Security.Cryptography;
// Create an md5 sum string of this string
static public string GetMd5Sum(string str)
{
// First we need to convert the string into bytes, which
// means using a text encoder.
Encoder enc = System.Text.Encoding.Unicode.GetEncoder();
// Create a buffer large enough to hold the string
byte[] unicodeText = new byte[str.Length * 2];
enc.GetBytes(str.ToCharArray(), 0, str.Length, unicodeText, 0, true);
// Now that we have a byte array we can ask the CSP to hash it
MD5 md5 = new MD5CryptoServiceProvider();
byte[] result = md5.ComputeHash(unicodeText);
// Build the final string by converting each byte
// into hex and appending it to a StringBuilder
StringBuilder sb = new StringBuilder();
for (int i=0;i<result.Length;i++)
{
sb.Append(result[i].ToString("X2"));
}
// And return it
return sb.ToString();
}您不能将加密文本还原为普通字符串。
如果有任何疑问,请联系我们。
发布于 2011-12-25 18:45:45
我建议就地隐藏密码并将其保存在数据库中,通常我们不将明文保存在数据库中,因此它应该是加密的密码。
用于数据库设计的,
在数据库中添加Cipher text和key In table两个字段来存储密码过程和最终的用户密码。
然后,程序应该加密密码,并将Cipher text和key保存到前面提到的datatable列中。
然后,一旦用户再次登录,仅比较密文相等或不相等的过程将给出成功或失败的登录状态。
示例代码
/// <summary>
/// Encrypts the specified hash algorithm.
/// 1. Generates a cryptographic Hash Key for the provided text data.
/// </summary>
/// <param name="hashAlgorithm">The hash algorithm.</param>
/// <param name="dataToHash">The data to hash.</param>
/// <returns></returns>
public static string Encrypt(HashAlgorithm hashAlgorithm, string dataToHash)
{
var tabStringHex = new string[16];
var UTF8 = new System.Text.UTF8Encoding();
byte[] data = UTF8.GetBytes(dataToHash);
byte[] result = hashAlgorithm.ComputeHash(data);
var hexResult = new StringBuilder(result.Length);
for (int i = 0; i < result.Length; i++)
{
//// Convert to hexadecimal
hexResult.Append(result[i].ToString("X2"));
}
return hexResult.ToString();
}
/// <summary>
/// Determines whether [is hash match] [the specified hash algorithm].
/// </summary>
/// <param name="hashAlgorithm">The hash algorithm.</param>
/// <param name="hashedText">The hashed text.</param>
/// <param name="unhashedText">The unhashed text.</param>
/// <returns>
/// <c>true</c> if [is hash match] [the specified hash algorithm];
/// otherwise, <c>false</c>.
/// </returns>
public static bool IsHashMatch(HashAlgorithm hashAlgorithm,
string hashedText, string unhashedText)
{
string hashedTextToCompare = Encrypt(
hashAlgorithm, unhashedText);
return (String.Compare(hashedText,
hashedTextToCompare, false) == 0);
}发布于 2011-12-25 13:47:15
一般来说,它不需要转换它(至少根据我的经验),但出于更多的安全原因,一些用户使用encryption /decryption方法或将其转换为base64,最好的方法是单向算法,如Hash
阿里
https://stackoverflow.com/questions/8628350
复制相似问题