Convert SecureString to string

Because SecureString is a sealed class , we have to work with pointers and unmanaged resources to get to the data.


static class SecureStringExtensions
{
    public static string GetString(
        this SecureString source)
    {
        string result = null;
        int length = source.Length;
        IntPtr pointer = IntPtr.Zero;
        char[] chars = new char[length];

        try
        {
            pointer = Marshal.SecureStringToBSTR(source);
            Marshal.Copy(pointer, chars, 0, length);

            result = string.Join("", chars);
        }
        finally
        {
            if (pointer != IntPtr.Zero)
            {
                Marshal.ZeroFreeBSTR(pointer);
            }
        }

        return result;
    }
}


The Marshal class actually has a BSTR method for use with the SecureString. Just remember when working with unmanaged resources you will need to manually release and free the pointers that you used.

Basically if you have not worked with Marshal and pointers in C# you will have to get the pointer to the char[] from the secure string. Then we use Marshal.Copy to marshal the *char[] to our managed char[] using the length of the string. A simple string.Join and we are home free. Just remember to zero out our pointer to release the resources.

Comments

Popular Posts