IOS加密 AES 256算法(EncryptAndDecrypt.h)
[cpp]////EncryptAndDecrypt.h#import <Foundation/Foundation.h>@class NSString;@inte易做图ce NSData (Encryption)- (NSData *)AES256EncryptWithKey:(NSData *)key; //加密- (NSData *)AES256DecryptWithKey:(NSData *)key; //解密- (NSString *)newStringInBase64FromData; //追加64编码+ (NSString*)base64encode:(NSString*)str; //同上64编码+(NSData*)stringToByte:(NSString*)string;+(NSString*)byteToString:(NSData*)data;@end[cpp]///EncryptAndDecrypt.m#import "EncryptAndDecrypt.h"#import <CommonCrypto/CommonCrypto.h>static char base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";@implementation NSData (Encryption)- (NSData *)AES256EncryptWithKey:(NSData *)key //加密{//AES256加密,密钥应该是32位的const void * keyPtr2 = [key bytes];char (*keyPtr)[32] = keyPtr2;//对于块加密算法,输出大小总是等于或小于输入大小加上一个块的大小//所以在下边需要再加上一个块的大小NSUInteger dataLength = [self length];size_t bufferSize = dataLength + kCCBlockSizeAES128;void *buffer = malloc(bufferSize);size_t numBytesEncrypted = 0;CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128,kCCOptionPKCS7Padding/*这里就是刚才说到的PKCS7Padding填充了*/| kCCOptionECBMode,[key bytes], kCCKeySizeAES256,NULL,/* 初始化向量(可选) */[self bytes], dataLength,/*输入*/buffer, bufferSize,/* 输出 */&numBytesEncrypted);if (cryptStatus == kCCSuccess) {return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];}free(buffer);//释放bufferreturn nil;}- (NSData *)AES256DecryptWithKey:(NSData *)key //解密{//同理,解密中,密钥也是32位的const void * keyPtr2 = [key bytes];char (*keyPtr)[32] = keyPtr2;//对于块加密算法,输出大小总是等于或小于输入大小加上一个块的大小//所以在下边需要再加上一个块的大小NSUInteger dataLength = [self length];size_t bufferSize = dataLength + kCCBlockSizeAES128;void *buffer = malloc(bufferSize);size_t numBytesDecrypted = 0;CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128,kCCOptionPKCS7Padding/*这里就是刚才说到的PKCS7Padding填充了*/| kCCOptionECBMode,keyPtr, kCCKeySizeAES256,NULL,/* 初始化向量(可选) */[self bytes], dataLength,/* 输入 */ 补充:综合编程 , 安全编程 ,
上一个:Android软件安全开发实践
下一个:jsp url传参加密