iOS 在OC 中使用 AEC 的 ECB、CTR模式加解密

实用实测过的代码。

 

AEC加解密网上一大把,简单列举一下。

CTR模式,搜索了好多,试用了好几个都是代码不完全参数不对造成无法正常运行加解密。

不同模式引用了不同的系统库路径。

 

调整加解密,修改参数 operation :kCCDecrypt / kCCEncrypt

AEC CTR模式解密

#import <CommonCrypto/CommonCrypto.h>

#import <CommonCrypto/CommonKeyDerivation.h>

#import <Security/Security.h>

+ (NSData *) AESCTRDecryptData:(NSData *)data withKey:(NSData *)key withiv:(NSData *)iv
{
    // Init cryptor
    CCCryptorRef cryptor = NULL;
    
    // Create Cryptor
    CCCryptorStatus createDecrypt = CCCryptorCreateWithMode(kCCDecrypt, // operation
                                                            kCCModeCTR, // mode CTR
                                                            kCCAlgorithmAES, // Algorithm
                                                            ccPKCS7Padding, // padding
                                                            iv.bytes, // can be NULL, because null is full of zeros
                                                            key.bytes, // key
                                                            key.length, // keylength
                                                            NULL, //const void *tweak
                                                            0, //size_t tweakLength,
                                                            0, //int numRounds,
                                                            kCCModeOptionCTR_BE, //CCModeOptions options,
                                                            &cryptor); //CCCryptorRef *cryptorRef
    
    
    if (createDecrypt == kCCSuccess)
    {
        // Alloc Data Out
        NSMutableData *cipherDataDecrypt = [NSMutableData dataWithLength:data.length + kCCBlockSizeAES128];
        
        //alloc number of bytes written to data Out
        size_t outLengthDecrypt;
        
        //Update Cryptor
        CCCryptorStatus updateDecrypt = CCCryptorUpdate(cryptor,
                                                        data.bytes, //const void *dataIn,
                                                        data.length,  //size_t dataInLength,
                                                        cipherDataDecrypt.mutableBytes, //void *dataOut,
                                                        cipherDataDecrypt.length, // size_t dataOutAvailable,
                                                        &outLengthDecrypt); // size_t *dataOutMoved)
        
        if (updateDecrypt == kCCSuccess)
        {
            //Cut Data Out with nedded length
            cipherDataDecrypt.length = outLengthDecrypt;
            
            // Data to String
//            NSString* cipherFinalDecrypt = [[NSString alloc] initWithData:cipherDataDecrypt encoding:NSUTF8StringEncoding];
            
            //Final Cryptor
            CCCryptorStatus final = CCCryptorFinal(cryptor, //CCCryptorRef cryptorRef,
                                                   cipherDataDecrypt.mutableBytes, //void *dataOut,
                                                   cipherDataDecrypt.length, // size_t dataOutAvailable,
                                                   &outLengthDecrypt); // size_t *dataOutMoved)
            
            if (final == kCCSuccess)
            {
                //Release Cryptor
                //CCCryptorStatus release =
                CCCryptorRelease(cryptor); //CCCryptorRef cryptorRef
            }
            
            return cipherDataDecrypt;
        }
    }
    else
    {
        //error
        NSLog(@"AESCTRDecryptData is error");
    }
    
    return nil;
}

 

 

AEC ECB模式加密


//加密算法


#import <CommonCrypto/CommonDigest.h>


#import <CommonCrypto/CommonCryptor.h>



/*
*  加密:先采用AES/ECB/PKCS5Padding,再采用base64-url-safe 编码  */ + (NSString *)encryptAES128WithContent:(NSString *)content key:(NSString *)key{ NSData *contentData = [content dataUsingEncoding:NSUTF8StringEncoding]; NSUInteger dataLength = contentData.length; // 为结束符'\0' +1 char keyPtr[kCCKeySizeAES128+1]; memset(keyPtr,0,sizeof(keyPtr)); [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding]; // 密文长度 <= 明文长度 + BlockSize size_t encryptSize = dataLength + kCCBlockSizeAES128; void * encryptedBytes = malloc(encryptSize); size_t actualOutSize = 0; CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding|kCCOptionECBMode, //CBC -> PKCS7Padding,ECB -> kCCOptionPKCS7Padding|kCCOptionECBMode keyPtr, kCCKeySizeAES128, NULL, contentData.bytes, dataLength, encryptedBytes, encryptSize, &actualOutSize); if(cryptStatus ==kCCSuccess) { NSData*data = [NSData dataWithBytesNoCopy:encryptedBytes length:actualOutSize]; NSString *base64Str = [data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed]; NSMutableString *mutBase64Str = [NSMutableString stringWithString:base64Str]; mutBase64Str = (NSMutableString * )[base64Str stringByReplacingOccurrencesOfString:@"+" withString:@"-"]; mutBase64Str = (NSMutableString * )[base64Str stringByReplacingOccurrencesOfString:@"/" withString:@"_"]; mutBase64Str = (NSMutableString * )[base64Str stringByReplacingOccurrencesOfString:@"=" withString:@""]; return mutBase64Str; } free(encryptedBytes); return nil; }

 

posted @ 2024-10-12 14:16  徐家汇  阅读(38)  评论(0编辑  收藏  举报