Des Cross (C # Android IOS) Three platforms common encryption and decryption method

Source: Internet
Author: User

       #region   cross-platform plus decryption (C # Android IOS)      // public static string SKey = "12345 678 ";     // ///<summary>     // ///decryption      // // /</summary>     // ///<param name= "Ptodecrypt" > to Decrypt to base64</param>     // ///<param name= "SKey" > key, and must be 8-bit </param>     // ///<returns > decrypted string </returns>     // public static string Desdecrypt (String ptodecrypt)      / {     //     //escape special characters      //    &NBSP;PT Odecrypt = Ptodecrypt.replace ("-", "+");     /     ptodecrypt = Ptodecrypt.replace ("_", " /");     /     ptodecrypt = Ptodecrypt.replace (" ~ "," = ");     //  & nbsp  byte[] Inputbytearray = ConveRt. FromBase64String (ptodecrypt);     /     using (descryptoserviceprovider des = new descry Ptoserviceprovider ())      //     {     //        &NBS P;des. Key = ASCIIEncoding.ASCII.GetBytes (sKey);     /        &NBSP;DES.IV = ASCIIEncoding. Ascii. GetBytes (SKey);     /         system.io.memorystream ms = new System.IO.MemoryS Tream ();     /         using (CryptoStream cs = new CryptoStream (MS, Des. CreateDecryptor (), CryptoStreamMode.Write)      //         {    &NBSP ;              cs. Write (Inputbytearray, 0, Inputbytearray.length);     /            &NBSP;CS . FlushFinalBlock ();     /          &NBSP;  cs. Close ();     /         }     //        &NB sp;string str = Encoding.UTF8.GetString (MS. ToArray ());     /         ms. Close ();     /         return str;     //    &NBSP;}      // }      // ///<summary>     // /// String for DES encryption      // ///</summary>     // ///<param name= "sourcestring > Strings to be encrypted </param>     // ///<returns> encrypted BASE64 encoded strings </returns>     // public string Encrypt (String sourcestring)      //{     //  by te[] BtKey = Encoding.UTF8.GetBytes (sKey);     /  byte[] Btiv = Encoding.UTF8.GetBytes (SKey); &nbsp ;    //  &NBSP;descryptoserviceprovider des = new DESCryptoServiceProvider ();     /   using (MemoryStream ms = new MemoryStream ())      //   {     //       byte[] in Data = Encoding.UTF8.GetBytes (sourcestring);     /       try     //        {     //           using (CryptoStream cs = new CryptoStream (MS, Des. CreateEncryptor (BtKey, Btiv), CryptoStreamMode.Write)      //           {& nbsp    /               cs. Write (inData, 0, Indata.length);     /               cs. FlushFinalBlock ();     /           }      //  & nbsp        return convert.tobase64String (Ms. ToArray ());     /       }     //      &NBSP;CATCH&NB Sp    /       {     //           throw;     /       }     //   }     //}                #endregion       Android---------------------------------------------------------------------------   /   //decryption    //public static string decryptdonet (String message, string key)    //      &NBSP;T Hrows Exception {   //   byte[] bytesrc = Base64.decode (Message.getbytes (), Base64.default);   //   cipher Cipher = cipher.getinstance ("des/cbc/pkcs5padding");   //    Deskeyspec Deskeyspec = new Deskeyspec (key.getbytes ("UTF-8"));nbsp  //   secretkeyfactory keyfactory = secretkeyfactory.getinstance ("DES");   //    Secretkey Secretkey = Keyfactory.generatesecret (deskeyspec);   //   ivparameterspec IV = new IvPara Meterspec (Key.getbytes ("UTF-8"));   //   cipher.init (Cipher.decrypt_mode, Secretkey, iv);    //   byte[] Retbyte = cipher.dofinal (BYTESRC);   //   return new String (ret Byte);   //}    ////encryption    //public static string encryptasdonet (String message, Stri ng key)    /       throws Exception {   //   cipher Cipher = Cipher. getinstance ("des/cbc/pkcs5padding");   //   deskeyspec Deskeyspec = new Deskeyspec (Key.getbytes ( "UTF-8"));   //   secretkeyfactory keyfactory = secretkeyfactory.getinstance ("DES");   //   secretkey Secretkey = kEyfactory.generatesecret (DESKEYSPEC);   //   ivparameterspec IV = new IVPARAMETERSPEC ( Key.getbytes ("UTF-8");   //   cipher.init (Cipher.encrypt_mode, Secretkey, iv);   //& nbsp  byte[] Encryptbyte = cipher.dofinal (Message.getbytes ());   //   return new String ( Base64.encode (Encryptbyte, Base64.default));   //}   ios------------------------------- -------------------------------------------------------------------------------------\//Encryption + (NSString *) Decryptwithcontent: (NSString *) content{        char * KeyChar = (char*) [@ "Encryption Key" utf8string];& nbsp      nsstring *JM = [NSString stringwithcstring:encryptwithkeyandtype ([content utf8string], Kccencrypt, KeyChar) encoding:nsutf8stringencoding];        return [nsstring stringwithformat:@ "%@%@%@" , qstr,jm,hstr]; }//decryption + (NSData *) Encryptwithcontent: (NSData *) content{   NSString *contentstr = [[NSString alloc] initwithdata:content encoding:nsutf8stringencoding];         if (contentstr = = Nil | | [Contentstr isequaltostring:@ ""]) {        return nil;   }        contentstr= [Contentstr Substringw Ithrange:nsmakerange (4,contentstr.length-8)];        const char * Contentchar =[CONTENTSTR utf8string];    char * KeyChar = (char*) [@ "Encryption Key" utf8string];    const char *michar;    MICH AR = Encryptwithkeyandtype (Contentchar, Kccdecrypt, KeyChar);    if (Michar = nil) {        Michar = "";   }        NSString *zmstr = [NSString Stringwithcstring:michar encoding :nsutf8stringencoding];    if (zmstr = = nil) {        ZMSTR [email protected] "";   }    return [Zmstr datausingencoding:nsutf8stringencoding];}    static Const char* encryptwithkeyandtype (const char *text,ccoperation encryptoperation,char *key) {    NSString *textstring=[[nsstring alloc]initwithcstring:text encoding:nsutf8stringencoding];   //     nslog (@ "[[item.url description] utf8string=%@", textstring);    const void *datain;    size_t datainlength;        if (encryptoperation = = Kccdecrypt)//pass over decrypt decode     {       /decode base64        NSData *decryptdata = [GTMBase64 Decodedata:[textstrin G datausingencoding:nsutf8stringencoding]];//turn into Utf-8 and decode        datainlength = [Decryptdata length];        DataIn = [Decryptdata bytes];   }    Else  //encrypt  & nbsp {        nsdata* encryptData = [textstring datausingencoding:nsutf8stringencoding];    & nbsp   Datainlength = [EncryptData Length];        DataIn = (const void *) [encryptData bytes];   }             cccryptorstatus ccstatus;    uint8_t *dataout = NULL; can understand the abbreviation of bit type/typedef (effectively maintain the code, such as: a person with int, a person with a long.) Best defined with typedef)     size_t dataoutavailable = 0; size_t   is operator sizeof returns the result type     size_t dataoutmoved = 0;        dataoutavailable = (Datainlength + kccblocksizedes) & ~ (kCCBlockSizeDES-1);    dataout = malloc (dataoutavailable * sizeof ( uint8_t);    memset ((void *) Dataout, XX, dataoutavailable);//Set the first 1 bytes of the open memory space buffer to the value 0        //nsstring *initiv = @ "12345678";    const void *vkey = key;    const void *IV = ( const void *) key; [Initiv utf8string];       //cccrypt function encryption/decryption     Ccstatus = Cccrypt ( encryptoperation,//  Encryption/decryption               &NBsp        kccalgorithmdes,//  encryption based on which criteria (Des,3des,aes ....                        kccoptionpkcs7padding,//  Options Group cipher Method (des: Add a secret  3des for each block: three different secrets per block)                       &NBSP ; vkey,  //key     Encryption and decryption keys must be consistent                       &N bsp;kcckeysizedes,//  DES key size (kcckeysizedes=8)                   &NBSP ;   &NBSP;IV,//  selectable initial vector                        datain ,//Data storage unit                        datainlength,//data size                         (void *) dataout,//for return data                       &NBSP;d ataoutavailable,                       &dataoutmoved), & nbsp       NSString *result = nil;        if (encryptoperation = = Kccdecrypt)//en Cryptoperation==1   decode     {       //Get decrypted data, change to Utf-8 string       & nbsp result = [[NSString alloc] initwithdata:[nsdata datawithbytes: (const void *) Dataout length: (Nsuinteger) dataoutmoved] encoding:nsutf8stringencoding];   }    Else//encryptoperation==0   (during the encryption process, Convert well-coded data to base64)     {       //encode base64        NSData *data = [NSData Datawithbytes: (const void *) Dataout length: (nsuinteger) dataoutmoved];        result = [GTMBase64 stringbyencodingdata:data];   }        Return [result utf8string];     }                            ios----------------------------------------------------------------------------------------------------- ---------------\static Const char* encryptwithkeyandtype (const char *text,ccoperation Encryptoperation,char *key) {     NSString *textstring=[[nsstring alloc]initwithcstring:text encoding:nsutf8stringencoding];   /     nslog (@ "[[[Item.url description] utf8string=%@", textstring);    const void * datain;    size_t datainlength;        if (encryptoperation = = kccdecrypt)// Pass through is decrypt decode     {       //decode base64        NSData *decryptdata = [G TMBase64 decodedata:[textstring datausingencoding:nsutf8stringencoding]];//turn utf-8 and decode        Datainlength = [Decryptdata length];        datain = [Decryptdata bytes];   }    Else  //encrypt    {        nsdata* encryptData = [textst Ring datausingencoding:nsutf8stringencoding];        datainlength = [EncryptData length];  & nbsp     DataIn = (const void *) [encryptData bytes];   }          &nbsp ; Cccryptorstatus ccstatus;    uint8_t *dataout = NULL; can understand the abbreviation of bit type/typedef (effectively maintain the code, such as: a person with int, a person with a long.) Best defined with typedef)     size_t dataoutavailable = 0; size_t   is operator sizeof returns the result type     size_t dataoutmoved = 0;        dataoutavailable = (Datainlength + kccblocksizedes) & ~ (kCCBlockSizeDES-1);    dataout = malloc (dataoutavailable * sizeof ( uint8_t);    memset ((void *) Dataout, XX, dataoutavailable);//Set the first 1 bytes of the open memory space buffer to the value 0        //nsstring *initiv = @ "12345678";    const void *vkey = key;  &nbsP const void *IV = (const void *) key; [Initiv utf8string];       //cccrypt function encryption/decryption     Ccstatus = Cccrypt ( encryptoperation,//  Encryption/decryption                        kccalgor ithmdes,//  Encryption according to which criteria (Des,3des,aes ....                        kccoptionpkcs7padding,//  Options Group cipher Method (des: Add a secret  3des for each block: three different secrets per block)                       &NBSP ; vkey,  //key     Encryption and decryption keys must be consistent                       &N bsp;kcckeysizedes,//  DES key size (kcckeysizedes=8)                   &NBSP ;   &NBSP;IV,//  selectable initial vector                        datain ,//Data storage unit                   &NBSP    datainlength,//data size                         (void) *) dataout,//for return data                       &NBSP;DATAOUTAVAILABLE,&N Bsp                      &dataoutmoved);      & nbsp NSString *result = nil;        if (encryptoperation = = kccdecrypt)//encryptoperation==1   Decode     {       //Get decrypted data, change to Utf-8 string         result = [[NSString a] Lloc] Initwithdata:[nsdata datawithbytes: (const void *) Dataout length: (nsuinteger) dataoutmoved] Encoding: nsutf8stringencoding];   }    Else//encryptoperation==0   (in the process of encryption, turn the encrypted data into base64)     {       //encode base64        NSData *data = [NSData datawithbytes: (const voi d *) dataout length: (Nsuinteger) Dataoutmoved];        result = [GTMBase64 stringbyencodingdata:data];   }    & nbsp   Return [result utf8string];    }+ (nsstring*) Encryptwithcontent: (nsstring*) content type: ( ccoperation) type key: (nsstring*) akey{    const char * Contentchar =[content utf8string];    char * key Char = (char*) [Akey utf8string];    const char *michar;    Michar = Encryptwithkeyandtype (Contentchar , type, KeyChar);    return  [nsstring Stringwithcstring:michar encoding:nsutf8stringencoding];}

des Cross (C # Android IOS) Three platforms common encryption and decryption method

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.