Encrypt and Decrypt Secret Documents with PHP

Maybe you would like to encrypt some of your documents to avoid the content of them could be shared with unwanted users.

In this story, I will show you a simple solution based on PHP 5/7/8 that lets you encrypt and decrypt strings, protect them with a password and securely share them with other users.

To do it we have to build an encrypt function such as:

$data_to_encrypt = ‘Secret Data Here!’;
$secret_key = ‘Secret_123’;
$encrypted = openssl_encrypt($data_to_encrypt, ‘aes256’, $secret_key, 0, ‘IV_16-bit_string’);echo $encrypted; // sh4XQQ1FWJiarQo4qp97OqOOF4sqA00VqBYjDWP+XbE=

This code will generate an encrypted string:
sh4XQQ1FWJiarQo4qp97OqOOF4sqA00VqBYjDWP+XbE=

This string contains the original data: Secret Data Here!

And it’s protected by a secret key (password): Secret_123

You can share it with another user or conserve it, the code to decrypt it is:

$data_to_decrypt = ‘sh4XQQ1FWJiarQo4qp97OqOOF4sqA00VqBYjDWP+XbE=’;
$secret_key = ‘Secret_123’;
$decrypted = openssl_decrypt($data_to_decrypt, ‘aes256’, $secret_key, 0, ‘IV_16-bit_string’);echo $decrypted; // Secret Data Here!

--

--

--

I’m a software engineer based in Milan. Always looking to discover new development methods and technologies, I am an open source enthusiast and supporter.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Privacy is at risk when security fails

Castamash Privacy

Race Condition — Resulted in using the feature which was supposed to be obtained after subscription.

{UPDATE} Onet Hack Free Resources Generator

Anonymization and Randomisation of IoT identities in the context of industrial applications

Find users by password and PGP key

Samsung 21.5 1080p LED Monitor (S22E200B) 13563466

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Andrea Pollastri

Andrea Pollastri

I’m a software engineer based in Milan. Always looking to discover new development methods and technologies, I am an open source enthusiast and supporter.

More from Medium

A simple PHP site (4/?)— Routing

Debug Walkthrough: Exploiting SSH MOTD and PHP Deserialization

How to update a mysql column’s data type for an already migrated Table in PHP

PHP 8.1 Begginer —Through introduction to Enums