David G

David G

  • NA
  • 224
  • 14.7k

Rewriting unsafe code in order not to have to use it

Sep 11 2017 1:31 PM

Hey all I have the following unsafe code that I am looking to have converted into something other than that.

  1. SecureString sString = new SecureString();  
  2.   
  3. sString.AppendChar('8');  
  4. sString.AppendChar('1');  
  5. sString.AppendChar('*');  
  6. sString.AppendChar('Y');  
  7. //...more sString.AppendChar('') here  
  8. sString.AppendChar('Z');  
  9. sString.AppendChar('0');  
  10. sString.AppendChar('4');  
  11.   
  12. byte[] secureStringBytes = null;  
  13. IntPtr unmanagedBytes = Marshal.SecureStringToGlobalAllocAnsi(sString);  
  14.   
  15. try  
  16. {  
  17.    unsafe  
  18.    {  
  19.       byte* byteArray = (byte*)unmanagedBytes.ToPointer();  
  20.       byte* pEnd = byteArray;  
  21.   
  22.       while (*pEnd++ != 0) { }  
  23.   
  24.       int length = (int)((pEnd - byteArray) - 1);  
  25.       secureStringBytes = new byte[length];  
  26.   
  27.       for (int i = 0; i < length; ++i)  
  28.       {  
  29.          secureStringBytes[i] = *(byteArray + i);  
  30.       }  
  31.    }  
  32. }  
  33. finally  
  34. {  
  35.    Marshal.ZeroFreeGlobalAllocAnsi(unmanagedBytes);  
  36. }  
  37.   
  38. return secureStringBytes;  
Would anyone be able to help me out to change the code above so that I wont have to use /unsafe when compiling?

Answers (1)