Share via

ComputeSHA256 From Stream

OSVBNET 1,401 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 :)
Developer technologies | VB
0 comments No comments

Answer accepted by question author

Viorel 127K 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).

Was this answer helpful?


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.