AES 128 用CBC 加密

2019-08-03  本文已影响0人  神一样的队友

整了很长时间才好,网上参考材料很少

参考 :

//Ase加密

https://www.jianshu.com/p/9a348bdf9ce1

//十六进制字符串与NSData的转化

https://www.jianshu.com/p/2e68a91d4681

导入框架 #import   <CommonCrypto/CommonCryptor.h>


最近在完成一个需求时,遇到了NSData类型转换为十六进制的字符串这个需求的函数,

.h文件

//加密

- (NSData*)AES128EncryptWithKey:(NSString*)key iv:(NSString*)iv;

//解密

- (NSData*)AES128DecryptWithKey:(NSString*)key iv:(NSString*)iv;

.m文件

//://加密

- (NSData*)AES128EncryptWithKey:(NSString*)key iv:(NSString*)iv

{

    return [self AES128operation:kCCEncrypt key:key iv:iv];

}

//解密

- (NSData*)AES128DecryptWithKey:(NSString*)key iv:(NSString*)iv

{

    return [self AES128operation:kCCDecrypt key:key iv:iv];

}

- (NSData*)AES128operation:(CCOperation)operation key:(NSString*)key iv:(NSString*)iv

{

    charkeyPtr[kCCKeySizeAES128+1];

    bzero(keyPtr,sizeof(keyPtr));

    [keygetCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];

    // IV

    char ivPtr[kCCBlockSizeAES128 + 1];

    bzero(ivPtr,sizeof(ivPtr));

    [ivgetCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];

    size_tbufferSize = [selflength] +kCCBlockSizeAES128;

    void*buffer =malloc(bufferSize);

    size_tnumBytesEncrypted =0;

    CCCryptorStatus cryptorStatus = CCCrypt(operation, kCCAlgorithmAES128, kCCOptionPKCS7Padding,

                                            keyPtr,kCCKeySizeAES128,

                                            ivPtr,

                                            [selfbytes], [selflength],

                                            buffer, bufferSize,

                                            &numBytesEncrypted);

    if(cryptorStatus ==kCCSuccess){

        NSLog(@"Success");

        return[NSDatadataWithBytesNoCopy:bufferlength:numBytesEncrypted];

    }else{

        NSLog(@"Error");

    }

    free(buffer);

    return nil;

}

十六进制字符串与NSData的转化

- (NSString*)convertDataToHexStr:(NSData*)data {

if(!data || [data length] ==0) {

return@"";

 }

NSMutableString*string = [[NSMutableStringalloc] initWithCapacity:[data length]];

 [data enumerateByteRangesUsingBlock:^(constvoid*bytes,NSRangebyteRange,BOOL*stop) {

unsignedchar*dataBytes = (unsignedchar*)bytes;f

or(NSIntegeri =0; i < byteRange.length; i++) {

NSString*hexStr = [NSStringstringWithFormat:@"%x", (dataBytes[i]) &0xff];

if([hexStr length] ==2) { 

 [string appendString:hexStr]; 

 }else{ 

 [string appendFormat:@"0%@", hexStr];

 }

 } 

 }

];

return string;}

上一篇下一篇

猜你喜欢

热点阅读