aes oc java_AES加密(oc实现)

AES加密(oc实现)

NSData+Encryption.h 文件:

#import

#import

@interface NSData(Encryption)

- (NSData *)AES256EncryptWithKey:(NSString *)key; //加密

- (NSData *)AES256DecryptWithKey:(NSString *)key; //解密

@end

NSData+Encryption.m文件:

#import "NSData+Encryption.h"

@implementation NSData (Encryption)

//这里AES在iOS加过密以后以nsdata的形式存下来,如果想以nsstring形式存储,那么对nsdata进行base64位编码。

- (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;

}

@end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值