iOS中的AES256算法

1,537 阅读1分钟

这次只展示代码,算法原理,网上一堆,我就不介绍了。

#import "Helper.h"
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonCrypto.h>
#import "TDWBase64.h"

@implementation Helper
///加密
+ (NSString *)aes256EncrytWithContent:(NSString *)content key:(NSString *)key {
    
    NSData *contentData = [content dataUsingEncoding:NSUTF8StringEncoding];
    char keyptr[kCCKeySizeAES256+1];
    bzero(keyptr, sizeof(keyptr));
    [key getCString:keyptr maxLength:sizeof(keyptr) encoding:NSUTF8StringEncoding];
    NSUInteger datalength = contentData.length;
    size_t bufferSize = datalength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    size_t numBytesEncrypted = 0;
    
    char iv[] = {0x30, 0x31, 0x30, 0x30, 0x31, 0x30, 0x30, 0x31, 0x30, 0x30, 0x31, 0x30, 0x30, 0x31, 0x30, 0x38};
    
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding, keyptr, 32, iv, contentData.bytes, datalength, buffer, bufferSize, &numBytesEncrypted);
    
    if (cryptStatus == kCCSuccess) {
        
        NSData *data = [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
        NSString *result = [TDWBase64 stringByEncodingData:data];
        return result;
        
    } else {
        
        free(buffer);
        return nil;
    }
    
    return @"";
}

///解密
+ (NSString *)aes256DecrytWithContent:(NSString *)content key:(NSString *)key {
    
    NSData *contentData = [TDWBase64 decodeString:content];
    char keyptr[kCCKeySizeAES256+1];
    bzero(keyptr, sizeof(keyptr));
    [key getCString:keyptr maxLength:sizeof(keyptr) encoding:NSUTF8StringEncoding];
    NSUInteger datalength = contentData.length;
    size_t bufferSize = datalength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    size_t numBytesEncrypted = 0;
    
    char iv[] = {0x30, 0x31, 0x30, 0x30, 0x31, 0x30, 0x30, 0x31, 0x30, 0x30, 0x31, 0x30, 0x30, 0x31, 0x30, 0x38};
    
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding, keyptr, 32, iv, contentData.bytes, datalength, buffer, bufferSize, &numBytesEncrypted);
    
    if (cryptStatus == kCCSuccess) {
        
        NSData *data = [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
        NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        return result;
        
    } else {
        
        free(buffer);
        return nil;
    }
    
    return @"";
}

坑点: 1.

NSData *data = [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];

这个会自动释放buffer。 坑点文章:www.jianshu.com/p/706b7fd03…

image.png
image.png

2.Vi偏移量要用byte的形式写。