Sunday 1 May 2011

Display and show SecureStrings

using System;
namespace Test_A
{
    public static class MyExtension
    {
        // Get the contents of the secure string as a string
        public static string ToSystemString(this System.Security.SecureString s)
        {
            if (s == null)
                return null;
            System.IntPtr p = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(s);
            return System.Runtime.InteropServices.Marshal.PtrToStringBSTR(p);
        }
        // Set the secure string
        public static void SetSystemString(this System.Security.SecureString s, String v)
        {
            s.Clear();
            if (String.IsNullOrEmpty(v)) return;
            foreach (char c in v) s.AppendChar(c);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            System.Security.SecureString securePwd = new System.Security.SecureString();
            securePwd.SetSystemString("choo-choo-train");

            Console.WriteLine("Password <{0}> len={1}", securePwd, securePwd.Length);
            Console.WriteLine("  Actual <{0}>", securePwd.ToSystemString());
        }
    }
}