문제

Hi guys I needed simple RSA Encryption Decryption. I tried the code examples on Apple developer guide, it works perfectly for small amount of text but the example code doesn't cater for situations of large encrypted data.

Take note of the comment that it is suggesting us to "split the data up into blocks equal to plainBufferSize":

    - (NSData*)decryptedDataFromData:(NSData*)data usingKey:(SecKeyRef)key
    {
        OSStatus status = noErr;

        size_t cipherBufferSize = [data length];
        uint8_t *cipherBuffer = (uint8_t *)[data bytes];

        size_t plainBufferSize;
        uint8_t *plainBuffer;

        //  Allocate the buffer
        plainBufferSize = SecKeyGetBlockSize(key);
        plainBuffer = malloc(plainBufferSize);

        if (plainBufferSize < cipherBufferSize) {
            // Ordinarily, you would split the data up into blocks
            // equal to plainBufferSize, with the last block being
            // shorter. For simplicity, this example assumes that
            // the data is short enough to fit.
            printf("Could not decrypt.  Packet too large.\n");
            return nil;
        }

        //  Error handling
        status = SecKeyDecrypt(key,
                               kSecPaddingPKCS1,
                               cipherBuffer,
                               cipherBufferSize,
                               plainBuffer,
                               &plainBufferSize
                               );                              // 3

        //  Error handling
        //  Store or display the decrypted text

        if(key) CFRelease(key);

        NSData *decrypted = [NSData dataWithBytes:(const void *)plainBuffer length:plainBufferSize];
        return decrypted;
    }

Any clues on how should I modify this method so that it will split the data in blocks to handle large amount of data?

도움이 되었습니까?

해결책

According to RFC3447 RSAES-PKCS1-v1_5 encryption scheme you are using can operate on messages of length up to k - 11 octets (k is the octet length of the RSA modulus) so if you are using 2048-bit RSA key then maximum length of the plain data to be encrypted is 245 bytes. So you will need to split plain data to the chunks of this size and then encrypt each of them individually but this is rather rare and slow solution. It is much better (and also pretty common) to generate symmetric AES key, encrypt large data using AES algorithm and then encrypt small AES key with RSA key.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top