Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AES Encryption of Arabic characters - Objective C

I have an encryption function that gets data and key, with inner iv and returns an encrypted string. I can encrypt every string that contains just English characters but not about Arabic. This is my function. Please help me to find the problem. Thanks

-(NSString*)Encrypt:(NSString*)data second:(NSString*)key
    {
        size_t outLength;
        NSMutableData * cipherData = [NSMutableData dataWithLength:data.length + kCCBlockSizeAES128];
        Byte byte[] = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,}; //It`s not valid. The main iv is secret
        NSData *datakey = [NSData dataWithBytes:key.UTF8String length:key.length];
        NSData *datadata = [NSData dataWithBytes:data.UTF8String length:data.length];
        CCCryptorStatus result = CCCrypt( kCCEncrypt
                                        , kCCAlgorithmAES128
                                        , kCCOptionPKCS7Padding
                                        , datakey.bytes
                                        , [datakey length]
                                        , byte
                                        , datadata.bytes
                                        , [datadata length]
                                        , cipherData.mutableBytes
                                        , cipherData.length
                                        , &outLength);

    if (result == kCCSuccess) {
        cipherData.length = outLength;
    }
    else {

    }
    NSData *encryptedData=cipherData;
    NSString *str=[encryptedData base64EncodedStringWithOptions: NSDataBase64Encoding64CharacterLineLength];
    return str;
}

like image 824
Mehdi Gilanpour Avatar asked Oct 28 '22 23:10

Mehdi Gilanpour


1 Answers

The problem is that cipherData is to short. It need to be a block longer than datadata which may (such as in this case) be longer than data.length.

When creating data with utf-8 encoding from a string that contains multiple-byte data such as Arabic, emoji and etc the data will be longer than the string characters.

Incorrect code:

NSMutableData * cipherData = [NSMutableData dataWithLength:data.length + kCCBlockSizeAES128];
NSData *datadata = [NSData dataWithBytes:data.UTF8String length:data.length];

Correct code:

NSData *datadata = [data dataUsingEncoding:NSUTF8StringEncoding];
NSMutableData * cipherData = [NSMutableData dataWithLength: datadata.length + kCCBlockSizeAES128];  

Note that misnaming the input string data does not help, it is a string. renaming data -> tex and then ``datadata->data` makes the code more clear. Good naming solves many code problems.

like image 124
zaph Avatar answered Nov 11 '22 10:11

zaph