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.