Is there any benefit to using SecureString in ASP.NET?

As you correctly deduced, and others already mentioned, it makes little sense to use SecureString to store security-sensitive data that comes from an ASP.NET form, because that data is already present in memory in plain text.

There are other scenarios, however, where the use of SecureString is recommended, because the sensitive data is created by the program itself and should not remain in memory after it’s done working with it. For instance, creating a SharePoint site programmatically, or transferring authentication credentials from one system to another.

Back in the good old days, it was easier to ensure that the lifetime of sensitive data was as short as possible. It could be allocated on the stack and cleared as soon as the program was done using it:

char secret[512];
generate_secret(secret, sizeof(secret));
do_something_with(secret);
memset(secret, 0, sizeof(secret));
// Secret data is now gone.

Such an approach is not possible with managed strings, though, mainly because:

  • They’re not allocated on the stack,
  • They’re immutable, so they cannot be cleared,
  • They’re not disposable, so there is no guarantee about the time when the GC will free the data. It might even never be freed, depending on memory conditions.

SecureString tries to solve that problem by being mutable and disposable, which allows one to write:

using (SecureString secret = new SecureString()) {
    GenerateSecret(secret);
    secret.MakeReadOnly();
    DoSomethingWith(secret);
}
// Secret data is now gone.

Leave a Comment