Reputation:
I'm trying to decrypt a file, but this method fails on devices with A5 chip. (signal SIGABRT) New devices work fine.
Why is this happening?
- (void) decryptFile{
unsigned char bookhashChar[kCCKeySizeAES128+1];
NSData *stringBytes = [self.bookhash dataUsingEncoding: NSUTF8StringEncoding]; /* or some other encoding */
if (CC_SHA1([stringBytes bytes], (CC_LONG)[self.bookhash length], bookhashChar)) {
/* SHA-1 hash has been calculated and stored in 'digest'. */
}
unsigned char idBookChar[CC_SHA1_DIGEST_LENGTH];
NSData *stringBytesForID = [self.book_id dataUsingEncoding: NSUTF8StringEncoding]; /* or some other encoding */
if (CC_SHA1([stringBytesForID bytes], (CC_LONG)[self.book_id length], idBookChar)) {
/* SHA-1 hash has been calculated and stored in 'digest'. */
}
char resultKey[kCCKeySizeAES128+1];
for (int i = 0; i< kCCKeySizeAES128+1; i++) {
resultKey[i] = (Byte)(bookhashChar[i] ^ idBookChar[i]);
}
char keyPtr[kCCKeySizeAES128 + 1];
bzero(keyPtr, sizeof(keyPtr));
char ivPtr[kCCKeySizeAES128 + 1];
bzero(ivPtr, sizeof(ivPtr));
char ivv[17] = { 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x02, 0x03, 0x03, 0x00, 0x06, 0x03, 0x07, 0x00, 0x00, 0x01 };
//[iv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];
//[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [self.downloadedData length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesDecrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,resultKey, kCCKeySizeAES128,
ivv /* initialization vector (optional) */,
[self.downloadedData bytes], dataLength, /* input */
buffer, bufferSize, /* output */
&numBytesDecrypted);
if (cryptStatus == kCCSuccess) {
self.downloadedData = [[NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted] copy];
}
Upvotes: 1
Views: 100
Reputation: 112873
One error is using kCCKeySizeAES128+1
for the returned size of CCSHA1
. Don't mix the value types, AES with SHA1.
The digest size of CCSHA1
is CC_SHA1_DIGEST_LENGTH, 20 bytes.
The size of kCCKeySizeAES128
is 16 bytes.
The buffer for CCSHA1
is to small.
Sooner or later there will be an overwrite of 3 bytes and incorrect operation (possible a crash) will occur.
You may only need kCCKeySizeAES128
bytes but the buffer must be large enough for CCSHA1
and then use the bytes needed.
Upvotes: 1