我想用内VB.NET一个SecureString的varible和将其转换成一个或SHA1哈希SHA512。我将如何安全地SecureString的转换为字节数组HashAlgorithm.ComputeHash会接受吗?

有帮助吗?

解决方案

类型化它在C#,并转换为VB。希望它仍然有效!

Dim input As [Char]() = "Super Secret String".ToCharArray()
Dim secret As New SecureString()

For idx As Integer = 0 To input.Length - 1
    secret.AppendChar(input(idx))
Next
SecurePassword.MakeReadOnly()

Dim pBStr As IntPtr = Marshal.SecureStringToBSTR(secret)

Dim output As String = Marshal.PtrToStringBSTR(pBStr)
Marshal.FreeBSTR(pBStr)

Dim sha As SHA512 = New SHA512Managed()
Dim result As Byte() = sha.ComputeHash(Encoding.UTF8.GetBytes(output))

修改

由于它已经指出通过自己和其他几个人的意见,我希望把这种关注到这里。这样做是不是一个好主意。您正在字节到一个地方,不再是安全的。当然,你可以做到这一点,但你可能不应该

其他提示

什么,如果我们避免唯一使用的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;
    }

有什么我错过了吗?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top