The use of AES encryption in iOS

Source: Internet
Author: User

Now do the app, because of security, so the use of AES encryption, and paired with the use of Android AES encryption.

. h file

#import <Foundation/Foundation.h> #import <CommonCrypto/CommonCryptor.h> #import <commoncrypto/ commonkeyderivation.h> #define AES_KEY @ "[email protected]!*&y.) X#[;> "#define AES_IV @" 0102030405060708 "@interface NSData (AES) + (NSString *) Aesencryptwithdata: (NSData *) data;+ ( NSData *) Aesdecryptwithtext: (NSString *) text;

. m file

#import "Nsdata+aes.h" @implementation NSData (AES) static const char encodingtable[] = " abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789+/"; + (NSString *) Aesencryptwithdata: (NSData *) data  {//' key ' should is bytes for AES256, 'll be null-padded otherwise char keyptr[kcckeysizeaes256+1];// Terminator (unused) bzero (keyptr, sizeof (KEYPTR));        Fill with zeroes (for padding) nsuinteger datalength = [data length];    size_t buffersize = datalength + kCCBlockSizeAES128;    void *buffer = malloc (buffersize);        bzero (buffer, sizeof (buffer));        size_t numbytesencrypted = 0;                                          Cccryptorstatus cryptstatus = Cccrypt (Kccencrypt, kccalgorithmaes128,kccoptionpkcs7padding,                                          [[Aes_key datausingencoding:nsutf8stringencoding] bytes], kCCKeySizeAES128,                     [[Aes_iv datausingencoding:nsutf8stringencoding] bytes]/* initialization vector (optional) */,                     [Data bytes], datalength,/* input */buffer, buffersize,/*    Output */&numbytesencrypted); if (Cryptstatus = = kccsuccess) {NSData *encryptdata = [NSData datawithbytesnocopy:buffer length:numbytesencrypted]        ;            return [EncryptData base64encoding2]; } free (buffer);    Free the buffer; return nil;}    + (NSData *) Aesdecryptwithtext: (NSString *) text{nsdata *cipherdata = [NSData Datawithbase64encodedstring:text]; ' Key ' should is bytes for AES256, 'll be null-padded otherwise char keyptr[kcckeysizeaes256+1]; The Terminator (unused) bzero (keyptr, sizeof (KEYPTR));        Fill with zeroes (for padding) nsuinteger datalength = [CipherData length];    size_t buffersize = datalength + kCCBlockSizeAES128;        void *buffer = malloc (buffersize);    size_t numbytesdecrypted = 0; Cccryptorstatus cryptstatus = Cccrypt (kccdecryPT, kCCAlgorithmAES128, kccoptionpkcs7padding, [[Aes_key Datausingencoding:nsutf8 Stringencoding] bytes], kCCKeySizeAES128, [[Aes_iv datausingencoding:nsutf8string Encoding] bytes],/* initialization vector (optional) */[CipherData bytes], data                                          Length,/* input */buffer, buffersize,/* output */        &numbytesdecrypted);    if (Cryptstatus = = kccsuccess) {return [NSData datawithbytesnocopy:buffer length:numbytesdecrypted]; } free (buffer);    Free the buffer; return nil;} + (ID) datawithbase64encodedstring: (NSString *) string;    {if (string = nil) [NSException raise:nsinvalidargumentexception Format:nil];        if ([string length] = = 0) return [NSData data];    static char *decodingtable = NULL; if (decodingtable = = NULL) {decodingtable = malloc (256);        if (decodingtable = = NULL) return nil;        memset (decodingtable, Char_max, 256);        Nsuinteger i;    for (i = 0; i <, i++) decodingtable[(short) encodingtable[i]] = i;    } const char *characters = [string cstringusingencoding:nsasciistringencoding];        if (characters = = NULL)//Not an ASCII string!    return nil;    Char *bytes = malloc ((([string length] + 3)/4) * 3);    if (bytes = = NULL) return nil;        Nsuinteger length = 0;    Nsuinteger i = 0;        while (YES) {char buffer[4];        Short bufferlength;            for (bufferlength = 0; bufferlength < 4; i++) {if (characters[i] = = ' + ') break;            if (Isspace (characters[i]) | | characters[i] = = ') continue;            Buffer[bufferlength] = decodingtable[(short) characters[i]];            if (buffer[bufferlength++] = = Char_max)//illegal character!           {     Free (bytes);            return nil;        }} if (bufferlength = = 0) break;        if (bufferlength = = 1)//At least-characters is needed to produce one byte!            {free (bytes);        return nil;        }//Decode the characters in the buffer to bytes. bytes[length++] = (Buffer[0] << 2) |        (Buffer[1] >> 4); if (Bufferlength > 2) bytes[length++] = (buffer[1] << 4) |        (Buffer[2] >> 2); if (Bufferlength > 3) bytes[length++] = (buffer[2] << 6) |    BUFFER[3];    } bytes = realloc (bytes, length); return [NSData datawithbytesnocopy:bytes length:length];} -(NSString *) base64encoding2;        {if ([self length] = = 0) return @ "";    Char *characters = malloc (([Self length] + 2)/3) * 4);    if (characters = = NULL) return nil;        Nsuinteger length = 0;    Nsuinteger i = 0; while (i < [self lengTH]) {char buffer[3] = {0,0,0};        Short bufferlength = 0; while (Bufferlength < 3 && i < [self length]) buffer[bufferlength++] = ((char *) [self bytes]) [i++                ];        Encode the bytes in the buffer to four characters, including padding "=" characters if necessary.        characters[length++] = encodingtable[(buffer[0] & 0xFC) >> 2]; characters[length++] = encodingtable[((buffer[0] & 0x03) << 4) |        ((Buffer[1] & 0xF0) >> 4)]; if (Bufferlength > 1) characters[length++] = encodingtable[((buffer[1] & 0x0F) << 2) |        ((Buffer[2] & 0xC0) >> 6)];        else characters[length++] = ' = ';        if (Bufferlength > 2) characters[length++] = encodingtable[buffer[2] & 0x3F];    else characters[length++] = ' = '; } return [[NSString alloc] initwithbytesnocopy:characters length:length encoding:nsasciistringencoding freeWhenDone : YES];} @end

Java file

Package Com.yuxin168.library.util;import Java.io.unsupportedencodingexception;import Java.security.invalidalgorithmparameterexception;import Java.security.invalidkeyexception;import Java.security.nosuchalgorithmexception;import Javax.crypto.badpaddingexception;import Javax.crypto.Cipher;import Javax.crypto.illegalblocksizeexception;import Javax.crypto.nosuchpaddingexception;import  Javax.crypto.spec.ivparameterspec;import javax.crypto.spec.secretkeyspec;import android.util.Base64;/** * AESº "√‹* * @author Baoyz * */public class AES {public static final string Vipara = "0102030405060708";p ublic static final string b m = "UTF-8";/** *º "√‹* * @param content *–ë" ™º "√‹µƒƒ⁄»›* @param password *º" √‹√‹¬î* @return * /public static string Encrypt (string content) {try {ivparameterspec zeroiv = new Ivparameterspec (Vipara.getbytes ()); Secretkeyspec key = new Secretkeyspec (GetKey (). GetBytes (), "AES"); Cipher Cipher = cipher.getinstance ("aes/cbc/pkcs5padding"); Cipher.init (CiPher. Encrypt_mode, key, ZEROIV); byte[] EncryptedData = cipher.dofinal (content.getbytes (BM)); return base64.encodetostring ( EncryptedData, 0);} catch (NoSuchAlgorithmException e) {e.printstacktrace ();} catch (Nosuchpaddingexception e) {e.printstacktrace ();} catch (InvalidKeyException e) {e.printstacktrace ();} catch (Unsupportedencodingexception e) {e.printstacktrace ();} catch (Illegalblocksizeexception e) {e.printstacktrace ();} catch (Badpaddingexception e) {e.printstacktrace ();} catch ( Invalidalgorithmparameterexception e) {e.printstacktrace ();} return null;} /** *ω ' √‹* * @param content *¥?ω ' √‹ƒ⁄»›* @param password *ω ' √‹√‹ ' ø* @return */public static S Tring Decrypt (String content) {try {byte[] Bytemi = Base64.decode (content.getbytes (BM), 0); Ivparameterspec zeroiv = new Iv Parameterspec (Vipara.getbytes ()); Secretkeyspec key = new Secretkeyspec (GetKey (). GetBytes (), "AES"); Cipher Cipher = cipher.getinstance ("aes/cbc/pkcs5padding"); Cipher.init (Cipher.decrypt_mode, key, ZEROIV); byte[] Decrypteddata = cipher.dofinal (Bytemi); return new String (Decrypteddata, BM);} catch (NoSuchAlgorithmException e) {e.printstacktrace ();} catch (Nosuchpaddingexception e) {e.printstacktrace ();} catch (InvalidKeyException e) {e.printstacktrace ();} catch (Illegalblocksizeexception e) {e.printstacktrace ();} catch ( Badpaddingexception e) {e.printstacktrace (),} catch (Unsupportedencodingexception e) {e.printstacktrace ();} catch ( Invalidalgorithmparameterexception e) {e.printstacktrace ();} return null;} public static String GetKey () {return "[Email protected]!*&y.] X#[;> ";}}

As follows:

Http://pan.baidu.com/s/1kT1bzSV

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.