Des asymmetric encryption and decryption across platforms (C #, Android, iOS)

Source: Internet
Author: User
Tags asymmetric encryption

#regionCross-platform plus decryption (C # Android IOS) Public Static stringSKey ="123456"; /// <summary>        ///decryption/// </summary>        /// <param name= "Ptodecrypt" >To decrypt the Base64</param>        /// <param name= "SKey" >Key , and must be 8-bit</param>        /// <returns>decrypted String</returns>         Public Static stringDesdecrypt (stringPtodecrypt) {            //Escape Special CharactersPtodecrypt = Ptodecrypt.replace ("-","+"); Ptodecrypt= Ptodecrypt.replace ("_","/"); Ptodecrypt= Ptodecrypt.replace ("~","="); byte[] Inputbytearray =convert.frombase64string (Ptodecrypt); using(DESCryptoServiceProvider des =NewDESCryptoServiceProvider ()) {des. Key=ASCIIEncoding.ASCII.GetBytes (SKey); Des.iv=ASCIIEncoding.ASCII.GetBytes (SKey); System.IO.MemoryStream Ms=NewSystem.IO.MemoryStream (); using(CryptoStream cs =NewCryptoStream (MS, Des. CreateDecryptor (), cryptostreammode.write)) {cs. Write (Inputbytearray,0, inputbytearray.length); Cs.                    FlushFinalBlock (); Cs.                Close (); }                stringstr =Encoding.UTF8.GetString (Ms.                ToArray ()); Ms.                Close (); returnstr; }        }        /// <summary>        ///des encryption of strings/// </summary>        /// <param name= "sourcestring" >string to encrypt</param>        /// <returns>BASE64 encoded string after encryption</returns>         Public Static stringEncrypt (stringsourcestring) {            byte[] BtKey =Encoding.UTF8.GetBytes (SKey); byte[] Btiv =Encoding.UTF8.GetBytes (SKey); DESCryptoServiceProvider des=NewDESCryptoServiceProvider (); using(MemoryStream ms =NewMemoryStream ()) {                byte[] InData =Encoding.UTF8.GetBytes (sourcestring); Try                {                    using(CryptoStream cs =NewCryptoStream (MS, Des. CreateEncryptor (BtKey, Btiv), CryptoStreamMode.Write)) {cs. Write (InData,0, indata.length); Cs.                    FlushFinalBlock (); }                    returnconvert.tobase64string (Ms.                ToArray ()); }                Catch                {                    Throw; }            }        }        #endregion        //Android ---------------------------------------------------------------------------//    //decryption//Public static string decryptdonet (String message, string key)//throws Exception {//byte[] bytesrc = Base64.decode (Message.getbytes (), base64.default); //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.decrypt_mode, Secretkey, iv); //byte[] Retbyte = cipher.dofinal (BYTESRC); //return new String (Retbyte); //}        ////Encryption        //Public static string encryptasdonet (String message, string 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); //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"; nsstring* JM = [NSString stringwithcstring:encryptwithkeyandtype ([content utf8string], Kccencrypt, KeyChar) encoding:                          Nsutf8stringencoding];       return [NSString stringwithformat:@ "%@", JM]; }//Decryption + (nsdata*) Encryptwithcontent: (nsdata*) content {nsstring* contentstr = [[NSString alloc           ] Initwithdata:content encoding:nsutf8stringencoding]; if (contentstr = = Nil | | [Contentstr isequaltostring:@ ""])           {return nil;           } contentstr= [Contentstr substringwithrange:nsmakerange (4, contentstr.length-8)];       Const char* Contentchar =[contentstr utf8string];       char* KeyChar = (char*) [@ "Encryption key" utf8string]; Const char* MIChar;           Michar = 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 is decrypt decoding {//decoding base64 nsdata* DECRYPTD ATA = [GTMBase64 decodedata:[textstring datausingencoding:nsutf8stringencoding]];//turns into utf-8 and decode dataInlength = [Decryptdata length];           DataIn = [Decryptdata bytes]; } else//encrypt {nsdata* EncryptData = [TextString Datausingencoding:nsutf8stringenc       Oding];               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.) It is best to use typedef to define) size_t dataoutavailable = 0;       size_t is the result type returned by the operator sizeof 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 memory space buffer to a value of 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 kccalgorithmdes,//encryption according to which standard (Des,3des,aes ....                              ) kccoptionpkcs7padding,//option block cipher algorithm (des: Add a secret 3DES for each block grouping: Three different secrets per block)                              Vkey,//key encryption and decryption keys must be consistent kcckeysizedes,//the size of the DES key (kcckeysizedes=8) IV,//optional initial vector datain,//data storage unit Datainlength                              ,//Data size (void*) dataout,//used to return the data dataoutavailable,           &dataoutmoved);           nsstring* result = nil;               if (encryptoperation = = Kccdecrypt)//encryptoperation==1 decode {//Get decrypted data, change to Utf-8 string result = [[NSString alloc] initwithdata:[nsdata datawithbytes: (const void *) Dataout length: (Nsuinteger) Datao           Utmoved] encoding:nsutf8stringencoding]; } else//encryptoperatIon==0 (in the encryption process, the well-encrypted data into 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 over is decrypt decoding {//decoding base64 nsdata* DECRYPTD ATA = [GTMBase64 decodedata:[textstring datausingencoding:nsutf8stringencoding]];//turn into utf-8 and decode datainlength = [Decryptdata length];           DataIn = [Decryptdata bytes]; } else//encrypt {nsdata* EncryptData = [TextString Datausingencoding:nsutf8stringenc       Oding];               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.) It is best to use typedef to define) size_t dataoutavailable = 0;       size_t is the result type returned by the operator sizeof 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 memory space buffer to a value of 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 kccalgorithmdes,//encryption according to which criteria (Des,3des,aes 。。。。                              ) kccoptionpkcs7padding,//option block cipher algorithm (des: Add a secret 3DES for each block grouping: Three different secrets per block)                              Vkey,//key encryption and decryption keys must be consistent kcckeysizedes,//the size of the DES key (kcckeysizedes=8) IV,//optional initial vector datain,//data storage unit Datainlength                              ,//Data size (void*) dataout,//used to return the data dataoutavailable,           &dataoutmoved);           nsstring* result = nil;               if (encryptoperation = = Kccdecrypt)//encryptoperation==1 decode {//Get decrypted data, change to Utf-8 string result = [[NSString alloc] initwithdata:[nsdata datawithbytes: (const void *) Dataout length: (Nsuinteger) Datao           Utmoved] encoding:nsutf8stringencoding];  }         Else//encryptoperation==0 (during encryption, turn the encrypted data into Base64) {//Encode base64 nsdata*               data = [NSData datawithbytes: (const void *) Dataout length: (Nsuinteger) dataoutmoved];           result = [GTMBase64 stringbyencodingdata:data];       } return [result utf8string]; } + (nsstring*) Encryptwithcontent: (nsstring*) Content type: (ccoperation) type key: (nsstring*) Akey {con       St char* Contentchar =[content utf8string];       char* KeyChar = (char*) [Akey utf8string];       Const char* Michar;           Michar = Encryptwithkeyandtype (Contentchar, type, KeyChar);       return [NSString Stringwithcstring:michar encoding:nsutf8stringencoding];        }*/

Pro-Test available: Comes with an iOS source code

Https://files.cnblogs.com/files/xiang-wei/ios_des%E5%8A%A0%E5%AF%86.zip

Des asymmetric encryption and decryption across platforms (C #, Android, iOS)

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.