I am trying to copy the content of a SecureString
directly into unmanaged memory.
Microsoft recommends using Marshal.SecureStringToBSTR()
, Marshal.SecureStringToGlobalAllocAnsi()
, Marshal.SecureStringToGlobalAllocUnicode()
and the corresponding methods for COM usage.
I have a SecureString
with the chars '127' and '128'. Because ANSI uses 8 bit encoding I would expect that the following conversion into an unmanaged string would work:
var secureString = new SecureString();
secureString.AppendChar((char)127);
secureString.AppendChar((char)128);
IntPtr unmanagedString = Marshal.SecureStringToGlobalAllocAnsi(secureString);
var b1 = Marshal.ReadByte(unmanagedString, 0); // 127
var b2 = Marshal.ReadByte(unmanagedString, 1); // 63
But the '128' results in '63'.
I could use SecureStringToBSTR()
or SecureStringToGlobalAllocUnicode()
and omit every other byte. This would work. But I would like to understand why the ANSI method returns '63' instead of '128'.
I use C# with .Net Framework 4.8.