Question

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?

Was it helpful?

Solution

Typed it up in c# and converted to VB. Hopefully it still works!

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))

edit:

As it has been pointed out by myself and a few others in the comments, I want to bring this to attention here. Doing this isn't a good idea. You are moving the bytes to a place that is no longer secure. Sure you CAN do it, but you probably shouldn't

OTHER TIPS

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?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top