How to erase StringBuilder memory with zero

c#, security, stringbuilder

Solution

The simple answer is that none of the methods you are proposing are secure. And once you put a password into `StringBuilder`, it's game over. Don't use `StringBuilder` for storing a password, use `SecureString` instead, if you have to use a managed class.

Now, you say in comments that you are calling `CredUIPromptForCredentials`. So do that, but don't put the password into a `StringBuilder`. Put it into unmanaged memory, for instance allocated with `Marshal.AllocHGlobal`. Then when you are done with that unmanaged memory, do what the docs for `CredUIPromptForCredentials` say and call `SecureZeroMemory` before you deallocate the unmanaged memory.

I note that the pinvoke.net translation uses `StringBuilder` for the password parameter. Perhaps that is what has led you astray. You don't need to do that (you should not do that). Declare the parameter to have type `IntPtr` instead.

Problem

I have a password stored in `StringBuilder` object. I am looking for a way to erase the password in memory. Does any of the following methods will achieve this: - Iterate through the StringBuilder characters and assign `'\0'`. Is this guaranteed to use the same memory if I have allocated sufficient memory initially? - Can I use any unmanaged API like `ZeroMemory()` or `SecureZeroMemory()` with `StringBuilder`? Any code samples? EDIT: Using `SecureString` is not an option for me since I am calling `CredUIPromptForCredentials()` to get the credentials.

Original source