0

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.

Servy
  • 202,030
  • 26
  • 332
  • 449
Matt
  • 1,674
  • 2
  • 16
  • 34
  • 1
    I think the idea is that you should never have the entire password in a string variable at any given time. So in your example code you shouldn't have a **password** string in the first place. – Sal Jul 24 '17 at 14:44
  • 1
    Think about what you are asking. The very existence of this class IS to avoid doing just that. The whole idea is not to have the whole string present in memory as a whole. – JuanR Jul 24 '17 at 14:46

2 Answers2

5

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.

DavidG
  • 113,891
  • 12
  • 217
  • 223
1

Because then the string you're trying to secure is already present in memory as a normal String, negating any benefit of keeping it as a whole item only within a SecureString.

James Thorpe
  • 31,411
  • 5
  • 72
  • 93