首页 > 系统 > iOS > 正文

iOS系统方法进行AES对称加密

2019-11-09 14:02:29
字体:
来源:转载
供稿:网友

废话不多说,直接上代码:

头文件:

[objc] view plain copy PRint?在CODE上查看代码片#import <Foundation/Foundation.h>    @class NSString;    @interface NSData (Encryption)    - (NSData *)AES256ParmEncryptWithKey:(NSString *)key;   //加密  - (NSData *)AES256ParmDecryptWithKey:(NSString *)key;   //解密    @end  

.m实现文件:

[objc] view%20plain copy print?派生到我的代码片#import "Encryption.h"  #import <CommonCrypto/CommonCryptor.h>    @implementation NSData (Encryption)    - (NSData *)AES256ParmEncryptWithKey:(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;      voidvoid *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 *)AES256ParmDecryptWithKey:(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;      voidvoid *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;  }  
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表