我想将文本框中的数据存储到数据库中,但应加密 然后通过一些搜索键显示这些数据 我使用了一种加密方法,并且工作正常 主要问题是显示解密数据
string encClass = AESencDec.Decrypt(txt_class.Text);
SqlConnection connection = new SqlConnection(ConnectionString);
SqlCommand command = new SqlCommand("select * from nuclear where Class='" + encClass + "'", connection);
connection.Open();
command.CommandType = CommandType.Text;
command.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter();
da.Fill(dt);
dataGridView1.DataSource = dt;
connection.Close();
它实际上从数据库中读取数据并显示但我想知道如何将其显示为解密???
这是我用于此项目的Decrypt类
public static string Decrypt(string text)
{
string hash = "f0xle@rn";
byte[] plaintextbytes = Convert.FromBase64String(text);
using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
{
byte[] keys = md5.ComputeHash(UTF8Encoding.UTF8.GetBytes(hash));
using (TripleDESCryptoServiceProvider triples = new TripleDESCryptoServiceProvider() { Key = keys, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 })
{
ICryptoTransform transform = triples.CreateDecryptor();
byte[] results = transform.TransformFinalBlock(plaintextbytes, 0, plaintextbytes.Length);
return UTF8Encoding.UTF8.GetString(results);
}
}
}
这是加密功能
public static string Encrypt(string text)
{
string hash = "f0xle@rn";
byte[] plaintextbytes = UTF8Encoding.UTF8.GetBytes(text);
using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
{
byte[] keys = md5.ComputeHash(UTF8Encoding.UTF8.GetBytes(hash));
using (TripleDESCryptoServiceProvider triples = new TripleDESCryptoServiceProvider() {Key = keys, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 })
{
ICryptoTransform transform = triples.CreateEncryptor();
byte[] results = transform.TransformFinalBlock(plaintextbytes, 0, plaintextbytes.Length);
return Convert.ToBase64String(results);
}
}
}
答案 0 :(得分:0)
这是一个示例,显示使用测试数据更新数据表。您可以更新它以使用数据库中的任何列名称:
int rowCount = 5;
DataTable table = new DataTable();
table.Columns.Add(new DataColumn("id", typeof(String)));
table.Columns.Add(new DataColumn("encrypted", typeof(String)));
table.Columns.Add(new DataColumn("decrypted", typeof(String)));
//Write test encrypted data to data table
for(int i = 0; i < rowCount; i++)
{
string clearText = "test" + i.ToString();
string cipherText = Encrypt(clearText);
table.Rows.Add(new object[] {i.ToString(), cipherText, ""});
}
//Decrypt each item, and assign result to decrypted column
foreach (DataRow row in table.Rows)
{
row["decrypted"] = Decrypt(row["encrypted"].ToString());
}
因此,您的数据适配器会填充数据表。您可以在将行应用到数据源之前迭代行并解密:
da.Fill(dt);
foreach(DataRow row in dt.Rows)
{
row["name of encrypted column"] = Decrypt(row["name of encrypted column"].ToString());
}
dataGridView1.DataSource = dt;