Use C # To implement MD5 and sha1 hash algorithms

Source: Internet
Author: User
Tags md5 hash sha1 hash

// Write to yourself or friends who have the same needs

/*
* Hash functions:
* The hash function maps a binary string of any length to a small binary string of a fixed length.
* The encryption hash function has the following attribute: it is unlikely that two hash columns with the same value are found in calculation.
* Different inputs. That is, the hash values of the two groups of data match only when the corresponding data matches.
* A small amount of data changes will generate unpredictable and massive changes in the hash value.
*
* The Hash Value of the MD5 algorithm is 128 bits.
* The sha1 algorithm's hash value is 160 bits.
*/

Using system;
Using system. Collections. Generic;
Using system. text;
Using system. Security. cryptography;

Namespace md5_app
{
Class Program
{
Static void main (string [] ARGs)
{
String strsrc = "how are you? ";
Console. writeline ("Original:" + strsrc );
Console. writeline ();

Console. writeline ("MD5 Hash Value:" + md5_hash (strsrc ));
Console. writeline ();

Console. writeline ("sha1 hash value:" + sha1_hash (strsrc ));
Console. writeline ();
}

// MD5
Static Public String md5_hash (string str_md5_in)
{
MD5 MD5 = new md5cryptoserviceprovider ();
Byte [] bytes_md5_in = utf8encoding. Default. getbytes (str_md5_in );
Byte [] bytes_md5_out = md5.computehash (bytes_md5_in );
String str_md5_out = bitconverter. tostring (bytes_md5_out );
Return str_md5_out;
}

// Sha1
Static Public String sha1_hash (string str_sha1_in)
{
Sha1 sha1 = new sha1cryptoserviceprovider ();
Byte [] bytes_sha1_in = utf8encoding. Default. getbytes (str_sha1_in );
Byte [] bytes_sha1_out = sha1.computehash (bytes_sha1_in );
String str_sha1_out = bitconverter. tostring (bytes_sha1_out );
Return str_sha1_out;
}
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.