using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Md5_Calculator
{
class Md5StringDigest
{
private Md5Base md5;
private byte[] Message;
public const int ENCODING_VALUE_UNICODE = 0;
public const int ENCODING_VALUE_ASCII = 1;
public const int ENCODING_VALUE_UTF7 = 2;
public const int ENCODING_VALUE_UTF8 = 3;
public const int ENCODING_VALUE_UTF32 = 4;
public Md5StringDigest(String message):this(message, 0)
{
}
/// <summary>
/// Initialiser of the class Md5StringDigest
/// </summary>
/// <param name="message">The message to get the digest from</param>
/// <param name="EncodingValue">An int value representing a specific encoder for the message</param>
public Md5StringDigest(String message, int EncodingValue)
{
switch (EncodingValue)
{
case ENCODING_VALUE_UNICODE:
Message = Encoding.Unicode.GetBytes(message);
break;
case ENCODING_VALUE_ASCII:
Message = Encoding.ASCII.GetBytes(message);
break;
case ENCODING_VALUE_UTF7:
Message = Encoding.UTF7.GetBytes(message);
break;
case ENCODING_VALUE_UTF8:
Message = Encoding.UTF8.GetBytes(message);
break;
case ENCODING_VALUE_UTF32:
Message = Encoding.UTF32.GetBytes(message);
break;
default:
Message = Encoding.Default.GetBytes(message);
break;
}
padding();
ProcessMessage();
}
private void padding()
{
// Dato LONG della lunghezza del messaggio originale in bits.
ulong MessageLength = (ulong) Message.Length * 8;
// Divido il dato LONG della lunghezza dell'array in array di byte.
byte[] MessageLengthArray
= new byte[8
];
for (int i = 0, k = 0; i < 64; i += 8, k++)
MessageLengthArray[k] = (byte)(MessageLength >> i);
// Lunghezza messaggio in bytes
MessageLength = (ulong)Message.Length;
// Aggiungo il primo byte (0x80)
Array.Resize(ref Message, Message.Length + 1);
Message[Message.Length - 1] = 0x80;
MessageLength++;
//Padding congruent 54 mod 64
while (Math.Abs((uint) MessageLength - 56) % 64 != 0)
MessageLength++;
Array.Resize(ref Message, (int) MessageLength + 8);
// Aggiungo la lunghezza del messaggio (dato LONG) al messaggio.
long h = (Message.Length - 8);
foreach (int value in MessageLengthArray)
{
Message[h] = (byte) value;
h++;
}
}
private void ProcessMessage()
{
// Divido il messagio in WORD
uint[] Mword
= new uint[Message.
Length / 4
];
for (int i = 0, k = 0; i < Mword.Length; i++, k += 4)
{
uint word = (uint)Message[k + 3] << 24 | (uint)Message[k + 2] << 16 | (uint)Message[k + 1] << 8 | (uint)Message[k];
Mword[i] = word;
}
// Spezzo in blocchi e lavoro su ogni blocco
long N = Message.Length / 4;
for (int i = 0; i <= N / 16 - 1; i++)
{
// Creo il blocco
uint[] block
= new uint[16
];
for (int k = 0; k < 16; k++)
block[k] = Mword[i * 16 + k];
md5.ProcessBlock(block);
}
}
public String getDigest()
{
return md5.returnDigest();
}
}
}