ios 中aes能对汉字加密吗

 我来答
出家人词悲
高赞答主

推荐于2016-04-23 · 大脑停止不了思考
知道大有可为答主
回答量:1.4万
采纳率:12%
帮助的人:3990万
展开全部
// 开发中用到AES128加密、解密
#import <Foundation/Foundation.h>
#import <CommonCrypto/CommonCryptor.h>
@interface NSData (AES)
- (NSData *)AES128Operation:(CCOperation)operation key:(NSString *)key iv:(NSString *)iv;
- (NSData *)AES128EncryptWithKey:(NSString *)key iv:(NSString *)iv;
- (NSData *)AES128DecryptWithKey:(NSString *)key iv:(NSString *)iv;
@end

@implementation NSData (AES)
- (NSData *)AES128Operation:(CCOperation)operation key:(NSString *)key iv:(NSString *)iv
{
char keyPtr[kCCKeySizeAES128 + 1];
memset(keyPtr, 0, sizeof(keyPtr));
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];

char ivPtr[kCCBlockSizeAES128 + 1];
memset(ivPtr, 0, sizeof(ivPtr));
[iv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];

NSUInteger dataLength = [self length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);

size_t numBytesCrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(operation,
kCCAlgorithmAES128,
kCCOptionPKCS7Padding,
keyPtr,
kCCBlockSizeAES128,
ivPtr,
[self bytes],
dataLength,
buffer,
bufferSize,
&numBytesCrypted);
if (cryptStatus == kCCSuccess) {
return [NSData dataWithBytesNoCopy:buffer length:numBytesCrypted];
}
free(buffer);
return nil;
}

- (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];
}
@end

int main(int argc, char const* argv[])
{
NSAutoreleasePool* pool;
pool = [[NSAutoreleasePool alloc] init];

NSString *key = [NSString stringWithCString:argv[1] encoding:NSUTF8StringEncoding];
NSString *iv = [NSString stringWithCString:argv[2] encoding:NSUTF8StringEncoding];
NSString *data_str = [NSString stringWithCString:argv[3] encoding:NSUTF8StringEncoding];
NSData *data = [data_str dataUsingEncoding:NSUTF8StringEncoding];

NSData *en_data = [data AES128EncryptWithKey:key iv:iv];
NSData *de_data = [en_data AES128DecryptWithKey:key iv:iv];

NSString *de_str = [[[NSString alloc] initWithData:de_data
encoding:NSUTF8StringEncoding] autorelease];

NSLog(@"%@", en_data);
NSLog(@"%@", de_str);

[pool drain];
return 0;
}
本回答被提问者和网友采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式