C#_ Encryption and decryption

Source: Internet
Author: User
Tags md5 encryption sha1 sha1 encryption

First, MD5 encryption and decryption

1. Encryption

public static string ToMd5 (String clearstring)
{            byte[] clearbytes = System.Text.Encoding.Unicode.GetBytes (clearstring);            String hashedpwd = Bitconverter.tostring (((HashAlgorithm) cryptoconfig.createfromname ("MD5"). ComputeHash (clearbytes));            return hashedpwd;        }

2, 32-bit MD5 encryption

        public static string Getmd5base32 (String sInput)
        {            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding ();            System.Security.Cryptography.MD5 MD5;            Byte[] BYTESSRC;            Byte[] result;            StringBuilder sb = new StringBuilder ();            BYTESSRC = Encoding. GetBytes (sInput);            MD5 = new System.Security.Cryptography.MD5CryptoServiceProvider ();            result = Md5.computehash (BYTESSRC);            for (int i = 0; I < result. Length; i++)            {                sb. AppendFormat ("{0:x2}", Result[i]);            }            Return SB. ToString ();        }

Second, base64 algorithm encryption and decryption

    <summary>////    for Base64 coding algorithms///    </summary> public    class Base64    {        public Base64 ()        {        }//         <summary>        encrypt string using base64 algorithm        ///</summary> <param name= "sourcestring" > Strings to be encrypted </param>//        <param name= "Ens" >system.text.encoding objects , such as creating a Chinese encoding Set object: System.Text.Encoding.GetEncoding (54936) </param>///        <returns> Overweight text string </returns > Public        static string encodingforstring (String sourcestring, System.Text.Encoding ens)        {            Return convert.tobase64string (Ens. GetBytes (sourcestring));        }
<summary>////Use the Base64 algorithm to encrypt the string///</summary>//<param name= "sourcestring" > string to be encrypted </param >///<returns> Overweight text string </returns> public static string encodingforstring (String sourcestring){return encodingforstring (sourcestring, System.Text.Encoding.GetEncoding (54936));}<summary>////restore string from Base64 encoded string, support Chinese//</summary>//<param name= "base64string" > Base64 encrypted string </param>//<param name= "Ens" >system.text.encoding object, such as creating a Chinese encoding Set object: System.Text.Encoding.GetEncoding (54936) </param>///<returns> restored text string </returns> public static string Decodingforstring (String base64string, System.Text.Encoding ens){/** * *********************************************************** * * * The In-machine code (ANSI character encoding) of the character in bytes obtained from Base64string * General, Conversion of the in-machine code to Chinese characters is the formula: * (char) (first byte binary value *256+ second byte value) * While char or string in C # is Unicode-encoded, it is not possible to calculate the * ANSI Byte-and Unicode-encoded incompatible with the above formula * Therefore, using the encoding classes provided by the. NET class library to implement conversions from ANSI encoding to Unicode code * The GetEncoding method relies on the underlying platform to support most code pages. However, system support is provided for the following scenarios: The default encoding, which is the encoding specified in the locale of the computer on which the method is executed; Little-endian Unicode (utf-16le); Big-endian Unicode (UTF-16BE); Windows Operating system (windows-1252); Utf-7;utf-8;ascii and GB18030 (Simplified Chinese). * * Specify one of the names listed in the following table to obtain the system-supported encoding with the corresponding code page. * * code page name * "Utf-16le", "utf-16", "ucs-2", "Unicode" or "iso-10646-ucs-2" * 1201 "utf-16be" or "Unicodefffe" * 1252 "windows- 1252 "* 65000" utf-7 "," Csunicode11utf7 "," unicode-1-1-utf-7 "," unicode-2-0-utf-7 "," x-unicode-1-1-utf-7 "or" X-unicode-2-0-utf-7 "* 65001" Utf-8 "," Unicode-1-1-utf-8 "," Unicode-2-0-utf-8 "," X-unicode-1-1-utf-8 "or" X-unicode-2-0-utf-8 "* 20127" Us-ascii "," Us "," ASCII "," ansi_x3.4-1968 "," ansi_x3.4-1986 "," cp367 "," Csascii "," IBM367 " , "Iso-ir-6", "iso646-us" or "iso_646.irv:1991" *54936 "GB18030" * * Some platforms may not support specific code pages. For example, the U.S. version of Windows 98 may not support the Japanese Shift-jis code page (code page 932). In this case, the GetEncoding method will raise NotSupportedException when executing the following C # code: * * Encoding enc = encoding.getencoding ("Shift-jis"); ///Get the original character return ens from Base64string. GetString (convert.frombase64string (base64string)); }<summary>////restore string from Base64 encoded string, support Chinese//</summary>//<param name= "base64string" > Base64 encrypted string </param>////<returns> restored text string </returns> public static string Decodingforstring ( String base64string){return decodingforstring (base64string, System.Text.Encoding.GetEncoding (54936));} //--------------------------------------------------------------------------------------<summary>///Base64 for any type of file///</summary>//<param name= "filename" > File path and filename </param >///<returns> base64 encoded string </returns> public static string Encodingforfile (String fileName){System.IO.FileStream fs = System.IO.File.OpenRead (FileName); System.IO.BinaryReader br = new System.IO.BinaryReader (FS);/*system.byte[] B=new System.byte[fs. Length]; Fs. Read (B,0,convert.toint32 (fs. LENGTH); */String base64string = Convert.tobase64string (Br. Readbytes ((int) fs. Length)); Br. Close (); Fs. Close (); return base64string; }<summary>////Save the Base64 encoded string as a file///</summary>//<param name= "base64string" > the string after base64 </param>//<param name= "filename" > Save file path and file name </param>//<returns> Save file successfully </returns > public static bool Savedecodingtofile (string base64string, String fileName){System.IO.FileStream fs = new System.IO.FileStream (FileName, System.IO.FileMode.Create); System.IO.BinaryWriter bw = new System.IO.BinaryWriter (FS); Bw. Write (convert.frombase64string (base64string)); Bw. Close (); Fs. Close (); return true; } //-------------------------------------------------------------------------------///<summary>///From the network address one and convert it to Base64 code///</summary>// <param name= "url" > URL address of the file, an absolute URL address </param>//<param name= "Objwebclient" > System.Net.WebClient objects </param>///<returns></returns> public static string Encodingfilefromurl ( String URL, System.Net.WebClient objwebclient) {return Convert.tobase64string (objwebclient.downloaddata (URL)); } ///<summary>///From the network address one and convert it to Base64 code///</summary>// <param name= "url" > URL address of the file, an absolute URL address </param>//<returns> Convert the file after the Base64 string </returns> public static string Encodingfilefromurl (string url) {// System.Net.WebClient mywebclient = new System.Net.WebClient (); Return Encodingfilefromurl (URL, new System.Net.WebClient ()); } }

Third, SHA1 encryption

{     {      return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile (Code, " SHA1 "). ToLower ();   }   else    {      return string. Empty;   }   } 

Iv. AES Encryption and decryption

<summary>//AES Encryption decryption///</summary> public class AES{<summary>///Get key///</summary> private static string key{Get{return @ ")        O[nb]6,yf}+efcaj{+oesb9d8>z ' e9m ';} }<summary>///Get vector//</summary> private static string IV{Get{return @ "L+/~f4,ir) B$=PKF"; } }<summary>//AES encryption///</summary>/<param name= "Plainstr" > Clear text string </param>//<returns& gt; ciphertext </returns> public static string Aesencrypt (String plainstr){byte[] bkey = Encoding.UTF8.GetBytes (Key); byte[] BIV = Encoding.UTF8.GetBytes (IV); byte[] ByteArray = Encoding.UTF8.Get Bytes (PLAINSTR); string encrypt = null; Rijndael AES = Rijndael.create (); Try{using (MemoryStream mstream = new MemoryStream ()){using (CryptoStream cstream = new CryptoStream (Mstream, AES. CreateEncryptor (Bkey, BIV), CryptoStreamMode.Write)){cstream.write (byteArray, 0, bytearray.length); Cstream.flushfinalblock (); encrypt = Convert.tobase64string ( Mstream.toarray ()); }}} catch{} aes. Clear (); return encrypt; }<summary>//AES encryption///</summary>/<param name= "Plainstr" > Clear text string </param>//<param Nam E= "Returnnull" > whether to return Null,false when encryption fails to return string.empty</param>//<returns> redaction </returns> Public static string Aesencrypt (string plainstr, bool returnnull){String encrypt = Aesencrypt (PLAINSTR); return returnnull? Encrypt: (encrypt = = null?) String.Empty:encrypt); }<summary>//AES decryption///</summary>/<param name= "Encryptstr" > Ciphertext string </param>//< returns> plaintext </returns> public static string Aesdecrypt (String encryptstr){byte[] bkey = Encoding.UTF8.GetBytes (Key); byte[] BIV = Encoding.UTF8.GetBytes (IV); byte[] ByteArray = Convert.frombase6 4String (ENCRYPTSTR); string decrypt = null; Rijndael AES = Rijndael.create (); Try{using (MemoryStream mstream = new MemoryStream ()){using (CryptoStream cstream = new CryptoStream (Mstream, AES. CreateDecryptor (Bkey, BIV), cryptostreammode.write)) {cStream.Write ( ByteArray, 0, bytearray.length); Cstream.flushfinalblock (); Decrypt = Encoding.UTF8.GetString (Mstream.toarray ()); }}} catch {} AES. Clear (); return decrypt; } ///<summary>//AES decryption//</summary>//<param name= " Encryptstr "> Ciphertext string </param>//<param name=" Returnnull "> If decryption fails return null,false return String.empty</param >//<returns> Clear text </returns> public static string Aesdecrypt (string encryptstr, bool returnnull) {String decrypt = Aesdecrypt (ENCRYPTSTR); return returnnull? Decrypt: (Decrypt = = NULL ? String.Empty:decrypt); } }

C#_ Encryption and decryption

Related Article

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.