Hashing SecureString w .NET

W .NET mamy klasę SecureString, która jest bardzo dobra, dopóki nie spróbujesz jej użyć, a (na przykład) hash łańcucha, potrzebujesz tekstu jawnego. Miałem tutaj przejść do pisania funkcji, która będzie mieszać SecureString, biorąc pod uwagę funkcję mieszania, która pobiera tablicę bajtów i wyprowadza tablicę bajtów.

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;
}

Uważam, że poprawi to poprawnie ciąg znaków i poprawnie wyszuka wszystkie kopie tekstu jawnego z pamięci do czasu powrotu funkcji, zakładając, że dostarczona funkcja mieszania jest dobrze zachowana i nie tworzy żadnych kopii danych wejściowych, których nie ma szorować się. Czy coś tu przegapiłem?

questionAnswers(4)

yourAnswerToTheQuestion