By "securely", I mean in such a way that GC doesn't move it around in memory, copying is kept to a minimum, and it's removed from memory as soon as it's no longer needed.
I have the code for generating a random password, but I need to display it and I'd rather not use a string
to do so. The password is currently generated in a SecureString
which I can put in a fixed/pinned buffer to work with. What's the most secure way I can render it to the user?
I don't know of any way to display a SecureString
without converting it to a normal string. In any event, Microsoft themselves don't even recommend secure SecureString
anymore. This is linked to from the official msdn documentation page:
DE0001: SecureString shouldn't be used
Motivation
- The purpose of
SecureString
is to avoid having secrets stored in the process memory as plain text.- However, even on Windows,
SecureString
doesn't exist as an OS concept.
- It just makes the window getting the plain text shorter; it doesn't fully prevent it as .NET still has to convert the string to a plain text representation.
- The benefit is that the plain text representation doesn't hang around as an instance of
System.String
-- the lifetime of the native buffer is shorter.- The contents of the array is unencrypted except on .NET Framework.
- In .NET Framework, the contents of the internal char array is encrypted. .NET doesn't support encryption in all environments, either due to missing APIs or key management issues.
Recommendation
Don't use
SecureString
for new code. When porting code to .NET Core, consider that the contents of the array are not encrypted in memory.The general approach of dealing with credentials is to avoid them and instead rely on other means to authenticate, such as certificates or Windows authentication.
SecureString
isn't really effective protection for sensitive information, it just limits the attack window a bit and obfuscates things.
My personal opinion is that if you are going to show it to the user anyway, you should really be worrying about how accessible it is inside the application. And, in general, the safety of the memory of an application is the responsibility of the OS and the physical security of the hardware. If you need to worry about unauthorized access to application memory, you already have a much bigger security problem.