如何将SecureString的内容写入Response流? [英] How do I write the contents of a SecureString to the Response stream?

查看:136
本文介绍了如何将SecureString的内容写入Response流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Asp.net MVC 5应用程序中,我有一个SecureString通过模型传递到我的视图中.我现在想将该SecureString的内容写入Response流,而不必先将其转换为字符串.我该如何实现?

In an Asp.net MVC 5 application I have a SecureString being passed into my view via the model. I would now like to write the contents of that SecureString to the Response stream without having to convert it to a string first. How can I achieve this?

推荐答案

这是我提出的HtmlHelper扩展.我确信它可以改进,但是可以实现我将SecureString写入Response流而无需将其表示为字符串的目的.

This is the HtmlHelper extension I have come up with. I am sure it can be improved, but it achieves my goal of writing a SecureString to the Response stream without it ever being represented as a string.

public static class SecureStringHelpers
{
    public static void WriteSecureStringToResponse(this HtmlHelper helper, SecureString secureString)
    {
        if (secureString != null)
        {
            IntPtr unmanagedString = IntPtr.Zero;

            var secureByteArray = new byte[2];

            try
            {
                unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(secureString);

                var offset = 0;
                var endOfString = false;

                do
                {
                    secureByteArray[0] = Marshal.ReadByte(unmanagedString, offset);
                    offset++;
                    secureByteArray[1] = Marshal.ReadByte(unmanagedString, offset);
                    offset++;

                    if (!(secureByteArray[0] == 0 && secureByteArray[1] == 0))
                    {
                        helper.ViewContext.Writer.Write(System.BitConverter.ToChar(secureByteArray, 0));
                    }
                    else
                    {
                        endOfString = true;
                    }

                } while (!endOfString);
            }
            finally
            {
                Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString);
                secureByteArray[0] = 0;
                secureByteArray[1] = 0;
            }
        }
    }
}

这篇关于如何将SecureString的内容写入Response流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆