MD5 HASH Encoding Problem

  • Thread starter Thread starter Shaun Merrill
  • Start date Start date
S

Shaun Merrill

This function doesn't seem to be giving me the appearance I expect. This
should appear more like
"1ba442ab45c8002a86d068d1c1748e44" but it looks really cryptic and screwy,
like "­óìØLÜzrVÊ%' \Y7".

Here is my code segment written in VB.NET Enterprise Architect:
--------
Public Function MD5File(ByVal Filename As String) As String
'
' Read a file, produce an MD5 hashed key value in a String.
'
With New Security.Cryptography.MD5CryptoServiceProvider
Dim result() As Byte = .ComputeHash( New
IO.StreamReader(Filename).BaseStream )
Dim Encoding As Text.Encoding = System.Text.Encoding.Default
Return Encoding.GetString(result)
Encoding = Nothing
.Clear()
End With
End Function
---------
Perhaps you can suggest a modification to my code which yields a more
hex-like string. I'm new to VB.NET, but I love it so far.
Thanks,
~ Shaun
near Seattle, WA
 
Hi there,

This is much easier done by loading the file into a byte array first,

Imports System.Security.Cryptography

Public Function createHash(ByVal iByteArray() As Byte) As String
Dim pBytHash() As Byte
pBytHash = New MD5CryptoServiceProvider().ComputeHash(iByteArray)
Return (BitConverter.ToString(pBytHash, 0, pBytHash.GetUpperBound(0)))
End Function

You can then use the above function to get an MD5 Hash of the data.

Nick.
 
Shaun,

The result you are getting is actually correct... it's just not formatted in
"nice-hex-format", you still have it as raw data.

Here's a quick code snippet that will take your raw data, and display it how
you want...

///
Dim strMD5 As String
For Each bytByte As Byte In result
strMD5 &= bytByte.ToString("x2")
Next
///

Now, strMD5 contains the nicely formatted MD5 hash. (Assuming 'result' is
your byte array).

Also, you have an unreachable code segment in your code:
Encoding = Nothing
.Clear()

These two lines will *never* be called, because they are preceeded with a
'Return' statement, which exits the method.

Hope this helps!

-- Tom Spink
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top