【问题标题】:How do a use a SecureString to create a SHA1 or SHA512 Hash?如何使用 SecureString 创建 SHA1 或 SHA512 哈希?
【发布时间】:2010-12-04 12:13:12
【问题描述】:

我想在 VB.NET 中使用 SecureString 变量并将其转换为 SHA1 或 SHA512 哈希。如何安全地将 SecureString 转换为 HashAlgorithm.ComputeHash 将接受的 Byte 数组?

【问题讨论】:

    标签: .net hash sha1 sha512 securestring


    【解决方案1】:

    如果我们避免使用唯一使用的 String 实例(输出)并将其替换为字符数组,那又如何呢?这将使我们能够在使用后擦除这个数组:

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

    有什么我错过的吗?

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-20
    • 1970-01-01
    • 2010-09-07
    • 2011-11-26
    • 1970-01-01
    • 2018-06-07
    • 1970-01-01
    • 2012-02-09
    相关资源
    最近更新 更多