Reputation: 5525
I have this code :
<?php
$key = 'thisisakey';
$iv = '1234567812345678';
$plaintext = 'Hello World';
$ciphertext = openssl_encrypt($plaintext, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
echo $ciphertext . '<br>';
$plaintext = openssl_decrypt($ciphertext, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
echo $plaintext . '<br>';
?>
The idea behind this code was encrypt the data to be used on the URL. So, I'm expecting output which URL friendly. I mean, it contains alpha-numeric characters only. But when I use this openssl_encrypt
function, I got weird characters, which I don't think URL friendly.
it produces output like this :
^‘-7Ⱦ®l¿ô¾áÙ
how to generate URL friendly characters from openssl_encrypt
? thank you
Upvotes: 1
Views: 2909
Reputation: 34093
This question has been asked a lot, with different word choice (which makes it difficult to say, "Just search for it!"). This fact prompted a blog post titled, The Comprehensive Guide to URL Parameter Encryption in PHP .
Typically, people want short random-looking URLs. This doesn't allow you much room to encrypt then authenticate the database record ID you wish to obfuscate. Doing so would require a minimum URL length of 32 bytes (for HMAC-SHA256), which is 44 characters when encoded in base64.
A simpler strategy is to generate a random string (see random_compat for a PHP5 implementation of random_bytes()
and random_int()
for generating these strings) and reference that column instead.
If you must encrypt data (very much NOT recommended), don't use a homegrown design (especially unauthenticated CBC mode). Use a trustworthy library instead.
Once you have encryption working, make sure you the ciphertext uses hex or base64url encoding.
Upvotes: 7