1

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

1

1 Answer 1

7

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 .

What People Want To Do Here

Some encryption function is used to deterministically retrieve the ID

What People Should Do Instead

Use a separate column

Explanation

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.

What To Do If Encryption Is Non-Negotiable?

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.