1

I am writing an API which will accept a standard string for a username and password as a means of compatibility. I know standard strings are not ideal and my API already uses the SecureString class for this purpose and my summaries above methods warn the API user of this. However since the API may not be used in an environment where SecureString is possible, I have written a function to really destroy a string as soon as my SecureString Extention methods convert the standard string to SecureString.

    public static void CrunchString(ref string str) {
        int l = str.Length;
        unsafe {
            fixed (char* c = str) {
                for (int i = 0; i < l; ++i) {
                    c[i] = (char)0x00;
                }
            }
        }
        str = null;
    }

Is this the right way about it or is there a better solution? Are there any consequences that could be forseen by destroying the string in this nature in-place?

The aim here is to really destroy the un secured string early on and to thoroughly remove it from normal memory.

Gelion
  • 531
  • 7
  • 18
  • 2
    You better hope that string isn't interned. – mjwills Jul 31 '18 at 10:00
  • 1
    Possible duplicate of [Can you change the contents of a (immutable) string via an unsafe method?](https://stackoverflow.com/questions/32464944/can-you-change-the-contents-of-a-immutable-string-via-an-unsafe-method) – mjwills Jul 31 '18 at 10:01
  • I´m not sure why one would ever need this. What do you mean by "destroy a string"? Isn´t the normal GC enough, so when the variable is out of scope it will be collected anyway? You may have a look at https://stackoverflow.com/questions/2423111/strings-and-garbage-collection. Anyway what has the password-tag to do with that? – MakePeaceGreatAgain Jul 31 '18 at 10:04
  • *"convert the standard string to SecureString"* - that's already non-secure. You shouldn't have strings at all. Rather construct `SecureString` directly (using `Append`, `InsertAt`, `DeleteAt` and `Clear` methods) as characters are typed. My guess that's how specialized controls (e.g. [PasswordBox](https://msdn.microsoft.com/en-us/library/system.windows.controls.passwordbox.securepassword(v=vs.110).aspx) in wpf) are doing it. – Sinatr Jul 31 '18 at 10:26
  • @Sinatr - So what about Web forms passing in strings (ASP.NET PHP)? As far as I can remember ASP.NET doesnt pass SecureString objects... – Gelion Jul 31 '18 at 10:34
  • @TheGeneral the fixed keyword here prevents the runtime from that memory from being moved during the unsafe operation. – Gelion Jul 31 '18 at 11:33
  • http://mattwarren.org/2016/10/26/How-does-the-fixed-keyword-work/ yeah i was wondering if it did an internal copy, but it doesn't, good luck though – TheGeneral Jul 31 '18 at 11:43

0 Answers0