简体   繁体   English

使用itemdatabound在转发器项目中解密

[英]decrypt in repeater item using itemdatabound

I am displaying image using the asp repeater and i wish to encrypt it but i have no idea how to decrypt everytime the repeater fire a item 我正在使用ASP中继器显示图像,我希望对其进行加密,但是我不知道每次中继器发射物品时如何解密

//client side <asp:Repeater ID="Repeater1" runat="server" OnItemCommand="Repeater1_ItemCommand" OnItemDataBound="Repeater1_ItemDataBound" >

`//server side
//decrypt method
private void DecryptFile(string inputFile, string outputFile)
    {

        {
            string password = @"myKey123"; // Your Key Here

            UnicodeEncoding UE = new UnicodeEncoding();
            byte[] key = UE.GetBytes(password);

            FileStream fsCrypt = new FileStream(inputFile, FileMode.Open);

            RijndaelManaged RMCrypto = new RijndaelManaged();

            CryptoStream cs = new CryptoStream(fsCrypt,
                RMCrypto.CreateDecryptor(key, key),
                CryptoStreamMode.Read);

            FileStream fsOut = new FileStream(outputFile, FileMode.Create);

            int data;
            while ((data = cs.ReadByte()) != -1)
                fsOut.WriteByte((byte)data);

            fsOut.Close();
            cs.Close();
            fsCrypt.Close();

        }
    }

` `

protected void Repeater1_ItemDataBound(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName =="openimage")
            {
                string[] commandArgs = e.CommandArgument.ToString().Split(new char[] { ',' });
                DecryptFile(commandArgs[0], commandArgs[0]);

            }
        }

when i try to run it, it gave me the error CS0123: No overload for 'Repeater1_ItemDataBound' matches delegate 'System.Web.UI.WebControls.RepeaterItemEventHandler' 当我尝试运行它时,它给了我错误CS0123:'Repeater1_ItemDataBound'没有重载匹配委托'System.Web.UI.WebControls.RepeaterItemEventHandler'

Please help me as i am new to c# 请帮助我,因为我是C#新手

The method signature on your event handler is incorrect. 您的事件处理程序上的方法签名不正确。 You need to change RepeaterCommandEventArgs to RepeaterItemEventArgs . 您需要将RepeaterCommandEventArgs更改为RepeaterItemEventArgs

protected void Repeater1_ItemDataBound(object source, RepeaterItemEventArgs e)
{
}

That will fix your error, however with what you're trying to do I'm not sure that this would be a good way to display the decrypted image. 这样可以解决您的错误,但是对于您要尝试执行的操作,我不确定这是否是显示解密图像的好方法。 What I recommend is creating a generic handler that will decrypt your image on the fly by passing in the id, once the id is passed you can decrypt and write out to the screen. 我建议创建一个通用处理程序,该处理程序将通过传入ID即时解密您的图像,一旦传递ID,您就可以解密并写到屏幕上。

public class DisplayImage : IHttpHandler
{

    /// <summary>
    /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler" /> interface.
    /// </summary>
    /// <param name="context">An <see cref="T:System.Web.HttpContext" /> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
    public void ProcessRequest(HttpContext context)
    {
        if (!this.HasAccess())
        {
            context.Response.End();
            return;
        }

        string requestFileName = context.Request.QueryString["FileName"];

        DecryptFile(requestFileName, context);
    }

    /// <summary>
    /// Gets a value indicating whether another request can use the <see cref="T:System.Web.IHttpHandler" /> instance.
    /// </summary>
    /// <value><c>true</c> if this instance is reusable; otherwise, <c>false</c>.</value>
    /// <returns>true if the <see cref="T:System.Web.IHttpHandler" /> instance is reusable; otherwise, false.</returns>
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

    /// <summary>
    /// Determines whether the user has access to display an image.
    /// </summary>
    /// <returns><c>true</c> if this instance has access; otherwise, <c>false</c>.</returns>
    private bool HasAccess()
    {
        // Check if user is logged in and has permissions
        // to do the decryption
        // use your own logic here
        return true;
    }

    /// <summary>
    /// Decrypts the file and outputs to the response buffer
    /// </summary>
    /// <param name="inputFile">The input file.</param>
    /// <param name="context">The context.</param>
    private void DecryptFile(string inputFile, HttpContext context)
    {
        if (PathTraversalCheck(inputFile))
        {
            context.Response.End();
            return;
        }

        // get the base directory
        inputFile = Path.Combine(ConfigurationManager.AppSettings["filedirectory"], inputFile);

        if (!File.Exists())
        {
            context.Response.End();
            return;
        }

        string password = @"myKey123"; // Your Key Here

        UnicodeEncoding UE = new UnicodeEncoding();
        byte[] key = UE.GetBytes(password);

        using (FileStream encryptedFile = new FileStream(inputFile, FileMode.Open))
        {
            RijndaelManaged rijndael = new RijndaelManaged();

            using (MemoryStream output = new MemoryStream())
            {
                using (CryptoStream cryptoStream = new CryptoStream(encryptedFile, rijndael.CreateDecryptor(key, key), CryptoStreamMode.Read))
                {
                    // write to the memory stream
                    var buffer = new byte[1024];
                    var read = cryptoStream.Read(buffer, 0, buffer.Length);
                    while (read > 0)
                    {
                        output.Write(buffer, 0, read);
                        read = cryptoStream.Read(buffer, 0, buffer.Length);
                    }

                    cryptoStream.Flush();

                    // output to the response buffer
                    context.Response.ContentType = "image/jpeg";
                    context.Response.BinaryWrite(output.ToArray());
                }
            }

        }
    }

    /// <summary>
    /// Checks for a path traversal attack
    /// </summary>
    /// <param name="inputFile">The input file.</param>
    /// <returns>System.String.</returns>
    private bool PathTraversalCheck(string inputFile)
    {
        if (inputFile.Contains(".") || inputFile.Contains('\\') || inputFile.Contains('/'))
        {
            return true;
        }

        return false;
    }
}

In your repeater you simply have to put the an img tag with the src set to the handler. 在转发器中,您只需要将src设置为img的img标签放置到处理程序中即可。

<ItemTemplate>
    <img src="DisplayImage.ashx?FIleName=<%# DataBinder.Eval(Container.DataItem, "FileName" )%>" />
</ItemTemplate>

Something else I would change as well is I would not store my key in the source code, that's easily readable by decompiling the dlls. 我还需要更改的其他地方是,我不会将密钥存储在源代码中,而通过对dll进行反编译很容易读取。 Instead you should store it in your web.config and encrypt the web.config. 相反,您应该将其存储在web.config中并加密web.config。 Check out http://msdn.microsoft.com/library/dtkwfdky.aspx for instructions. 请查看http://msdn.microsoft.com/library/dtkwfdky.aspx以获取说明。

You need to correct repeater events: 您需要更正中继器事件:

void Repeater1_ItemDataBound(Object Sender, RepeaterItemEventArgs e) {

}

Also, for handling event inside repeater, you should move your code to Repeater1__ItemCommand event. 另外,要处理转发器中的事件,应将代码移至Repeater1__ItemCommand事件。

void Repeater1__ItemCommand(Object Sender, RepeaterCommandEventArgs e) {       
        if (e.CommandName =="openimage")
        {
            string[] commandArgs = e.CommandArgument.ToString().Split(new char[] { ',' });
            DecryptFile(commandArgs[0], commandArgs[0]);

        }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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