简体   繁体   中英

How to decrypt an encrypted key from database and use it for fetching data from database in C# asp.net . Encryption is done with AES

Here the thing is that I used AES encryption to encrypt a value named KeyValue and I need to use that key value to get data from the database . when i am using the KeyValue in btnHide_Click and btnSearch_Click it is not getting decrypted and i am not able to use it for getting the image and text field from database. please help me how to write the code for decryption and where to write it. I am a beginner . So a little explanation will be a great thing for me to understand how it was done. thanks in advance .

I have used the encryption method given in this link

http://www.aspsnippets.com/Articles/Encrypt-and-Decrypt-Username-or-Password-stored-in-database-in-ASPNet-using-C-and-VBNet.aspx

public partial class _Default : System.Web.UI.Page
 {
    InsertValue ivo = new InsertValue();
    ImageEncryptEntities ctx = new ImageEncryptEntities();
     protected void Page_Load(object sender, EventArgs e)
   {
    if (!IsPostBack)
    {
        Tab1.CssClass = "Clicked";
        MainView.ActiveViewIndex = 0;
    }
}



protected void Upload(object sender, EventArgs e)
{

    if (FileUpload1.HasFile)
    {
        FileUpload1.SaveAs(MapPath("~/Images/" + FileUpload1.FileName));

        Image1.ImageUrl = "~/Images/" + FileUpload1.FileName;



    }
}

protected void btnSave_Click(object sender, EventArgs e)
{
    ivo.Insert(Image1.ImageUrl, TextBox1.Text, txtKeyValue.Text);
    Response.Write("Records Saved");
}

protected void btnHide_Click(object sender, EventArgs e)
{
    var keystrike = (from p in ctx.tblPhotos
                     where p.KeyValue.Equals(txtValue.Text)
                     select p).SingleOrDefault();
    try
    {
        Image1.ImageUrl = keystrike.Picture;
        lblMessage.Text = keystrike.Text;



    }
    catch (NullReferenceException)
    {
        Image1.ImageUrl = "";
        lblMessage.Text = "No key match";
    }
}
protected void Tab1_Click(object sender, EventArgs e)
{
    Tab1.CssClass = "Clicked";
    Tab2.CssClass = "Initial";

    MainView.ActiveViewIndex = 0;
}

protected void Tab2_Click(object sender, EventArgs e)
{
    Tab1.CssClass = "Initial";
    Tab2.CssClass = "Clicked";

    MainView.ActiveViewIndex = 1;
}


protected void btnSearch_Click(object sender, EventArgs e)
{
    var keystrike = (from p in ctx.tblPhotos
                     where p.KeyValue.Equals(txtKey.Text)
                     select p).SingleOrDefault();

    try
    {
        Image2.ImageUrl = keystrike.Picture;

    }
    catch (NullReferenceException)
    {
        Image2.ImageUrl = "";
        lblMessage.Text = "No key match";
    }

}

These are the two entity framework classes GetValue and InsertValue

    public class GetValue
   {
     SqlConnection cnn = new SqlConnection("Data Source=.;Initial          Catalog=ImageEncrypt;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework");

public SqlDataReader Get(string mstrKeyValue)
{
    cnn.Open();
    SqlCommand cmd = new SqlCommand("spGetValues", cnn);
    cmd.CommandType = System.Data.CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@KeyValue",mstrKeyValue);
    SqlDataReader dr = cmd.ExecuteReader();
    return dr;
}




      public class InsertValue
      {
           SqlConnection cnn = new SqlConnection("DataSource=.;InitialCatalog=ImageEncrypt;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework");

public void Insert(string mstrPicture, string mstrText, string mstrKeyValue)
{
    cnn.Open();
    SqlCommand cmd = new SqlCommand("spInsertValues", cnn);
    cmd.CommandType = System.Data.CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@Picture", mstrPicture);
    cmd.Parameters.AddWithValue("@Text", mstrText);
    cmd.Parameters.AddWithValue("@KeyValue", Encrypt(mstrKeyValue.Trim()));
    cmd.ExecuteNonQuery();

}
       private string Encrypt(string clearText)
       {
    string EncryptionKey = "MAKV2SPBNI99212";
    byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
    using (Aes encryptor = Aes.Create())
    {
        Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
        encryptor.Key = pdb.GetBytes(32);
        encryptor.IV = pdb.GetBytes(16);
        using (MemoryStream ms = new MemoryStream())
        {
            using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
            {
                cs.Write(clearBytes, 0, clearBytes.Length);
                cs.Close();
            }
            clearText = Convert.ToBase64String(ms.ToArray());
        }
    }
    return clearText;
}

Please show this answer

when you insert value.

 cmd.Parameters.AddWithValue("@KeyValue", Encrypt(mstrKeyValue.Trim()));

and then you get value

   Datatable dt=new Datatable();
    string dyc_val=decrypt(dt.rows[0]["encryptvalue"].tostring());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM