Obj-C: In CommonCrypto, if the CCCrypt() do not use option kCCOptionPKCS7Padding, the result buffer is empty

StackOverflow https://stackoverflow.com/questions/17740113

  •  03-06-2022
  •  | 
  •  

Question

If I remove the kCCOptionPKCS7Padding, the following function will return me correct buffer size with empty cipher data <>. I can't use kCCDecrypt option to decrypt empty cipher text back to Plain text.

    char keyPtr[kCCKeySizeAES128 + 1];
    memset(keyPtr, 0, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];

    char ivPtr[kCCBlockSizeAES128 + 1];
    memset(ivPtr, 0, sizeof(ivPtr));

    [iv getCString:ivPtr
         maxLength:sizeof(ivPtr)
          encoding:NSUTF8StringEncoding];

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

    size_t numBytesCrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
                                          kCCAlgorithmAES128,
                                          kCCOptionECBMode|kCCOptionPKCS7Padding,
                                          keyPtr,
                                          kCCBlockSizeAES128,
                                          ivPtr,
                                          [self bytes],
                                          dataLength,
                                          buffer,
                                          bufferSize,
                                          &numBytesCrypted);
   return [NSData dataWithBytesNoCopy:buffer length:numBytesCrypted];

If kCCOptionPKCS7Padding not there, encryption engine doesn't work. Thus, it looks like compulsory, not option.
My question:
Who to make CCCrypt() works without PKCS7 Padding?

Was it helpful?

Solution

This is to do with block alignment of input data. If the input data length is not an integer multiple of the encryption block size, then padding will have to be added to finish the final block. There is some discussion of this in the header file for CCCryptorUpdate (CCCrypt is actually CCCryptorCreate, CCCryptorUpdate, CCCryptorFinal and CCCryptorRelease called sequentially):

When performing symmetric encryption with block ciphers, and padding is enabled via kCCOptionPKCS7Padding, the total number of bytes provided by all the calls to this function when encrypting can be arbitrary (i.e., the total number of bytes does not have to be block aligned). However if padding is disabled, or when decrypting, the total number of bytes does have to be aligned to the block size; otherwise CCCryptFinal() will return kCCAlignmentError.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top