Saint Robson
Saint Robson

Reputation: 5525

PHP Openssl Encrypt Data For URL

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

Answers (1)

Scott Arciszewski
Scott Arciszewski

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 .

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.

Upvotes: 7

Related Questions