Question

I'm using RNCryptor to encrypt a message in iOS and then decrypting it in PHP. However, special characters dissapear from the decrypted string.

How I encrypt in iOS

-(NSData *)encryptThis:(NSString *)str

{

NSString *key = @"mysuper32bitkey";
NSError *error = nil;
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSData *encryptedData = [RNEncryptor encryptData:data
                                    withSettings:kRNCryptorAES256Settings
                                        password:key
                                           error:&error];

return encryptedData;

}

How I decrypt in PHP

$b64_data = $message;
$password = "mysuper32bitkey"
// back to binary
$bin_data = $message;// message already in binary. No need for -> mb_convert_encoding($b64_data, "UTF-8", "BASE64");
// extract salt
$salt = substr($bin_data, 2, 8);
// extract HMAC salt
$hmac_salt = substr($bin_data, 10, 8);
// extract IV
$iv = substr($bin_data, 18, 16);
// extract data
$data = substr($bin_data, 34, strlen($bin_data) - 34 - 32);
// extract HMAC
$hmac = substr($bin_data, strlen($bin_data) - 32);

// make HMAC key
$hmac_key = pbkdf2('SHA1', $password, $hmac_salt, 10000, 32, true);
// make HMAC hash
$hmac_hash = hash_hmac('sha256', $data , $hmac_key, true);
// check if HMAC hash matches HMAC
if($hmac_hash != $hmac)
    echo "false";

// make data key
$key = pbkdf2('SHA1', $password, $salt, 10000, 32, true);
// decrypt
$ret = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv);

echo trim(preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x80-\xFF]/u', '', $ret));

The thing is that if I encrypt "Agresión" in iOS, PHP only returns "Agresin". Why it doesn't decrypt the "ó" ? I thought dataUsingEncoding:NSUTF8StringEncoding would keep special characters... Am I supposed to use another type of encoding?

Was it helpful?

Solution

You're stripping the ó (U+00F3) in this line:

echo trim(preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x80-\xFF]/u', '', $ret));

Note that you're removing all of \x80-\xFF. Don't do that.

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