问题
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?
回答1:
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;
}
}
}
}
来源:https://stackoverflow.com/questions/28234906/how-do-i-write-the-contents-of-a-securestring-to-the-response-stream