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:
'\0'
. Is
this guaranteed to use the same memory if I have allocated
sufficient memory initially?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.
Two ways that work: Use stringBuilderObj. setLength(0) . Allocate a new one with new StringBuilder() instead of clearing the buffer.
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.
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().
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With