Foro de elhacker.net

Programación => .NET (C#, VB.NET, ASP) => Mensaje iniciado por: **Aincrad** en 13 Octubre 2018, 19:57 pm



Título: Convertir Cadena Hex a Bytes y compararlos Con Bytes de un archivo
Publicado por: **Aincrad** en 13 Octubre 2018, 19:57 pm
Bueno hola foro, Como dice el titulo, tengo un Escanear Hexadecimal para identificar archivos, Pero es lento y segun me he documentado se puede mejorar si :

1) Convierto la cadena Hex a Bytes.

2) Obtengo los Bytes del archivo .

4) Comparo la Cadena Hex convertida a Bytes con los Bytes del archivo.




Bueno ahora lo que tengo hecho hasta ahora :


Cadena Hex Almacenada en una variable XML:

Código
  1. Dim xml = <?xml version="1.0"?>
  2.              <signatures>
  3.                  <signature>
  4.                      <name>Archivo1</name>
  5.                      <hex>58354f2150254041505b345c505a58353428505e2937434329377d2445494341522d5354414e4441</hex>
  6.                  </signature>
  7.                  <signature>
  8.                      <name>Archivo2</name>
  9.                      <hex>f649e7cc1e00d37e7f3bc85fff3486ac6de91433aa3a39ef1b114d37b534b8323f6ff67132638a3fe2f2afb4aaf9b7e3b4669bb3cab028298aab533c5d73546cdd396fd58c2c7734c50bca68eb709b889a086fb3db5f8ae533a4d5816e8c5f560983695efa14e291c204b1316e657773</hex>
  10.                  </signature>
  11.              </signatures>

Aquí el código para leer el XML y Convertirlo a Bytes:

Código
  1. Private Sub hexttoBytes()
  2.        Dim Str As New StringBuilder
  3.        For Each signature As XElement In xml.Root.Elements
  4.  
  5.            stringToByteArray(signature.<hex>.Value)
  6.  
  7.        Next
  8.  
  9.    End Sub
  10.  
  11.    Public Shared Function stringToByteArray(text As String) As Byte()
  12.        Dim bytes As Byte() = New Byte(text.Length \ 2 - 1) {}
  13.  
  14.        For i As Integer = 0 To text.Length - 1 Step 2
  15.            bytes(i \ 2) = Byte.Parse(text(i).ToString() & text(i + 1).ToString(), System.Globalization.NumberStyles.HexNumber)
  16.        Next
  17.  
  18.        Return bytes
  19.    End Function


Aquí el código para Obtener los Bytes del archivo a comparar

Código
  1.  ' Opendia IS OPENFILEDIALOG
  2.        Dim result As DialogResult = OpenDia.ShowDialog()
  3.  
  4.  
  5.        If result = Windows.Forms.DialogResult.OK Then
  6.  
  7.  
  8.            Dim path As String = OpenDia.FileName
  9.            Try
  10.  
  11.                Dim bytesFile As Byte() = File.ReadAllBytes(path)
  12.  
  13.                ' BytesFile es donde se almacenan Los Bytes del archivo a comparar
  14.                ' Necesito saber Como los Comparo con los Otros Bytes que antes eran HEX
  15.  
  16.            Catch ex As Exception
  17.  
  18.                MsgBox(ex.Message)
  19.  
  20.            End Try
  21.        End If
  22.  




AHORA LAS DUDAS, SEGÚN LO QUE TENGO ECHO ,  No logro Como hacer Para Comparar los Bytes que antes eran HEX con los Bytes del archivo. Lo que quiero lograr seria algo como esto :

Código
  1. 'Donde BytesFiles es el Archivo y BytesHex eran la Cadena Hex que ahora son Bytes
  2. ' En caso de que los Bytes sean Iguales. lanza el mensaje de que encontró el archivo o no.
  3. If bytesFile = BytesHex then
  4. Msgbox("Archivo Coincide")
  5. else
  6. Msgbox("Archivo No Coincide")
  7. end if

Gracias De Antemano



Título: Re: Convertir Cadena Hex a Bytes y compararlos Con Bytes de un archivo
Publicado por: Eleкtro en 13 Octubre 2018, 22:57 pm
No logro Como hacer Para Comparar los Bytes que antes eran HEX con los Bytes del archivo.

Te escribo un ejemplo...

Código
  1. Dim signature As Byte?() = {&HFF, &HD8, &HFF} ' JPEG magic number.
  2. Dim fi As New FileInfo("C:\Image.jpg") ' JPEG image.
  3. Dim chunk As Byte() = GetFileChunk(fi, 0, signature.Length) ' First three bytes (signature length) of the JPEG image.
  4. Dim result As Boolean = IsMatchSignature(chunk, signature, offset:=0)
  5.  
  6. Console.WriteLine("Signature Match?: {0}", result)

Código
  1. Public Shared Function GetFileChunk(file As FileInfo, offset As Integer, length As Integer) As Byte()
  2.    Dim fileLen As Long = file.Length
  3.    If (fileLen < length) Then
  4.        length = CInt(fileLen)
  5.    End If
  6.  
  7.    Dim chunk As Byte() = New Byte(length - 1) {}
  8.    Using fs As New FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.Read)
  9.        fs.Read(chunk, offset, length)
  10.    End Using
  11.    Return chunk
  12. End Function

Código
  1. Public Shared Function IsMatchSignature(bytes As Byte(), signature As Byte?(), offset As Integer) As Boolean
  2.    For i As Integer = 0 To (signature.Length - 1)
  3.        ' If byte value in file signature is null, the value is variable, so we ignore it.
  4.        If (signature(i) Is Nothing) Then
  5.            Continue For
  6.        End If
  7.  
  8.        If (signature(i) <> bytes(i + offset)) Then
  9.            Return False
  10.        End If
  11.    Next i
  12.    Return True
  13. End Function

Saludos.


Título: Re: Convertir Cadena Hex a Bytes y compararlos Con Bytes de un archivo
Publicado por: **Aincrad** en 13 Octubre 2018, 23:09 pm
Y como aplico ese ejemplo al mio? es que tengo una base de datos XML grande.

Código
  1. Dim xml = <?xml version="1.0"?>
  2.              <signatures>
  3.                  <signature>
  4.                      <name>Archivo1</name>
  5.                      <hex>58354f2150254041505b345c505a58353428505e2937434329377d2445494341522d5354414e4441</hex>
  6.                  </signature>
  7.                  <signature>
  8.                      <name>Archivo2</name>
  9.                      <hex>f649e7cc1e00d37e7f3bc85fff3486ac6de91433aa3a39ef1b114d37b534b8323f6ff67132638a3fe2f2afb4aaf9b7e3b4669bb3cab028298aab533c5d73546cdd396fd58c2c7734c50bca68eb709b889a086fb3db5f8ae533a4d5816e8c5f560983695efa14e291c204b1316e657773</hex>
  10.                  </signature>
  11.              </signatures>



Título: Re: Convertir Cadena Hex a Bytes y compararlos Con Bytes de un archivo
Publicado por: Eleкtro en 14 Octubre 2018, 00:52 am
¿Cómo que cómo lo aplicas?, exactamente del mismo modo en el que te acabo de mostrar... pero usando tus secuencias (firmas) DEC que conviertes desde cadenas de texto HEX. Las funciones que he compartido son reutilizables, de uso genérico, copiar y listo.