【发布时间】:2013-12-08 01:33:45
【问题描述】:
我的数据库中有一个表,其中包含敏感数据,例如密码字段我想在将数据插入表之前对其进行加密,然后我不想解密数据,但我只想将加密密码与输入密码进行比较而不解密
【问题讨论】:
-
不清楚问题是什么...?
标签: c#
我的数据库中有一个表,其中包含敏感数据,例如密码字段我想在将数据插入表之前对其进行加密,然后我不想解密数据,但我只想将加密密码与输入密码进行比较而不解密
【问题讨论】:
标签: c#
我会推荐你hashing the passwords with salt 并将散列密码和盐存储到数据库中。还有一个 article 讨论这个话题。
【讨论】:
如果您不需要解密实际需要散列的数据,例如SHA1 或 .NET 在 System.Security.Cryptography 命名空间中提供的类似算法。
【讨论】:
使用 sha256 之类的散列函数:
using System.Security.Cryptography;
/// <summary>
/// Hash the given string with sha256
/// </summary>
/// <param name="password">the string to hash</param>
/// <returns>The hex representation of the hash</returns>
static string sha256(string password)
{
SHA256Managed crypt = new SHA256Managed();
string hash = String.Empty;
byte[] crypto = crypt.ComputeHash(Encoding.ASCII.GetBytes(password), 0, Encoding.ASCII.GetByteCount(password));
foreach (byte bit in crypto)
{
hash += bit.ToString("x2");
}
return hash;
}
它总是会为相同的输入提供相同的输出,因此您可以比较散列值。您还应该考虑对输入进行加盐(预先或附加一些特定于您的应用程序/程序的值,以希望减少彩虹表的用处)
【讨论】:
我有 2 个函数来加密和解密数据:
第一个函数用于解密数据,第二个函数用于加密数据。
using System.Security.Cryptography;
using System.Collections.Generic;
using System.ComponentModel;
private static readonly byte[] _key = { 0xA1, 0xF1, 0xA6, 0xBB, 0xA2, 0x5A, 0x37, 0x6F, 0x81, 0x2E, 0x17, 0x41, 0x72, 0x2C, 0x43, 0x27 };
private static readonly byte[] _initVector = { 0xE1, 0xF1, 0xA6, 0xBB, 0xA9, 0x5B, 0x31, 0x2F, 0x81, 0x2E, 0x17, 0x4C, 0xA2, 0x81, 0x53, 0x61 };
private static string Decrypt(string Value)
{
SymmetricAlgorithm mCSP;
ICryptoTransform ct = null;
MemoryStream ms = null;
CryptoStream cs = null;
byte[] byt;
byte[] _result;
mCSP = new RijndaelManaged();
try
{
mCSP.Key = _key;
mCSP.IV = _initVector;
ct = mCSP.CreateDecryptor(mCSP.Key, mCSP.IV);
byt = Convert.FromBase64String(Value);
ms = new MemoryStream();
cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
cs.Write(byt, 0, byt.Length);
cs.FlushFinalBlock();
cs.Close();
_result = ms.ToArray();
}
catch
{
_result = null;
}
finally
{
if (ct != null)
ct.Dispose();
if (ms != null)
ms.Dispose();
if (cs != null)
cs.Dispose();
}
return ASCIIEncoding.UTF8.GetString(_result);
}
private static string Encrypt(string Password)
{
if (string.IsNullOrEmpty(Password))
return string.Empty;
byte[] Value = Encoding.UTF8.GetBytes(Password);
SymmetricAlgorithm mCSP = new RijndaelManaged();
mCSP.Key = _key;
mCSP.IV = _initVector;
using (ICryptoTransform ct = mCSP.CreateEncryptor(mCSP.Key, mCSP.IV))
{
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, ct, CryptoStreamMode.Write))
{
cs.Write(Value, 0, Value.Length);
cs.FlushFinalBlock();
cs.Close();
return Convert.ToBase64String(ms.ToArray());
}
}
}
}
希望这两个功能可以帮到你。
【讨论】: