如何将SecureString的内容写入Response流?

时间:2015-01-30 11:27:08

标签: c# asp.net asp.net-mvc securestring

在Asp.net MVC 5应用程序中,我通过模型将SecureString传递到我的视图中。我现在想将SecureString的内容写入Response流,而不必先将其转换为字符串。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

这是我提出的HtmlHelper扩展。我确信它可以改进,但它实现了我的目标,即将SecureString写入Response流,而不会将其表示为字符串。

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;
            }
        }
    }
}