返回可变大小的字节数组并释放内存

Returning variable size byte array and free the memory

我正在编写代理 .c 文件以使用 OpenSSL 库进行 RSA 加密。可用于 iPhone。由于 Objective C 中的调用 class 不知道加密数据的大小,因此容器未初始化,我想保持动态。 char 数组和接收到的大小通过引用调用。它的内存在 ssl_encrypt_public_rsa 中动态分配,调用者必须释放它。我不喜欢将责任交给调用者的想法。

您是否可以推荐任何其他可靠的方法?

openssl .c 中的实现(稍后编译为静态 lib .a 文件)

// calling function must free cipherText memory
void ssl_encrypt_public_rsa(RSA *rsaKey, int plainLength, unsigned char *plainText,
                              int *cipherLength, unsigned char **cipherText)
{
    int enc_len = RSA_size(rsaKey);
    unsigned char *enc_bytes = malloc(enc_len * sizeof(char));
    int encSize = RSA_public_encrypt(plainLength, plainText, enc_bytes, rsaKey, RSA_PKCS1_PADDING);
    *cipherText = enc_bytes;
    *cipherLength = encSize;
}

void ssl_encrypt_mips(int plainLength, unsigned char *plainText,
                        int *cipherLength, unsigned char **cipherText)
{
// rsaKeyMips is defined and initialized earlier
    ssl_encrypt_public_rsa(rsaKeyMips, plainLength, plainText, cipherLength, cipherText);
}

调用函数Objective C.m文件

-(NSData *) encryptMips:(NSData *)inData
{
    int encSize = 0;
    unsigned char *cipherBytes;
    ssl_encrypt_mips((int)inData.length, (unsigned char *)inData.bytes, &encSize, &cipherBytes);
    if (encSize == -1 ) return nil;
    NSData * d = [NSData dataWithBytes:cipherBytes length:encSize];
    free(cipherBytes);
    return d;
}

不清楚你在问什么,因为你已经将 C 调用包装在一个包装器中,该包装器负责 free()。如果您希望从包装器中删除 free(),并意外地避免复制,您可以更改您的:

NSData *d = [NSData dataWithBytes:cipherBytes length:encSize];
free(cipherBytes);

至:

NSData *d = [NSData dataWithBytesNoCopy:cipherBytes length:encSize free:YES]; 

它将 malloc() 块的所有权交给 NSData 实例,稍后将在不再需要时 free() 它。

HTH