C # common encryption and decryption methods for IOS/Android,

Source: Internet
Author: User

C # common encryption and decryption methods for IOS/Android,

The company is working on ios/android on mobile terminals, and the server provides interfaces for use... net cannot be decrypted by encrypting android, or vice versa. The following describes how to encrypt and decrypt data on all three platforms. Key = "1234578" used in encryption and decryption; you can pass the value when calling the method.

C # code

# Region cross-platform encryption and decryption (c #) /// <summary> /// perform DES encryption on the string /// </summary> /// <param name = "sourceString"> string to be encrypted </param> /// <returns> encrypted BASE64 encoded string </returns> public string Encrypt (string sourceString, string sKey) {byte [] btKey = Encoding. UTF8.GetBytes (sKey); byte [] btIV = Encoding. UTF8.GetBytes (sKey); DESCryptoServiceProvider des = new DESCryptoServiceProvider (); using (MemoryStream MS = new MemoryStrea M () {byte [] inData = Encoding. UTF8.GetBytes (sourceString); try {using (CryptoStream cs = new CryptoStream (MS, des. createEncryptor (btKey, btIV), CryptoStreamMode. write) {cs. write (inData, 0, inData. length); cs. flushFinalBlock ();} return Convert. toBase64String (ms. toArray () ;}catch {throw ;}}} /// <summary> /// decrypt /// </summary> /// <param name = "pToDecrypt"> Base64 </param> /// <param na Me = "sKey"> key, which must be an 8-bit </param> // <returns> decrypted string </returns> public string Decrypt (string pToDecrypt, string sKey) {// escape special character pToDecrypt = pToDecrypt. replace ("-", "+"); pToDecrypt = pToDecrypt. replace ("_", "/"); pToDecrypt = pToDecrypt. replace ("~ "," = "); Byte [] inputByteArray = Convert. fromBase64String (pToDecrypt); using (DESCryptoServiceProvider des = new DESCryptoServiceProvider () {des. key = ASCIIEncoding. ASCII. getBytes (sKey); des. IV = ASCIIEncoding. ASCII. getBytes (sKey); System. IO. memoryStream MS = new System. IO. memoryStream (); using (CryptoStream cs = new CryptoStream (MS, des. createDecryptor (), CryptoStreamMode. write) {cs. write (inputByteArray, 0, inputByteArray. length); cs. flushFinalBlock (); cs. close ();} string str = Encoding. UTF8.GetString (ms. toArray (); ms. close (); return str ;}# endregion

IOS code

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) // transmit decrypt decoding {// decodes base64 NSData * decryptData = [GTMBase64 decodeData: [TextString dataUsingEncoding: NSUTF8StringEncoding]; // convert UTF-8 and decode dataInLength = [decryptData length]; dataIn = [decryptData bytes];} else // encrypt {NSData * encryptData = [textString dataUsingEncoding: Encrypted]; dataInLength = [encryptData length]; dataIn = (const void *) [encryptData bytes];} CCCryptorStatus ccStatus; uint8_t * dataOut = NULL; // understand the abbreviation of the bit type/typedef (effective maintenance code ratio: Use int to use lo Ng defined by typedef) size_t dataOutAvailable = 0; // size_t operator sizeof return type size_t dataOutMoved = 0; dataOutAvailable = (dataInLength + kCCBlockSizeDES )&~ (KCCBlockSizeDES-1); dataOut = malloc (dataOutAvailable * sizeof (uint8_t); memset (void *) dataOut, 00, dataOutAvailable ); // set the first byte value of the buffer in the memory space to 0 // NSString * initIv = @ "12345678"; const void * vkey = key; const void * iv = (const void *) key; // [initIv UTF8String]; // CCCrypt function encryption/Decryption ccStatus = CCCrypt (encryptOperation, // encrypt/decrypt kCCAlgorithmDES, // which standard is used for encryption (des3desaes) kCCOptionPKCS7Padding? // calculate the authorization group password (des: each group is encrypted 3DES: each group is encrypted with three same passwords) vkey, // The key must be encrypted and decrypted by kCCKeySizeDES, // DES key (kCCKeySizeDES = 8) iv, // select the initial vector dataIn, // data storage unit dataInLength, // data (void *) dataOut, // used to return data dataOutAvailable, & dataOutMoved); NSString * result = nil; if (encryptOperation = kCCDecrypt) // encryptOperation = 1 decoding {// decrypting data changes the UTF-8 string result = [[NSString alloc] initWithData: [NSData dataWithBytes :( const void *) dataOut length :( NSUInteger) dataOutMoved] encoding: NSUTF8StringEncoding];} else // encryptOperation = 0 (the encrypted data is converted to 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 {const char * contentChar = [content UTF8String]; char * keyChar = (char *) [aKey UTF8String]; const char * miChar; miChar = encryptWithKeyAndType (contentChar, type, keyChar); return [NSString stringWithCString: miChar encoding: NSUTF8StringEncoding];}

Android code

// Encrypt 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"); inclueyspec = new inclueyspec (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);} // decrypt public static String EncryptAsDoNet (String message, String key) throws Exception {Cipher cipher = Cipher. getInstance ("DES/CBC/PKCS5Padding"); inclueyspec = new inclueyspec (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 ));}

 

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.