skavinvarnan / Cross-Platform-AES

Simple cross-platform encryption and decryption using AES
MIT License
142 stars 69 forks source link

Decryption not working properly for DATA #26

Closed tselvakumar30 closed 4 years ago

tselvakumar30 commented 5 years ago

Hi I have used the following method to encrypt

And Decrypt it using the following method,

char keyPointer[kCCKeySizeAES256+2], ivPointer[kCCBlockSizeAES128+2]; BOOL patchNeeded;

patchNeeded = ([key length] > kCCKeySizeAES256+1);
if(patchNeeded)
{
    NSLog(@"Key length is longer %lu", (unsigned long)[[[StringEncryption alloc] md5:key] length]);
    key = [key substringToIndex:kCCKeySizeAES256];
}

[key getCString:keyPointer maxLength:sizeof(keyPointer) encoding:NSUTF8StringEncoding];
[iv getCString:ivPointer maxLength:sizeof(ivPointer) encoding:NSUTF8StringEncoding];

if (patchNeeded) {
    keyPointer[0] = '\0';
}

NSUInteger dataLength = [encryptedText length];

size_t buffSize = dataLength + kCCBlockSizeAES128;

void *buff = malloc(buffSize);

size_t numBytesEncrypted = 0;

CCCryptorStatus status = CCCrypt(kCCDecrypt,
                                 kCCAlgorithmAES128,
                                 kCCOptionPKCS7Padding,
                                 keyPointer, kCCKeySizeAES256,
                                 ivPointer,
                                 [encryptedText bytes], [encryptedText length], //input
                                 buff, buffSize,//output
                                 &numBytesEncrypted);
if (status == kCCSuccess) {
    return [NSData dataWithBytesNoCopy:buff length:numBytesEncrypted];
}

free(buff);
return nil;

But the decryption is not working. Please help me resolve this issue.

angelo-RSVP commented 5 years ago

Same. The fix for #29 worked but when I'm sending data from iOS 13 (fixed) to iOS 11 (pre-fixed) version, iOS 11 (the pre-fixed version) crashes.

Breakpointing, I can see that status == kCCSuccess, but the returned data is (null)

angelo-RSVP commented 5 years ago

I managed to fix it by doing the alternative approach here.

use this function and replace NSString *hash=[out debugDescription]; with NSString *hash = [self hex: out];

 -(NSString*)hex:(NSData*)data{
      NSMutableData *result = [NSMutableData dataWithLength:2*data.length];
      unsigned const char* src = data.bytes;
      unsigned char* dst = result.mutableBytes;
      unsigned char t0, t1;

      for (int i = 0; i < data.length; i ++ ) {
           t0 = src[i] >> 4;
           t1 = src[i] & 0x0F;

           dst[i*2] = 48 + t0 + (t0 / 10) * 39;
           dst[i*2+1] = 48 + t1 + (t1 / 10) * 39;
      }

      return [[NSString alloc] initWithData:result encoding:NSASCIIStringEncoding];
 }

I'm still on testing phase but the results so far looks positive.

skavinvarnan commented 4 years ago

This issue has been fixed