iOS encryption AES128/CBC/nopadding why is not working?

前端 未结 1 2041
梦谈多话
梦谈多话 2020-12-30 15:20

I have an app that needs to encode some data using AES/CBC/no padding. The app is ported also on android. There the encoding is done like this:

byte[] encode         


        
1条回答
  •  礼貌的吻别
    2020-12-30 15:53

    I found the solution to my problem. In order to make the encryption work without padding i had to add 0x0000 instead of kCCOptionPKCS7Padding or kCCOptionECBMode which are treated.

    Also if the data that needs to be encoded doesn't have a length multiple of kCCKeySizeAES128 ( 16 ) then the vector that holds the data must be resized to have the length multiple with kCCKeySizeAES128 and the empty values filled with something. I added spaces.

        - (NSData *)AES128EncryptWithKey:(NSString *)key
    {
        char keyPtr[kCCKeySizeAES128+1];
        bzero(keyPtr, sizeof(keyPtr));
    
        [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    
        int dataLength = [self length];
        int diff = kCCKeySizeAES128 - (dataLength % kCCKeySizeAES128);
        int newSize = 0;
    
        if(diff > 0)
        {
            newSize = dataLength + diff;
        }
    
        char dataPtr[newSize];
        memcpy(dataPtr, [self bytes], [self length]);
        for(int i = 0; i < diff; i++)
        {
            dataPtr[i + dataLength] = 0x20;
        }
    
        size_t bufferSize = newSize + kCCBlockSizeAES128;
        void *buffer = malloc(bufferSize);
    
        size_t numBytesEncrypted = 0;
        CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
                                              kCCAlgorithmAES128,
                                              0x0000, //No padding
                                              keyPtr,
                                              kCCKeySizeAES128,
                                              NULL,
                                              dataPtr,
                                              sizeof(dataPtr),
                                              buffer,
                                              bufferSize,
                                              &numBytesEncrypted);
    
        if(cryptStatus == kCCSuccess)
        {
            return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
        }
    
        return nil;
    }
    

    0 讨论(0)
提交回复
热议问题