1. The MD5 algorithm is a hash (hash) algorithm (digest algorithm, fingerprint algorithm), not a cryptographic algorithm (error-prone). Any content of any length can be computed with MD5 hash value. MD5 's predecessor: MD2, MD3, MD4. Introduction Tool: Calcmd5.zip. The main function is to "verify" the "", the string file can be (ensure the integrity of the information transmission process, consistency).
2. Features of the MD5 algorithm:
???? 1. Fixed length
???? 2. Unidirectional----can calculate the MD5 value of a file or string by MD5 calculator, but it is not possible to derive the file or string by the MD5 value given.
???? 3. Conflict-resistant (non-repetitive)
???? 4. "Avalanche effect", as long as the source of a little change, will cause large changes
???? 5. Different "source", the generated MD5 value is always not the same, the same "source", produces always the same MD5 value.
???? 6. The same content, each generated MD5 value is the same.
3. Code implementation "compute MD5 values for files and strings"
????· Computes the MD5 value of a string:
???? // <summary>
/// of the computed string. MD5 value
</summary>
<param name= "msg" ></param>
<returns></returns>
Privatestaticstringgetmd5fromstring(string msg )
{
//1. Create a method to calculate MD5 value of the class object
?
Using (MD5md5=MD5. Create())
{
// Convert the string to byte[] array
//Note: If the string contains Chinese characters, it will be used utf-8 encoding converted to byte[], when the MD5 value is calculated elsewhere, if a different encoding is used for the Chinese characters, the same Chinese characters are generated byte[] is not the same, so the calculated MD5 value is not the same.
?
//byte[] Msgbuffer = Encoding.Default.GetBytes (msg); using the system default encoding
BYTE[] msgbuffer=Encoding. UTF8. GetBytes(msg);
//2. that calculates the given string. MD5 value
//The return value is the computedMD5value, how to put a length of -of thebyte[]the array is converted to a length of +The string: is to put abyteturn into -binary while retaining2bit.
BYTE[] md5buffer=md5.computehash(msgbuffer);
MD5. Clear(); // Freeing Resources
StringBuildersbmd5=newStringBuilder();
For (inti=0; I<md5buffer.length; i++)
{
// in Input output, and 2 -bit retention
Sbmd5.append(md5buffer[i]. ToString("X2"));
}
returnsbmd5.tostring();
}
}
<summary>
/// of the calculation file MD5 value
</summary>
<param name= "path" ></param>
<returns></returns>
Privatestaticstringgetmd5fromfile(string Path )
{
Using (MD5md5=MD5. Create())
{
Using (FileStreamfsread=File. OpenRead(path))
{
BYTE[] bytes=md5.computehash(fsread);
MD5. Clear();
StringBuildersbmd5=newStringBuilder();
For (inti=0; I<bytes. Length; i++)
{
Sbmd5.append(bytes[i]. ToString("X2"));
}
returnsbmd5.tostring();
}
}
}
MD5 algorithm "computes the MD5 value of files and strings"