Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to erase StringBuilder memory with zero

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:

  1. Iterate through the StringBuilder characters and assign '\0'. Is this guaranteed to use the same memory if I have allocated sufficient memory initially?
  2. 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.

like image 243
hasmit Avatar asked Dec 03 '13 16:12

hasmit


People also ask

How do you clear a value in string builder?

Two ways that work: Use stringBuilderObj. setLength(0) . Allocate a new one with new StringBuilder() instead of clearing the buffer.

How do I remove all characters from StringBuilder?

StringBuilder delete() in Java with Examples The delete(int start, int end) method of StringBuilder class removes the characters starting from index start to index end-1 from String contained by StringBuilder.

How do I remove spaces from a string builder?

The trim() method removes all white space at the end of the string. That's correct. trim() only removes whitespace at the beginning or end of a String. To remove spaces in the middle, you need to call replaceAll().


1 Answers

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.

like image 133
David Heffernan Avatar answered Oct 05 '22 02:10

David Heffernan