Tuesday, 3 September 2013

iOS decrypt failed : kCCDecodeError -4304

iOS decrypt failed : kCCDecodeError -4304

I try to use DES to encrypt data as following:
+(BOOL) encryptDESFile:(NSString *)input_path
output_path:(NSString*)output_path
{
BOOL succeed=NO;
NSData *textData = [NSData dataWithContentsOfFile:input_path];
if (textData) {
NSUInteger dataLength = [textData length];
NSMutableData* cipherData = [NSMutableData dataWithLength:dataLength
+kCCBlockSizeDES];
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES,
kCCOptionPKCS7Padding,
[key UTF8String], kCCKeySizeDES,
iv,
[textData bytes] , dataLength,
cipherData.mutableBytes,
[cipherData length],
&numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
NSData *data = [NSData dataWithData:cipherData];
succeed=YES;
NSLog(@"en succeed!");
[data writeToFile:output_path atomically:YES];
}else{
NSLog(@"en failed!");
}
}
return succeed;
}
and decrypt data as following:
+(BOOL) decryptDESFile:(NSString *)input_path
output_path:(NSString*)output_path
{
BOOL succeed=NO;
NSString *cleartext = nil;
NSData *textData = [NSData dataWithContentsOfFile:input_path];
NSUInteger dataLength = [textData length];
NSMutableData* plainData = [NSMutableData dataWithLength:dataLength];
size_t numBytesDecrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmDES,
kCCOptionPKCS7Padding,
[key UTF8String], kCCKeySizeDES,
iv,
[textData bytes] , dataLength,
plainData.mutableBytes, [plainData
length],
&numBytesDecrypted);
if (cryptStatus == kCCSuccess) {
NSLog(@"de succeed!");
NSData *data = [NSData dataWithData:plainData];
cleartext = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
[data writeToFile:output_path atomically:YES];
succeed=YES;
}else{
NSLog(@"de failed! code=%d",cryptStatus);
}
return succeed;
}
When I encrypt and decrypt the sqlite database file it work properly. But
unfortunately when I try to decrypt the encrypted image or zip file from
above encrypt function it will return kCCDecodeError.
I have try to move the encrypted image or zip then use java code to
decrypt it can decrypt successfully. Could any one tell me why?

No comments:

Post a Comment