我正在尝试进入 aSecureString的形式byte[],我可以保持 GC 固定,以 UTF-8 格式编码。我已经成功地做到了这一点,但使用 UTF-16(默认编码),但我无法弄清楚如何进行编码转换,而 GC 没有机会在某处创建数据的托管副本(数据需要保持安全)。
这是我到目前为止所拥有的(上下文:一种计算 SecureString 散列的算法)
public static byte[] Hash(this SecureString secureString, HashAlgorithm hashAlgorithm)
{
IntPtr bstr = Marshal.SecureStringToBSTR(secureString);
int length = Marshal.ReadInt32(bstr, -4);
var utf16Bytes = new byte[length];
GCHandle utf16BytesPin = GCHandle.Alloc(utf16Bytes, GCHandleType.Pinned);
byte[] utf8Bytes = null;
try
{
Marshal.Copy(bstr, utf16Bytes, 0, length);
Marshal.ZeroFreeBSTR(bstr);
// At this point I have the UTF-16 byte[] perfectly.
// The next line works at converting the encoding, but it does nothing
// to protect the data from being spread throughout memory.
utf8Bytes = Encoding.Convert(Encoding.Unicode, Encoding.UTF8, utf16Bytes);
return hashAlgorithm.ComputeHash(utf8Bytes);
}
finally
{
if (utf8Bytes != null)
{
for (var i = 0; i < utf8Bytes.Length; i++)
{
utf8Bytes[i] = 0;
}
}
for (var i = 0; i < utf16Bytes.Length; i++)
{
utf16Bytes[i] = 0;
}
utf16BytesPin.Free();
}
}
进行此转换的最佳方法是什么,我是否尝试在正确的位置进行转换,或者我应该以某种方式更早地进行转换?通过完全跳过 UTF-16 byte[] 步骤,这可以提高内存效率吗?
波斯汪
ibeautiful
相关分类