How do a use a SecureString to create a SHA1 or SHA512 Hash?

坚强是说给别人听的谎言 提交于 2019-12-08 01:54:45

问题


I would like to use a SecureString varible within VB.NET and convert that to a SHA1 or SHA512 hash. How would I securely convert the SecureString to the Byte array that HashAlgorithm.ComputeHash will accept?


回答1:


What about that, if we avoid the only used String instance (output) and replace it with a character array. This would enable us to wipe this array after use:

    public static String SecureStringToMD5( SecureString password )
    {
        int passwordLength = password.Length;
        char[] passwordChars = new char[passwordLength];

        // Copy the password from SecureString to our char array
        IntPtr passwortPointer = Marshal.SecureStringToBSTR( password );
        Marshal.Copy( passwortPointer, passwordChars, 0, passwordLength );
        Marshal.ZeroFreeBSTR( passwortPointer );

        // Hash the char array
        MD5 md5Hasher = MD5.Create();
        byte[] hashedPasswordBytes = md5Hasher.ComputeHash( Encoding.Default.GetBytes( passwordChars ) );

        // Wipe the character array from memory
        for (int i = 0; i < passwordChars.Length; i++)
        {
            passwordChars[i] = '\0';
        }

        // Your implementation of representing the hash in a readable manner
        String hashString = ConvertToHexString( hashedPasswordBytes );

        // Return the result
        return hashString;
    }

Is there anything I missed?



来源:https://stackoverflow.com/questions/1529487/how-do-a-use-a-securestring-to-create-a-sha1-or-sha512-hash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!