• [iOS]AES加密在iOS上面的实现


    Encryption.h文件

     

     

    #import <Foundation/Foundation.h>
     
    @class NSString;
     
    @interface NSData (Encryption)
     
    - (NSData *)AES256EncryptWithKey:(NSString *)key;   //加密
    - (NSData *)AES256DecryptWithKey:(NSString *)key;   //解密
    - (NSString *)newStringInBase64FromData;            //追加64编码
    + (NSString*)base64encode:(NSString*)str;           //同上64编码
     
    @end


     

    ------------------------------------------------------------------------------------------------

     

    Encryption.m文件

     

    #import "Encryption.h"
    #import <CommonCrypto/CommonCryptor.h>
     
     
    static char base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
     
    @implementation NSData (Encryption)
     
    - (NSData *)AES256EncryptWithKey:(NSString *)key   //加密
    {
        char keyPtr[kCCKeySizeAES256+1];
        bzero(keyPtr, sizeof(keyPtr));
        [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
        NSUInteger dataLength = [self length];
        size_t bufferSize = dataLength + kCCBlockSizeAES128;
        void *buffer = malloc(bufferSize);
        size_t numBytesEncrypted = 0;
        CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128,
                                              kCCOptionPKCS7Padding | kCCOptionECBMode,
                                              keyPtr, kCCBlockSizeAES128,
                                              NULL,
                                              [self bytes], dataLength,
                                              buffer, bufferSize,
                                              &numBytesEncrypted);
        if (cryptStatus == kCCSuccess) {
            return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
        }
        free(buffer);
        return nil;
    }
     
     
    - (NSData *)AES256DecryptWithKey:(NSString *)key   //解密
    {
        char keyPtr[kCCKeySizeAES256+1];
        bzero(keyPtr, sizeof(keyPtr));
        [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
        NSUInteger dataLength = [self length];
        size_t bufferSize = dataLength + kCCBlockSizeAES128;
        void *buffer = malloc(bufferSize);
        size_t numBytesDecrypted = 0;
        CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128,
                                              kCCOptionPKCS7Padding | kCCOptionECBMode,
                                              keyPtr, kCCBlockSizeAES128,
                                              NULL,
                                              [self bytes], dataLength,
                                              buffer, bufferSize,
                                              &numBytesDecrypted);
        if (cryptStatus == kCCSuccess) {
            return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
        }
        free(buffer);
        return nil;
    }
     
     
    - (NSString *)newStringInBase64FromData            //追加64编码
    {
        NSMutableString *dest = [[NSMutableString alloc] initWithString:@""];
        unsigned char * working = (unsigned char *)[self bytes];
        int srcLen = [self length];
        for (int i=0; i<srcLen; i += 3) {
            for (int nib=0; nib<4; nib++) {
                int byt = (nib == 0)?0:nib-1;
                int ix = (nib+1)*2;
                if (i+byt >= srcLen) break;
                unsigned char curr = ((working[i+byt] << (8-ix)) & 0x3F);
                if (i+nib < srcLen) curr |= ((working[i+nib] >> ix) & 0x3F);
                [dest appendFormat:@"%c", base64[curr]];
            }
        }
        return dest;
    }
     
    + (NSString*)base64encode:(NSString*)str
    {
        if ([str length] == 0)
            return @"";
        const char *source = [str UTF8String];
        int strlength  = strlen(source);
        char *characters = malloc(((strlength + 2) / 3) * 4);
        if (characters == NULL)
            return nil;
        NSUInteger length = 0;
        NSUInteger i = 0;
        while (i < strlength) {
            char buffer[3] = {0,0,0};
            short bufferLength = 0;
            while (bufferLength < 3 && i < strlength)
                buffer[bufferLength++] = source[i++];
            characters[length++] = base64[(buffer[0] & 0xFC) >> 2];
            characters[length++] = base64[((buffer[0] & 0x03) << 4) | ((buffer[1] & 0xF0) >> 4)];
            if (bufferLength > 1)
                characters[length++] = base64[((buffer[1] & 0x0F) << 2) | ((buffer[2] & 0xC0) >> 6)];
            else characters[length++] = '=';
            if (bufferLength > 2)
                characters[length++] = base64[buffer[2] & 0x3F];
            else characters[length++] = '=';
        }
        NSString *g = [[[NSString alloc] initWithBytesNoCopy:characters length:lengthencoding:NSASCIIStringEncoding freeWhenDone:YES] autorelease];
        return g;
    }
     
     
    @end
     
    ------------------------------------------------------------------------------------------------
     
    测试代码
     
     
    #import "Encryption.h"
     
     
     
     
        NSString *key = @"my password";
        NSString *secret = @"text to encrypt";
        //加密
        NSData *plain = [secret dataUsingEncoding:NSUTF8StringEncoding];
        NSData *cipher = [plain AES256EncryptWithKey:key];
        NSLog(@"%@",[[cipher newStringInBase64FromData] autorelease]);
        printf("%s\n", [[cipher description] UTF8String]);
        NSLog(@"%@", [[[NSString alloc] initWithData:cipher encoding:NSUTF8StringEncoding] autorelease]);//打印出null,这是因为没有解密。
        //解密
        plain = [cipher AES256DecryptWithKey:key];
        printf("%s\n", [[plain description] UTF8String]);
        NSLog(@"%@", [[[NSString alloc] initWithData:plain encoding:NSUTF8StringEncoding] autorelease]);
        //打印出secret的内容,用密码解密过了。如果使用错误的密码,则打印null


  • 相关阅读:
    什么时候用resultMap,什么时候用resultType?
    Cannot create PoolableConnectionFactory解决思路
    去除list集合中重复项的几种方法-转载
    ORA-02298 定位问题
    命令行退出MySQL和登录MySQL
    CX4-480服务器数据恢复过程(服务器数据恢复通用方法)
    也谈腾讯云的静默损坏
    raid5阵列两块硬盘离线怎么解决
    服务器卷删除初检报告/数据恢复成功率分析
    服务器两块硬盘离线如何恢复数据
  • 原文地址:https://www.cnblogs.com/iapp/p/3631891.html
Copyright © 2020-2023  润新知