Md Mahfuzur Rahman
Md Mahfuzur Rahman

Reputation: 2359

Security::encrypt() method returns invalid characters in CakePHP 3.2

I'm using Security utility for encryption and decryption in CakePHP 3.2. When I call

Security::encrypt('string', 'key') //key length is 32 or more

method over a string, it returns the encrypted string with some invalid characters like following:

8e88c050ff20cb12984bf1af24b11fc7ada198082c67d6b3da7170572d5bcd54���p���lp���������21ķ�;ܝ�%N�

I want to use this string in url. But it's not working as expected as there are some invalid characters.

Now I want to avoid these characters. Is there any way to avoid these character ?

Upvotes: 0

Views: 904

Answers (1)

ndm
ndm

Reputation: 60463

Security::encrypt() returns binary data, there's nothing invalid about what you see.

If you need a URL safe string, then you for example use Base64 encoding as basis. That would however also require to take care of the URL unsafe characters that can occur in Base64, namely +, / and =:

// encode
$base64String = base64_encode($encryptedBinaryData);
$urlSafeString = str_replace(['+', '/', '='], ['-', '_', '~'], $base64String);

// decode
$base64String = str_replace(['-', '_', '~'], ['+', '/', '='], $urlSafeString);
$encryptedBinaryData = base64_decode($base64String);

If you're OK with a little more data, you could use hexadecimal encoding, which is completely URL safe:

// encode
$urlSafeString = bin2hex($encryptedBinaryData);

// decode
$encryptedBinaryData = hex2bin($urlSafeString);

See also

Upvotes: 6

Related Questions