1

I'm trying to encrypt a json in AES256 in objective C to send to one server and php decrypt it using the following line:

MCRYPT_DECRYPT (MCRYPT_RIJNDAEL_256, $ key, base64_decode ($ ha), MCRYPT_MODE_ECB, NULL));

took several days searching and testing and I have not gotten results. The code I'm using is this:

- (NSString *)AES256EncryptData:(NSData *) datos {

    //NSData * datos = [json dataUsingEncoding:NSUTF8StringEncoding];

    UIApplication *aplicacion = [UIApplication sharedApplication];
    AppDelegate *delegate = (AppDelegate *) aplicacion.delegate;

    char keyPtr[kCCKeySizeAES256+1];
    bzero(keyPtr, sizeof(keyPtr));
    [delegate.appKey getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding ];

    NSUInteger dataLength = [datos length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);


    size_t numBytesEncrypted;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
                                          kCCAlgorithmAES128,
                                          kCCOptionECBMode + kCCOptionPKCS7Padding,
                                          keyPtr,
                                          kCCKeySizeAES256,
                                          NULL,
                                          [datos bytes],
                                          [datos length],
                                          buffer,
                                          bufferSize,
                                          &numBytesEncrypted);


    if (cryptStatus == kCCSuccess) {
        NSData *returnData  = [[NSData alloc] initWithBytes:buffer length:numBytesEncrypted];
        return [returnData base64EncodedStringWithOptions:0];
    }

    free(buffer);
    return nil;
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
  • Yes, the key is 32 bytes length. I've change the key type but the result is the same. Any idea to set the padding? Averything that I've tested is wrong and the result is NULL – Alberto Gomes Oct 06 '14 at 17:15
  • I have found that I can decrypt the result in PHP with Rijndael_128 not Rijndael_256. – Alberto Gomes Oct 07 '14 at 07:22

1 Answers1

0

You can try forever given the encryption algorithm you are using. You are currently using MCRYPT_RIJNDAEL_256, which is the Rijndael block cipher with 256 block size. You should be using MCRYPT_RIJNDAEL_128 (otherwise known as AES), and then perform the PKCS#7 unpadding yourself.

You should indeed supply exactly the right amount of key bytes as well, which should be either 16, 24 or 32 bytes for AES. And the key bytes obviously must match the ones you are using in your C# code.


If you cannot change the server code you should make / compile mcrypt for IOS and implement the same functions for that particular API. At least it will be compatible. Unfortunately it seems you will have to do the porting yourself.

Community
  • 1
  • 1
Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263