iPhone开发技巧之数据篇(2)— iPhone程序中的加密处理
CCCrypt
在Objective-C语言中,加密时常用到CCCrypt(3cc) Mac OS X Manual Pagehttp://developer.apple.com/library/mac/#DOCUMENTATION/Darwin/Reference/ManPages/man3/CCCrypt.3cc.html 。下面的代码使用 CCCrypt() ,给 NSData 类增加了 AES256EncryptWithKey, AES256DecryptWithKey 方法。
1. #import <CommonCrypto/CommonCryptor.h>
2.
3. @implementation NSData (Additions)
4.
5. @class NSString;
6.
7. - (NSData *)AES256EncryptWithKey:(NSString *)key {
8. char keyPtr[kCCKeySizeAES256+1];
9. bzero(keyPtr, sizeof(keyPtr));
10.
11. [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
12.
13. NSUInteger dataLength = [self length];
14.
15. size_t bufferSize = dataLength + kCCBlockSizeAES128;
16. void *buffer = malloc(bufferSize);
17.
18. size_t numBytesEncrypted = 0;
19. CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128,
20. kCCOptionPKCS7Padding | kCCOptionECBMode,
21. keyPtr, kCCBlockSizeAES128,
22. NULL,
23. [self bytes], dataLength,
24. buffer, bufferSize,
25. &numBytesEncrypted);
26. if (cryptStatus == kCCSuccess) {
27. return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
28. }
29. free(buffer);
30. return nil;
31. }
32.
33. - (NSData *)AES256DecryptWithKey:(NSString *)key {
34. char keyPtr[kCCKeySizeAES256+1];
35. bzero(keyPtr, sizeof(keyPtr));
36.
37. [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
38.
39. NSUInteger dataLength = [self length];
40.
41. size_t bufferSize = dataLength + kCCBlockSizeAES128;
42. void *buffer = malloc(bufferSize);
43.
44. size_t numBytesDecrypted = 0;
45. CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128,
46. kCCOptionPKCS7Padding | kCCOptionECBMode,
47. keyPtr, kCCBlockSizeAES128,
48. NULL,
49. [self bytes], dataLength,
50.  
补充:移动开发 , IOS ,