Search code examples
c#.netstringsecurestring

How to check if SecureString contains certain text?


I'm trying to see whether my SecureString contains a particular text.

I could do it this way:

var sstr = new SecureString();
...
//sstr is now appended with a set of characters
if(sstr.ToString().Contains("Hello world")) {
   //do something
}

This works, but the moment when I do sstr.ToString(), it seems like I've just written the content in SecureString into the memory and this totally defeats the purpose of using SecureString.

How should I check whether a SecureString contains some text?


Solution

  • The best approach to check it without defeating SecureString purpose is in your Process output buffer loop, before it gets into the SecureString secured buffer. But in the best case, doing so you would create a plain memory string of the last N characters (being N the "Hello world" length) which would be a bit insecure. Less insecure than calling SecureString.ToString() of course 'cause as you already stated, it would store all the text in plain memory defeating the purpose.