forked from noahsmartin/AES128
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NSData+AES128.m
88 lines (81 loc) · 3.05 KB
/
NSData+AES128.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// Created by Noah Martin
// http://noahmart.in
#import "NSData+AES128.h"
#import <CommonCrypto/CommonCryptor.h>
@implementation NSData (AES128)
-(NSData*)AES128DecryptWithKey:(NSString*)key
{
NSMutableData *mutableData = [NSMutableData dataWithData:self];
char keyPtr[kCCKeySizeAES128+1];
bzero(keyPtr, sizeof(keyPtr));
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [mutableData length];
int excess = dataLength % 16;
if(excess) {
int padding = 16 - excess;
[mutableData increaseLengthBy:padding];
dataLength += padding;
}
NSMutableData *returnData = [[NSMutableData alloc] init];
int bufferSize = 16;
int start = 0;
int i = 0;
while(start < dataLength)
{
i++;
void *buffer = malloc(bufferSize);
size_t numBytesDecrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, 0,
keyPtr, kCCKeySizeAES128,
NULL,
[[mutableData subdataWithRange:NSMakeRange(start, bufferSize)] bytes], bufferSize,
buffer, bufferSize,
&numBytesDecrypted);
if (cryptStatus == kCCSuccess) {
NSData *piece = [NSData dataWithBytes:buffer length:numBytesDecrypted];
[returnData appendData:piece];
}
free(buffer);
start += bufferSize;
}
return returnData;
}
-(NSData*)AES128EncryptWithKey:(NSString *)key
{
NSMutableData *mutableData = [NSMutableData dataWithData:self];
char keyPtr[kCCKeySizeAES128+1];
bzero(keyPtr, sizeof(keyPtr));
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [mutableData length];
int excess = dataLength % 16;
if(excess) {
int padding = 16 - excess;
[mutableData increaseLengthBy:padding];
dataLength += padding;
}
NSMutableData *returnData = [[NSMutableData alloc] init];
int bufferSize = 16;
int start = 0;
int i = 0;
while(start < dataLength)
{
i++;
void *buffer = malloc(bufferSize);
size_t numBytesDecrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, 0,
keyPtr, kCCKeySizeAES128,
NULL,
[[mutableData subdataWithRange:NSMakeRange(start, bufferSize)] bytes], bufferSize,
buffer, bufferSize,
&numBytesDecrypted);
if (cryptStatus == kCCSuccess) {
NSData *piece = [NSData dataWithBytes:buffer length:numBytesDecrypted];
[returnData appendData:piece];
}
free(buffer);
start += bufferSize;
}
return returnData;
return nil;
}
@end