Domanda

Vorrei utilizzare un varible SecureString all'interno VB.NET e convertire che a uno SHA1 o SHA512 hash. Come faccio a convertire in modo sicuro il SecureString per la matrice di byte che HashAlgorithm.ComputeHash accetterà?

È stato utile?

Soluzione

digitata in c # e convertito in VB. Speriamo che funziona ancora!

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

modifica :

Come è stato sottolineato da me e pochi altri nei commenti, voglio portare questo all'attenzione qui. Fare questo non è una buona idea. Vi state spostando i byte in un luogo che non è più sicuro. Certo si può fare, ma probabilmente non dovrebbe

Altri suggerimenti

Che dire che se si evita l'unico caso usate String (output) e sostituirlo con un array di caratteri. Questo ci permetterebbe di cancellare questo array dopo l'uso:

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

C'è qualcosa che ho perso?

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top