AES symmetrical encryption decryption iOS

This article deals say the iPhone system comes symmetric encryption and decryption functions;

Symmetric encryption:

i. DES Data Encryption Standard
ii. 3DES DES same, except that the three key operation for a number
iii. AES Advanced password standard
DES Data Encryption Standard is early, AES is Advanced Encryption Standard, or DES and 3DES AES transition to the intermediate transition product;

Under the AES following said:
First, if required AES, then at least three parameters:
1, with the original encrypted text
2, encrypted using Key
3, filled with the vector iv

First, the introduction of encryption header file

//加密库
#import <CommonCrypto/CommonCryptor.h>

Second, the realization AES encryption

//AES 加密
- (NSString *)aesEnc:(NSData *)data key:(NSData *)key iv:(NSData *)iv {
    if ([iv length] != 16) {
        NSLog(@"iv length error!");
        return nil;
    }
    if ([key length] != 16 && [key length] != 24 && [key length] != 32 ) {
        NSLog(@"key length error!");
        return nil;
    }

    size_t bufferSize = [data length] + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);

    size_t encrySize = 0;
    CCCryptorStatus status = CCCrypt(kCCEncrypt,
                                     kCCAlgorithmAES128,
                                     kCCOptionPKCS7Padding,
                                     [key bytes],
                                     [key length],
                                     [iv bytes],
                                     [data bytes],
                                     [data length],
                                     buffer,
                                     bufferSize,
                                     &encrySize);
    if (status!= kCCSuccess) {
        free(buffer);
        return nil;
    }
    NSData *dataResult = [NSData dataWithBytes:buffer length:encrySize];
    NSString *res = [[NSString alloc]initWithData:dataResult encoding:NSUTF8StringEncoding];
    NSLog(@"result-enc-source-:%@",res);
    NSString *result = [dataResult base64EncodedStringWithOptions:0];
    NSLog(@"result--enc-base64-:%@",result);
    free(buffer);
    return result;
}

Third, to achieve AES decryption

//AES 解密
- (NSString *)aesDenc:(NSData *)data key:(NSData *)key iv:(NSData *)iv {
    if ([iv length] != 16) {
        NSLog(@"iv length error!");
        return nil;
    }
    if ([key length] != 16 && [key length] != 24 && [key length] != 32 ) {
        NSLog(@"key length error!");
        return nil;
    }

    size_t bufferSize = [data length] + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);

    size_t encrySize = 0;
    CCCryptorStatus status = CCCrypt(kCCDecrypt,
                                     kCCAlgorithmAES128,
                                     kCCOptionPKCS7Padding,
                                     [key bytes],
                                     [key length],
                                     [iv bytes],
                                     [data bytes],
                                     [data length],
                                     buffer,
                                     bufferSize,
                                     &encrySize);
    if (status!= kCCSuccess) {
        free(buffer);
        return nil;
    }
    NSData *dataResult = [NSData dataWithBytes:buffer length:encrySize];
    NSString *res = [[NSString alloc]initWithData:dataResult encoding:NSUTF8StringEncoding];
    NSLog(@"result-enc-source-:%@",res);
    NSString *result = [dataResult base64EncodedStringWithOptions:0];
    NSLog(@"result--aes-base64-:%@",result);
    free(buffer);

    return result;
}

IV Summary

AES symmetric encryption system call is primarily a function of:

CCCryptorStatus CCCrypt(
    CCOperation op,         /* kCCEncrypt, etc. */
    CCAlgorithm alg,        /* kCCAlgorithmAES128, etc. */
    CCOptions options,      /* kCCOptionPKCS7Padding, etc. */
    const void *key,
    size_t keyLength,
    const void *iv,         /* optional initialization vector */
    const void *dataIn,     /* optional per op and alg */
    size_t dataInLength,
    void *dataOut,          /* data RETURNED here */
    size_t dataOutAvailable,
    size_t *dataOutMoved)
    __OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_2_0);

This function can be seen by a total of 11 function parameters, but these parameters are not trouble
the first parameter is an enumeration type (encrypt | decrypt):

enum {
    kCCEncrypt = 0, 
    kCCDecrypt,     
};
typedef uint32_t CCOperation;

The second parameter: symmetric encryption algorithm (to support a variety of algorithms)

enum {
    kCCAlgorithmAES128 = 0,
    kCCAlgorithmAES = 0,
    kCCAlgorithmDES,
    kCCAlgorithm3DES,       
    kCCAlgorithmCAST,       
    kCCAlgorithmRC4,
    kCCAlgorithmRC2,   
    kCCAlgorithmBlowfish    
};
typedef uint32_t CCAlgorithm;

The third argument: encryption modes (ECB | CBC)

enum {
    /* options for block ciphers */
    kCCOptionPKCS7Padding   = 0x0001,
    kCCOptionECBMode        = 0x0002
    /* stream ciphers currently have no options */
};
typedef uint32_t CCOptions;

Fourth, five parameters: the length of its encryption key (encryption seeds)

//该数据的长度为特定值,根据实际情况选用

enum {
    kCCKeySizeAES128          = 16,
    kCCKeySizeAES192          = 24,
    kCCKeySizeAES256          = 32,
    kCCKeySizeDES             = 8,
    kCCKeySize3DES            = 24,
    kCCKeySizeMinCAST         = 5,
    kCCKeySizeMaxCAST         = 16,
    kCCKeySizeMinRC4          = 1,
    kCCKeySizeMaxRC4          = 512,
    kCCKeySizeMinRC2          = 1,
    kCCKeySizeMaxRC2          = 128,
    kCCKeySizeMinBlowfish     = 8,
    kCCKeySizeMaxBlowfish     = 56,
};

The sixth parameter: Fill vector iv

    @param      iv              Initialization vector, optional. Used for 
                                Cipher Block Chaining (CBC) mode. If present, 
                                must be the same length as the selected 
                                algorithm's block size. If CBC mode is
                                selected (by the absence of any mode bits in 
                                the options flags) and no IV is present, a 
                                NULL (all zeroes) IV will be used. This is 
                                ignored if ECB mode is used or if a stream 
                                cipher algorithm is selected. For sound encryption,
                                always initialize IV with random data.

Seventh, eight parameters: input data

第七个参数传入带加密原文数据;
第八个参数带加密数据长度;

Ninth parameter: the output data storage area

//存储加密或解密后的数据;
void *buffer = malloc(bufferSize);

10th parameter: extension length of the original data +

//dataOutAvailable The size of the dataOut buffer in bytes.
//初始化数据长度
    size_t bufferSize = [data length] + kCCBlockSizeAES128;

Eleventh Parameters: returns the actual length of the data

//最终需要的数据长度
//dataOutMoved    On successful return, the number of bytes
                    written to dataOut. If kCCBufferTooSmall is
                returned as a result of insufficient buffer
                space being provided, the required buffer space
                is returned here. 

So far, all steps have been explained;

Published 172 original articles · won praise 35 · views 390 000 +

Guess you like

Origin blog.csdn.net/u012198553/article/details/78710891