Página 1 de 1

Dll: HashAlgorithm (Basada en HashMD5)

Publicado: 18 May 2011 13:23
por Ceone
Buenas amigos de AMSSpecialist.info, como algunos ya sabreis hace no mucho saque una dll para saber el MD5 de un archivo o string, ahora estoy liado ampliando esta DLL, para que también consiga y compare hash de CRC32, y lo mas seguro que le agregue algún otro algoritmo pero bueno por ahora esto es lo que tengo, me he basado en varios ejemplos que vi por la red, espero que os guste. Un saludo.

Antigua DLL : Dll: HashMD5

Codigo Actual:

UnmanagedExports.cs
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Security.Cryptography;
using RGiesecke.DllExport;
using CRC32CS;

namespace CeoneHashAlgorithm
{
internal static class UnmanagedExports
{
// Function to get MD5Hash from string
[DllExport("GetMD5HashfromString", CallingConvention = System.Runtime.InteropServices.CallingConvention.StdCall)]
static string GetMD5HashfromString(string input)
{
// Create a new instance of the MD5CryptoServiceProvider object.
MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();

// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));

// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();

// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data.ToString("x2"));
}

// Return the hexadecimal string.
return sBuilder.ToString();
}

// Function verify MD5Hash from string
[DllExport("VerifyMD5HashfromString", CallingConvention = System.Runtime.InteropServices.CallingConvention.StdCall)]
static int VerifyMD5HashfromString(string input, string hash)
{
// Create a new instance of the MD5CryptoServiceProvider object.
MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();

// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));

// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();

// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data.ToString("x2"));
}

// Return the hexadecimal string.
string hashOfInput = sBuilder.ToString();

// Create a StringComparer an comare the hashes.
StringComparer comparer = StringComparer.OrdinalIgnoreCase;

if (0 == comparer.Compare(hashOfInput, hash))
{
return 1;
}
else
{
return 0;
}
}

// Function to get MD5Hash from FilePath
[DllExport("GetMD5HashfromFile", CallingConvention = System.Runtime.InteropServices.CallingConvention.StdCall)]
static string GetMD5HashfromFile(string filepath)
{
using (StreamReader sr = new StreamReader(filepath))
{
// Create a new instance of the MD5CryptoServiceProvider object.
MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();

// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(sr.ReadToEnd()));

// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();

// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data.ToString("x2"));
}

// Return the hexadecimal string.
return sBuilder.ToString();
}
}

// Function to get CRC32hash from FilePath
[DllExport("GetCRC32fromFile", CallingConvention = System.Runtime.InteropServices.CallingConvention.StdCall)]
static string GetCRC32fromFile(string stringValue, int format)
{
Crc32 crc32 = new Crc32();
String hash = String.Empty;

if (format == 1)
{
using (FileStream fs = File.Open(stringValue, FileMode.Open))
foreach (byte b in crc32.ComputeHash(fs)) hash += b.ToString("x2").ToLower();
}
else if (format == 2)
{
using (FileStream fs = File.Open(stringValue, FileMode.Open))
foreach (byte b in crc32.ComputeHash(fs)) hash += b.ToString("x2").ToUpper();
}
return hash;
}

// Function to verify CRC32hash from string
[DllExport("VerifyCRC32fromString", CallingConvention = System.Runtime.InteropServices.CallingConvention.StdCall)]
static bool VerifyCRC32fromString(string stringValue, int format, string vhash)
{
Crc32 crc32 = new Crc32();
String hash = String.Empty;

if (format == 1)
{
using (FileStream fs = File.Open(stringValue, FileMode.Open))
foreach (byte b in crc32.ComputeHash(fs)) hash += b.ToString("x2").ToLower();
}
else if (format == 2)
{
using (FileStream fs = File.Open(stringValue, FileMode.Open))
foreach (byte b in crc32.ComputeHash(fs)) hash += b.ToString("x2").ToUpper();
}
if (hash == vhash)
{
return true;
}
else
{
return false;
}
}

// Function to verify CRC32hash from FilePath
[DllExport("VerifyCRC32fromFile", CallingConvention = System.Runtime.InteropServices.CallingConvention.StdCall)]
static bool VerifyCRC32fromFile(string stringValueA, string stringValueB, int format)
{
Crc32 crc32 = new Crc32();
String hash = String.Empty;
String vhash = String.Empty;

if (format == 1)
{
using (FileStream fs = File.Open(stringValueA, FileMode.Open))
foreach (byte b in crc32.ComputeHash(fs)) hash += b.ToString("x2").ToLower();
using (FileStream fs = File.Open(stringValueB, FileMode.Open))
foreach (byte b in crc32.ComputeHash(fs)) vhash += b.ToString("x2").ToLower();
}
else if (format == 2)
{
using (FileStream fs = File.Open(stringValueA, FileMode.Open))
foreach (byte b in crc32.ComputeHash(fs)) hash += b.ToString("x2").ToUpper();
using (FileStream fs = File.Open(stringValueB, FileMode.Open))
foreach (byte b in crc32.ComputeHash(fs)) vhash += b.ToString("x2").ToLower();
}
if (hash == vhash)
{
return true;
}
else
{
return false;
}
}
}
}


Crc32.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;

namespace CRC32CS
{
public class Crc32 : HashAlgorithm
{
public const UInt32 DefaultPolynomial = 0xedb88320;
public const UInt32 DefaultSeed = 0xffffffff;

private UInt32 hash;
private UInt32 seed;
private UInt32[] table;
private static UInt32[] defaultTable;

public Crc32()
{
table = InitializeTable(DefaultPolynomial);
seed = DefaultSeed;
Initialize();
}

public Crc32(UInt32 polynomial, UInt32 seed)
{
table = InitializeTable(polynomial);
this.seed = seed;
Initialize();
}

public override void Initialize()
{
hash = seed;
}

protected override void HashCore(byte[] buffer, int start, int length)
{
hash = CalculateHash(table, hash, buffer, start, length);
}

protected override byte[] HashFinal()
{
byte[] hashBuffer = UInt32ToBigEndianBytes(~hash);
this.HashValue = hashBuffer;
return hashBuffer;
}

public override int HashSize
{
get { return 32; }
}

public static UInt32 Compute(byte[] buffer)
{
return ~CalculateHash(InitializeTable(DefaultPolynomial), DefaultSeed, buffer, 0, buffer.Length);
}

public static UInt32 Compute(UInt32 seed, byte[] buffer)
{
return ~CalculateHash(InitializeTable(DefaultPolynomial), seed, buffer, 0, buffer.Length);
}

public static UInt32 Compute(UInt32 polynomial, UInt32 seed, byte[] buffer)
{
return ~CalculateHash(InitializeTable(polynomial), seed, buffer, 0, buffer.Length);
}

private static UInt32[] InitializeTable(UInt32 polynomial)
{
if (polynomial == DefaultPolynomial && defaultTable != null)
return defaultTable;

UInt32[] createTable = new UInt32[256];
for (int i = 0; i < 256; i++)
{
UInt32 entry = (UInt32)i;
for (int j = 0; j < 8; j++)
if ((entry & 1) == 1)
entry = (entry >> 1) ^ polynomial;
else
entry = entry >> 1;
createTable = entry;
}

if (polynomial == DefaultPolynomial)
defaultTable = createTable;

return createTable;
}

private static UInt32 CalculateHash(UInt32[] table, UInt32 seed, byte[] buffer, int start, int size)
{
UInt32 crc = seed;
for (int i = start; i < size; i++)
unchecked
{
crc = (crc >> 8) ^ table[buffer ^ crc & 0xff];
}
return crc;
}

private byte[] UInt32ToBigEndianBytes(UInt32 x)
{
return new byte[] {
(byte)((x >> 24) & 0xff),
(byte)((x >> 16) & 0xff),
(byte)((x >> 8) & 0xff),
(byte)(x & 0xff)};
}
}
}


Si teneis alguna duda sugerencia o simplemente quereis dar por culo un rato este es vuestro post!!!

:ohyeah: :hypno:

Re: Dll: HashAlgorithm (Basada en HashMD5)

Publicado: 18 May 2011 15:34
por Ceone
he estado liado un rato y he sacado esto:

Imagen

Lógicamente no esta aun acabada por que no he echo las pruebas de todas las funciones seguro que mas de una estará mal jajajaja...

Re: Dll: HashAlgorithm (Basada en HashMD5)

Publicado: 18 May 2011 17:54
por Ceone
he cambiando mucho del contenido de esta dll pero me esta dando unos problemas increibles, asi que no se cuando la tendre lista al meterle muchos mas codigos algunas cosas no funcionan del todo bien tendre que mirarmelo con mucha calma por que falla mas que va... :(

Re: Dll: HashAlgorithm (Basada en HashMD5)

Publicado: 18 May 2011 21:16
por Ceone
sigo teniendo problemas... acabo de llegar hace un rato he probado un par de cosas pero no ay manera.

he cambiado las funciones de nombre, y he agregado una función mas... pero estoy empezando el test y "GetCRC32File" me esta dando un por culo... pero bueno espero encontrar el error.

Imagen

Re: Dll: HashAlgorithm (Basada en HashMD5)

Publicado: 19 May 2011 12:57
por Pabloko
cryptografy rulez el fin de semana te doy una mano con los sietemas asincronos

puta madre!!!

Re: Dll: HashAlgorithm (Basada en HashMD5)

Publicado: 19 May 2011 14:02
por Ceone
MD5 y CRC32 los tengo 100% listo y funkan de guais... pero SHA's me estan dando super por el culo, siempre me lanza un hash diferente parece que me vea cara de tonto. :focus:

Re: Dll: HashAlgorithm (Basada en HashMD5)

Publicado: 22 Mar 2013 16:16
por tam
thanks

Re: Dll: HashAlgorithm (Basada en HashMD5)

Publicado: 24 Oct 2017 11:49
por zinou21
merciiiiiiii