在 .NET 中,我们有 SecureString 类,在您尝试使用它之前一切都很好,至于(例如)散列字符串,您需要明文。在给定一个接受字节数组并输出字节数组的哈希函数的情况下,我已经尝试编写一个将散列 SecureString 的函数。
private static byte[] HashSecureString(SecureString ss, Func<byte[], byte[]> hash)
{
// Convert the SecureString to a BSTR
IntPtr bstr = Marshal.SecureStringToBSTR(ss);
// BSTR contains the length of the string in bytes in an
// Int32 stored in the 4 bytes prior to the BSTR pointer
int length = Marshal.ReadInt32(bstr, -4);
// Allocate a byte array to copy the string into
byte[] bytes = new byte[length];
// Copy the BSTR to the byte array
Marshal.Copy(bstr, bytes, 0, length);
// Immediately destroy the BSTR as we don't need it any more
Marshal.ZeroFreeBSTR(bstr);
// Hash the byte array
byte[] hashed = hash(bytes);
// Destroy the plaintext copy in the byte array
for (int i = 0; i < length; i++) { bytes[i] = 0; }
// Return the hash
return hashed;
}
我相信这将正确地散列字符串,并在函数返回时正确地从内存中清除任何明文副本,假设提供的散列函数表现良好并且不会复制它没有的输入擦洗自己。我在这里错过了什么吗?