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:
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!