Encrypt data with Objective-C and decrypt in Python

I have the same problem as this question , but unfortunately there was no answer to it.

I have the following objective-c code to encrypt with CCCrypt:

(NSData *)doCrypt:(NSData *)data usingKey:(NSData *)key withInitialVector:(NSData *)iv mode:(int)mode error: (NSError *)error
{
    int buffersize = 0;
    if(data.length % 16 == 0) { buffersize = data.length + 16; }
    else { buffersize = (data.length / 16 + 1) * 16 + 16; }

    // int buffersize = (data.length <= 16) ? 16 : data.length;
    size_t numBytesEncrypted = 0;
    void *buffer = malloc(buffersize * sizeof(uint8_t));
    CCCryptorStatus result = CCCrypt(mode, 0x0, 0x1, [key bytes], [key length], [iv bytes], [data bytes], [data length], buffer, buffersize, &numBytesEncrypted);

    return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted freeWhenDone:YES];
}

I use kCCAlgorithmAES128c kCCOptionPKCS7Paddingas parameters and call the function with[Cryptor doCrypt:data usingKey:key withInitialVector:nil mode:0x0 error:nil];

Now I would like to decrypt it using python, and for this I have the following code:

def decrypt(self, data, key):
        iv = '\x00' * 16

        encoder = PKCS7Encoder()
        padded_text = encoder.encode(data)

        mode = AES.MODE_CBC
        cipher = AES.new(key, mode, iv)
        decoded = cipher.decrypt(padded_text)
        return decoded

PKCS7Encoder is as follows:

class PKCS7Encoder():
    """
    Technique for padding a string as defined in RFC 2315, section 10.3,
    note #2
    """
    class InvalidBlockSizeError(Exception):
        """Raised for invalid block sizes"""
        pass

    def __init__(self, block_size=16):
        if block_size < 2 or block_size > 255:
            raise PKCS7Encoder.InvalidBlockSizeError('The block size must be ' \
                    'between 2 and 255, inclusive')
        self.block_size = block_size

    def encode(self, text):
        text_length = len(text)
        amount_to_pad = self.block_size - (text_length % self.block_size)
        if amount_to_pad == 0:
            amount_to_pad = self.block_size
        pad = chr(amount_to_pad)
        return text + pad * amount_to_pad

    def decode(self, text):
        pad = ord(text[-1])
        return text[:-pad]

But whenever I call a function decrypt(), it returns garbage. Am I missing something or am I having the wrong option?


Example input and output:

NSData *keyData = [[NSData alloc] initWithRandomData:16];
    NSLog(@"key: %@", [keyData hex]);
    NSString *str = @"abcdefghijklmno";
    NSLog(@"str: %@", str);
    NSData *encrypted = [Cryptor encrypt:[str dataUsingEncoding:NSUTF8StringEncoding] usingKey:keyData];
    NSLog(@"encrypted str: %@", [encrypted hex]);

gives:

key: 08b6cb24aaec7d0229312195e43ed829
str: a
encrypted str: 52d61265d22a05efee2c8c0c6cd49e9a

And python:

cryptor = Cryptor()
encrypted_hex_string = "52d61265d22a05efee2c8c0c6cd49e9a"
hex_key = "08b6cb24aaec7d0229312195e43ed829"
print cryptor.decrypt(encrypted_hex_string.decode("hex"), hex_key.decode("hex"))

Result:

láz

, , 610f0f0f0f0f0f0f0f0f0f0f0f0f0f0fb02b09fd58cccf04f042e2c90d6ce17a 61 = a, , .

:

key: 08b6cb24aaec7d0229312195e43ed829
str: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
encrypted str: 783fce3eca7ebe60d58b01da3d90105a93bf2d659cfcffc1c2b7f7be7cc0af4016b310551965526ac211f4d6168e3cc5

:

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaôNÍ"ƒ˜ Üšw6C%

, a ... , -

IV - iOs 16x 0 Python (. )

+4
1

: aes_decrypt(pkcs7_pad(ciphertext))
: pkcs7_unpad(aes_decrypt(ciphertext))

, AES CBC , , . .


, a - (b % a) 0 () a b. ,

if amount_to_pad == 0:
    amount_to_pad = self.block_size

. , a - (b % a) , if.

unpad (decode), , . , .

+2
source

Source: https://habr.com/ru/post/1606428/


All Articles