usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.Security.Cryptography;usingSystem.IO;namespaceencryptanddecrypt{ Public classCryptoutil {//random definition of 8-byte key and initialization vector Private byte[] key_64 =New byte[] {1,2,3,3,4,5,6,4}; Private byte[] iv_64 =New byte[] {2,3,4,5,3,4,3,2}; /// <summary> ///Encrypt/// </summary> /// <param name= "str" >strings that need to be encrypted</param> /// <returns>the encrypted string</returns> Public stringEncrypt (stringstr) { if(str = ="")returnstr; DESCryptoServiceProvider CryptoProvider=NewDESCryptoServiceProvider (); MemoryStream Ms=NewMemoryStream (); CryptoStream CS=NewCryptoStream (MS, Cryptoprovider.createencryptor (key_64, iv_64), cryptostreammode.write); StreamWriter SW=NewStreamWriter (CS); stringCyrstr =""; Try{SW. Write (str); Sw. Flush (); Cs. FlushFinalBlock (); Ms. Flush (); //Converts an encrypted byte array into a stringCyrstr = convert.tobase64string (ms. GetBuffer (),0, (int) Ms. Length); } finally{SW. Close (); Cs. Close (); Ms. Close (); Cryptoprovider.clear (); } returnCyrstr; } /// <summary> ///decryption/// </summary> /// <param name= "str" >A string that has been encrypted</param> /// <returns>the decrypted string</returns> Public stringDecrypt (stringstr) { if(str = ="")returnstr; //Convert a string into a byte array byte[] Strbyte =convert.frombase64string (str); DESCryptoServiceProvider CryptoProvider=NewDESCryptoServiceProvider (); MemoryStream Ms=NewMemoryStream (Strbyte); CryptoStream CS=NewCryptoStream (MS, Cryptoprovider.createdecryptor (key_64, iv_64), cryptostreammode.read); StreamReader SR=NewStreamReader (CS); stringUncrystr =""; Try{uncrystr=Sr. ReadToEnd (); } finally{Sr. Close (); Cs. Close (); Ms. Close (); Cryptoprovider.clear (); } returnUncrystr; } } Public classProgram { Public Static voidMain (string[] args) {Cryptoutil crypt=NewCryptoutil (); stringText ="KingSoft"; stringEn =Crypt. Encrypt (text); Console.WriteLine (en); stringDe =Crypt. Decrypt (en); Console.WriteLine (DE); } }}
C # Base64 plus decryption