C # The most practical string encryption and decryption Methods

Source: Internet
Author: User
Using System; using System. data; using System. configuration; using System. web; using System. web. security; using System. web. UI; using System. web. UI. webControls; using System. web. UI. webControls. webParts; using System. web. UI. htmlControls; using System. IO; using System. security. cryptography; using System. text; namespace SQL _function {// <summary> // All encryption methods // define the string encryption interface [MD5 encryption, SHA1 encryption, string encryption] defined in the foreground as follows: /// SQL _fu Nction. interFaceStringEncryptionDecryption QueryStringEncodeCodeAndDncodeCode = new SQL _function.StringEncryptionDecryption (); // description: SQL _function represents the namespace name InterFaceStringEncryptionDecryption represents the interface name StringEncryptionDecryption represents the class name // </summary> publicinterfaceInterFaceStringEncryptionDecryption {# region (1) queryString encryption and decryption start /// <summary> // QueryString encryption /// </summary> /// <param name = "StringS QL "> </param> // <returns> </returns> stringQueryStringEncodeCode (stringStringSQL ); /// <summary> /// QueryString decryption /// </summary> /// <param name = "StringSQL"> </param> /// <returns> </returns> stringQueryStringDncodeCode (stringStringSQL ); # endregion # region (2) rijndael algorithm // <summary> // encryption method // </summary> /// <param name = "Source"> string to be encrypted </param>/ // <returns> encrypted string </returns> stringRijndaelEncrypt (StringSource ); /// <summary> /// Decryption Method /// </summary> /// <param name = "Source"> string to be decrypted </param> /// <returns> decrypted string </returns> stringRijndaelDecrypt (stringSource ); # endregion (2) Rijndael algorithm # region (3) mix Base64 and UTF8 /// <summary> // string encryption /// </summary> /// <param name = "bb"> </param> /// <returns> </returns> stringBUEncrypt (string bb ); /// <summary> /// string decryption /// </summary> /// <param name = "aa"> </para M> // <returns> </returns> stringBUDecrypt (string aa); # endregion # region (4) fixed key algorithm // <summary> // string encryption // </summary> /// <param name = "strText"> </param> // <returns> </returns> stringSKeyEncrypt (string strText ); /// <summary> /// string decryption /// </summary> /// <param name = "strText"> </param> /// <returns> </returns> stringSKeyDecrypt (string strText ); # endregion # region (5) DES algorithm // <summary> /// DES encryption // </summary> /// <param name = "strSource"> </param> /// <returns> </returns> stringDESEncrypt (string strSource ); /// <summary> // DES decryption // </summary> /// <param name = "strSource"> </param> /// <returns> </returns> stringDESDecrypt (string strSource ); # endregion # region (6) encrypted password MD5T and SHA1 /// <summary> // encrypted password MD5T and SHA1 /// </summary> /// <param name = "strSource"> string </ param> // <param name = "str Flag "> encryption type </param> /// <param name =" substringlen "> encryption length </param> /// <returns> </returns> string encrypting (string strSource, int strFlag, int substringlen); # endregion} // <summary> // defines the method of the Interface Class Encryption Class /// </summary> publicclassStringEncryptionDecryption: interFaceStringEncryptionDecryption {# region (1) queryString encryption and decryption start /// <summary> // QueryString encryption /// </summary> /// <param name = "code"> </param> /// <Returns> </returns> publicstringQueryStringEncodeCode (string code) {string result = ""; if (code = null | code = "") {result = "";} else {result = Convert. toBase64String (System. text. encoding. default. getBytes ("" + code + "")). replace ("+", "% 2B");} return result ;} /// <summary> /// QueryString decryption /// </summary> /// <param name = "code"> </param> /// <returns> </returns> publicstringQueryStringDncodeCo De (string code) {string result = ""; if (code = null | code = "") {result = "";} else {try {result = System. text. encoding. default. getString (Convert. fromBase64String (code. replace ("% 2B", "+");} catch (FormatException ex) /// throw an exception [error message "invalid Base-64 character array length"] {result = "0" ;}} return result ;}# endregion (1) queryString encryption and decryption end # region (2) Rijndael algorithm privatestatic1_ricalgorithm mobjCryptoService = NewRijndaelManaged (); privatestaticstringKey = "Guz (% & hj7x89H $ yuBI0456FtmaT5 & fvHUFCy76 * h % (HilJ $ lhj! Y6 & (* jkP87jH7 "; /// <summary> /// obtain the key // </summary> /// <returns> key </returns> privatebyte [] GetLegalKey () {string sTemp = Key; mobjCryptoService. generateKey (); byte [] bytTemp = mobjCryptoService. key; intKeyLength = bytTemp. length; if (sTemp. length> KeyLength) sTemp = sTemp. substring (0, KeyLength); elseif (sTemp. length <KeyLength) sTemp = sTemp. padRight (KeyLength, ''); returnASCIIEncoding. ASCII. getBytes (STemp );} /// <summary> /// obtain the initial vector IV /// </summary> /// <returns> initial test vector IV </returns> privatebyte [] GetLegalIV () {string sTemp = "E4ghj * Ghg7! RNIfb & 95GUY86GfghUb # er57HBh (u % g6HJ ($ jhWk7 &! Hg4ui % $ hjk "; mobjCryptoService. generateIV (); byte [] bytTemp = mobjCryptoService. IV; intIVLength = bytTemp. length; if (sTemp. length> IVLength) sTemp = sTemp. substring (0, IVLength); elseif (sTemp. length <IVLength) sTemp = sTemp. padRight (IVLength, ''); returnASCIIEncoding. ASCII. getBytes (sTemp );} /// <summary> /// encryption method /// </summary> /// <param name = "Source"> string to be encrypted </param> /// <returns> encrypted string </returns> publi CstringRijndaelEncrypt (stringSource) {byte [] bytIn = UTF8Encoding. UTF8.GetBytes (Source); MemoryStream MS = newMemoryStream (); mobjCryptoService. key = GetLegalKey (); mobjCryptoService. IV = GetLegalIV (); ICryptoTransform encrypto = mobjCryptoService. createEncryptor (); CryptoStream cs = newCryptoStream (MS, encrypto, CryptoStreamMode. write); cs. write (bytIn, 0, bytIn. length); cs. flushFinalBlock (); ms. close (); Byte [] bytOut = ms. toArray (); returnConvert. toBase64String (bytOut );} /// <summary> /// Decryption Method /// </summary> /// <param name = "Source"> string to be decrypted </param> /// <returns> decrypted string </returns> publicstringRijndaelDecrypt (stringSource) {try {byte [] bytIn = Convert. fromBase64String (Source); MemoryStream MS = newMemoryStream (bytIn, 0, bytIn. length); mobjCryptoService. key = GetLegalKey (); mobjCryptoService. IV = GetLega LIV (); ICryptoTransform encrypto = mobjCryptoService. createDecryptor (); CryptoStream cs = newCryptoStream (MS, encrypto, CryptoStreamMode. read); StreamReader sr = newStreamReader (cs); return sr. readToEnd ();} catch (Exception ex) {return ex. message ;}# endregion # region (3) Mix Base64 and UTF8 // string encryption publicstringBUEncrypt (string bb) {byte [] by = newbyte [bb. length]; by = System. text. encoding. UTF8.GetBytes (bb ); String r = Convert. toBase64String (by); return r;} // string decryption publicstringBUDecrypt (string aa) {try {byte [] by = Convert. fromBase64String (aa); string r = Encoding. UTF8.GetString (by); return r;} catch (Exception ex) {return ex. message ;}# endregion # region (4) fixed key algorithm publicstaticByte [] Iv64 = {, 44,}; publicstaticByte [] byKey64 =, 50, 60, 70, 80}; // string encryption publicstringSKeyEnc Rypt (string strText) {try {DESCryptoServiceProvider des = newDESCryptoServiceProvider (); Byte [] inputByteArray = Encoding. UTF8.GetBytes (strText); MemoryStream MS = newMemoryStream (); CryptoStream cs = newCryptoStream (MS, des. createEncryptor (byKey64, Iv64), CryptoStreamMode. write); cs. write (inputByteArray, 0, inputByteArray. length); cs. flushFinalBlock (); returnConvert. toBase64String (ms. toArray ();} cat Ch (Exception ex) {return ex. message ;}// string decryption publicstringSKeyDecrypt (string strText) {Byte [] inputByteArray = newbyte [strText. length]; try {DESCryptoServiceProvider des = newDESCryptoServiceProvider (); inputByteArray = Convert. fromBase64String (strText); MemoryStream MS = newMemoryStream (); CryptoStream cs = newCryptoStream (MS, des. createDecryptor (byKey64, Iv64), CryptoStreamMode. write); cs. write (I NputByteArray, 0, inputByteArray. length); cs. flushFinalBlock (); System. text. encoding encoding = System. text. encoding. UTF8; return encoding. getString (ms. toArray ();} catch (Exception ex) {return ex. message ;}# endregion # region (5) DES algorithm publicstaticbyte [] region ey = newbyte [] {0x82, 0xBC, 0xA1, 0x6A, 0xF5, 0x87, 0x3B, 0xE6, 0x59, 0x6A, 0x32, 0x64, 0x7F, 0x3A, 0x2A, 0xBB, 0x2B, 0x68, 0xE2, 0x5F, 0x06, 0xFB, 0xB8, 0x2D, 0x67,0 XB3, 0x55, 0x19, 0x4E, 0xB8, 0xBF, 0xDD }; /// <summary> // DES encryption // </summary> /// <param name = "strSource"> string to be encrypted </param> // <param name = "key"> 32-bit Key value </param> // <returns> encrypted string </returns> publicstringDESEncrypt (string strSource) {returnDESEncryptF (strSource, cipher ey);} privatestringDESEncryptF (string strSource, byte [] key) {fig sa = Rijndael. create (); sa. key = key; sa. mode = CipherMode. EC B; sa. padding = PaddingMode. zeros; MemoryStream MS = newMemoryStream (); CryptoStream cs = newCryptoStream (MS, sa. createEncryptor (), CryptoStreamMode. write); byte [] byt = Encoding. unicode. getBytes (strSource); cs. write (byt, 0, byt. length); cs. flushFinalBlock (); cs. close (); returnConvert. toBase64String (ms. toArray ());} /// <summary> // DES decryption // </summary> /// <param name = "strSource"> string to be decrypted </param> /// <pa Ram name = "key"> 32-bit Key value </param> // <returns> decrypted string </returns> publicstringDESDecrypt (string strSource) {returnDESDecryptF (strSource, required ey);} privatestringDESDecryptF (string strSource, byte [] key) {try {fig sa = Rijndael. create (); sa. key = key; sa. mode = CipherMode. ECB; sa. padding = PaddingMode. zeros; ICryptoTransform ct = sa. createDecryptor (); byte [] byt = Convert. fromBase64String (strS Ource); MemoryStream MS = newMemoryStream (byt); CryptoStream cs = newCryptoStream (MS, ct, CryptoStreamMode. read); StreamReader sr = newStreamReader (cs, Encoding. unicode); return sr. readToEnd ();} catch (Exception ex) {return ex. message ;}# endregion # region (6) encrypted password MD5T and SHA1 /// <summary> // encrypted password MD5T and SHA1 /// </summary> /// <param name = "strSource"> string </ param> /// <param name = "strFlag"> encryption type </param> /// <Param name = "substringlen"> encryption length </param> /// <returns> </returns> // publicstring encrypting (string strSource, int strFlag, int substringlen) {string ss = ""; if (strFlag = 1) // MD5 encryption {if (substringlen = 16) // 16-bit MD5 encryption (9 ~ with 32-bit encryption ~ 25 characters) {ss = FormsAuthentication. hashPasswordForStoringInConfigFile (strSource, "MD5 "). toLower (). substring (8, 16);} elseif (substringlen = 32) // 32-bit encryption {ss = FormsAuthentication. hashPasswordForStoringInConfigFile (strSource, "MD5 "). toLower () ;}} elseif (strFlag = 2) // SHA1 encryption {if (substringlen = 16) // SHA1 16-bit encryption {ss = FormsAuthentication. hashPasswordForStoringInConfigFile (strSource, "SHA1 "). toLower (). substring (8, 16);} elseif (substringlen = 32) // SHA1 40-bit encryption {ss = FormsAuthentication. hashPasswordForStoringInConfigFile (strSource, "SHA1 "). toLower () ;}} else {ss = "" ;}return ss ;}# endregion }}

 

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.