PDA

View Full Version : [VB.Net] Calcolo MD5 di una stringa Esadecimale


Mendocino89
06-05-2010, 22:30
Salve a tutti !

Sto cercando di creare una semplice funzione che mi permetta di calcolare l'MD5 di una stringa esadecimale...
E sono arrivato a questo punto:


Const Str As String = "BA2CE82233122114113001112010C27142106A240281FA681526"

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim MD5_Processor As New System.Security.Cryptography.MD5Cng
Dim Retrn() As Byte
Dim rtn_u() As Byte
Retrn = Encoding.UTF8.GetBytes(Hex_TA(Str))
MD5_Processor.Initialize()
MD5_Processor.ComputeHash(Retrn)
rtn_u = MD5_Processor.Hash
Dim Out_MD5_Str As String
For j As Byte = 0 To rtn_u.GetUpperBound(0)
Out_MD5_Str = Out_MD5_Str & Hex(rtn_u(j).ToString)
Next
MsgBox(Out_MD5_Str)
End Sub

Public Function Hex_TA(ByVal In_HEX_Str As String) As Char()
Dim Lght As Byte
Dim Chr_Res() As Char
Lght = In_HEX_Str.Length / 2
ReDim Chr_Res(Lght - 1)
For pl As Byte = 0 To Lght - 1
Chr_Res(pl) = Chr(CInt("&h" & Mid(In_HEX_Str, (pl * 2) + 1, 2)))
Next
Hex_TA = Chr_Res
End Function


Ora il problema č che per stringhe del genere "5758" l'algoritmo funziona alla perferzione.

Appena gli do in pasto qualcosa di sostanzioso, niente, incomincia a sparare digest assurdi !

Ora secondo me il problema sta nella conversione delle coppie esadecimali a caratteri, che sono in formato ASCII.
Non vorrei che qualche coppia desse in uscita un carattere incomprensibile al formato UTF8.

P.S. A conferma di cio che si faccio fare il digest di una stringa di testo normale, questo funziona alla grande.
Il problema si presenta solo con ste dannate stringhe esadecimali.

AIUTO !:D

Mendocino89
07-05-2010, 10:48
Risolto !!:D

Const Str As String = "BA2CE82233122114113001112010C27142106A240281FA681526"

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim MD5_Processor As New System.Security.Cryptography.MD5CryptoServiceProvider
Dim Retrn() As Byte
Dim rtn_u() As Byte
MD5_Processor.Initialize()
MD5_Processor.ComputeHash(Hex_TA(Str))
rtn_u = MD5_Processor.Hash
Dim Out_MD5_Str As String
For j As Byte = 0 To rtn_u.GetUpperBound(0)
Out_MD5_Str = Out_MD5_Str & Hex(rtn_u(j).ToString)
Next
MsgBox(Out_MD5_Str)
End Sub

Public Function Hex_TA(ByVal In_HEX_Str As String) As Byte()
Dim Lght As Byte
Dim Chr_Res() As Byte
Lght = In_HEX_Str.Length / 2
ReDim Chr_Res(Lght - 1)
For pl As Byte = 0 To Lght - 1
Chr_Res(pl) = CInt("&h" & Mid(In_HEX_Str, (pl * 2) + 1, 2))
Next
Return Chr_Res
End Function

La soluzione era molto piu semplice di quanto potessi immaginare.
Molto semplicemente a MD5_Processor.ComputeHash posso passare l'array di byte Chr_Res, senza fare inutili conversioni fra UTF8 e ASCII.
Ciņ si rende necessario solo calcolando l'MD5 di stringhe testuali.
:p