AES256在目标C中加密以匹配php rijndael 256 ECB MODE

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;
}

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.