Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can cast the <code>IntPtr</code> of an unmanaged string buffer to <code>char*</code> and use the <code>SecureString(char*, int)</code> constructor.</p> <pre><code>// somehow, we come into posession of an IntPtr to a string // obviously, this would be a foolish way to come into it in // production, since stringOriginalContents is already in managed // code, and the lifetime can therefore not be guaranteed... var stringOriginalContents = "foobar"; IntPtr strPtr = Marshal.StringToHGlobalUni(stringOriginalContents); int strLen = stringOriginalContents.Length; int maxLen = 100; // we copy the IntPtr to a SecureString, and zero out the old location SecureString ssNew; unsafe { char* strUPtr = (char*)strPtr; // if we don't know the length, calculate //for (strLen = 0; *(strUPtr + strLen) != '\0' // // stop if the string is invalid // &amp;&amp; strLen &lt; maxLen; strLen++) // ; ssNew = new SecureString((char*)strPtr, strLen); // zero out the old memory and release, or use a Zero Free method //for (int i = 0; i &lt; strLen; i++) // *(strUPtr + i) = '\0'; //Marshal.FreeHGlobal(strPtr); // (only do one of these) Marshal.ZeroFreeGlobalAllocUnicode(strPtr); } // now the securestring has the protected data, and the old memory has been // zeroed, we can check that the securestring is correct. This, also should // not be in production code. string strInSecureString = Marshal.PtrToStringUni( Marshal.SecureStringToGlobalAllocUnicode(ssNew)); Assert.AreEqual(strInSecureString, stringOriginalContents); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload