ComputeSHA256 From Stream

OSVBNET 1,386 Reputation points
2022-09-10T22:51:22.713+00:00

Hello,
I've got 2 questions about my function to calculate the Sha256 from a MemoryStream.

    Private Function ComputeSHA256(ByVal InputStream As Stream) As String  
        InputStream.Position = 0  
        Dim MyString As String = String.Empty  
        Using MySHA256 As SHA256 = SHA256Managed.Create()  
            Using InputStream  
                For Each MyHash In MySHA256.ComputeHash(InputStream)  
                    MyString += MyHash.ToString("x2")  
                Next  
            End Using  
        End Using  
        ComputeSHA256 = MyString  
    End Function  
  1. Position = 0 needed?
  2. The stream I pass to the function must not get altered or disposed in anyway, is my method safe?
    Thanks :)
VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,580 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 112.5K Reputation points
    2022-09-11T07:41:57.707+00:00

    I think that different behaviours are possible depending on the purpose of this function. If it is "get hash values from the current position of the stream, ignoring other data that maybe were already processed by other functions", then Position = 0 must be removed. But if it is "get hash values from the beginning of the stream", then Position = 0 is advisable.

    For the second issue, the using InputStream must be removed, because it will alter (dispose) the stream. If required by the callers, you can also keep the current position (Dim p = InputStream.Position at the begining, InputStream.Position = p at the end, in case you want to reread the hash).


0 additional answers

Sort by: Most helpful