Search code examples
vb.netsecurestring

Why does SecureString not have an overloaded constructor?


Consider the following:

_securePassword = New SecureString()
For Each character As Char In password
    _securePassword.AppendChar(character)
Next

Surprisingly, the documentation seems to imply this is the "best practice" way to populate a SecureString with actual information:

When creating a string from a character-at-a-time ...

My question

Why not include a New SecureString(password)?

This seems like pure boiler-plate code for me as a consumer.


Solution

  • The docs tell you why:

    A SecureString object should never be constructed from a String, because the sensitive data is already subject to the memory persistence consequences of the immutable String class. The best way to construct a SecureString object is from a character-at-a-time unmanaged source, such as the Console.ReadKey method.

    So basically, you should never have the string in memory as that is insecure. There's no way for you to guarantee that the string has been removed from vulnerable memory.