在.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;
}
我相信这将正确地散列字符串,并在函数返回时正确地从内存中擦除明文的任何副本,假设所提供的散列函数表现良好,并且不会对输入进行任何不擦除自身的复制。我是不是漏掉了什么?
https://stackoverflow.com/questions/14293344
复制相似问题