views:

217

answers:

1

I would like to create a variable, a secure one, that is more or less a CONST to use in my code. I've looked into using System.Security.SecureString, and that looks like it could be the ticket as I don't want the user to find out this password. The only problem comes with initializing it. In most cases, it looks like the SecureString is best "set" by user keypress. I don't want this. One option I've come accross looks like this:

unsafe public static void Main()
   {
      SecureString testString;
      // Define the string value to assign to a new secure string.
      char[] chars = { 't', 'e', 's', 't' };

      // Instantiate a new secure string.
      fixed(char* pChars = chars)
      {
         testString = new SecureString(pChars, chars.Length);
      }
      // Display secure string length.
      Console.WriteLine("The length of the string is {0} characters.", 
                        testString.Length);
   }

Only problem is, the char array 't','e','s','t' is probably still packed together in memory after a compile. Is there any good way to set the value of a SecureString to a constant value before compile time and have that value be scrambled?

A: 

You could set every entry in chars to some strongly random value to remove the value from dynamic memory. The string will still be there in the executable, though.

Steve Gilham