在.NET中,我們有SecureString類,在您嘗試使用它之前,這一切都很好,例如對於字符串進行散列,您需要明文。我已經在這裏寫了一個函數來散列一個SecureString,給定一個散列函數,它需要一個字節數組並輸出一個字節數組。在.NET中散列安全字符串
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;
}
我相信這將正確地散列字符串,並通過函數返回時,假設所提供的哈希函數性能良好,並且不作任何副本的時間將正確擦洗明文的任何副本從內存它不會擦洗自己的輸入。我錯過了什麼嗎?
。注意,SecureString的可能是矯枉過正。如果攻擊者可以讀取你的記憶,你就會100%失去。 – usr
@usr SecureString使用受保護的內存,因爲只有調用進程可以解密內存位置。如果您希望在應用程序崩潰時創建一個小型轉儲並將其發送給開發人員,此功能特別有用:除了您的密碼外,他們還可以獲得整個上下文,堆棧跟蹤等。 –
@ M.Stramm是的,對於「冷啓動」而不是運行系統(這是攻擊面的99%)。可以讀取內存的攻擊者通常可以讀取按鍵和數據等。有有效的用例。我給你這個。 – usr