Encrypt and Decrypt Data Using Keys

Packages

November 19th, 2020

encrypt-security-featured.png

Crypto is a package by Spatie that allows you to easily generate public/private key pairs and then encrypt/decrypt messages using those keys. While dealing with complex ideas under-the-hood, this package provides a clean and simple interface over PHP’s openssl_* functions:

use Spatie\Crypto\Rsa\KeyPair;
use Spatie\Crypto\Rsa\PrivateKey;
use Spatie\Crypto\Rsa\PublicKey;

// generating an RSA key pair
[$privateKey, $publicKey] = (new KeyPair())->generate();

// when passing paths, the generated keys will be written those paths
(new KeyPair())->generate($pathToPrivateKey, $pathToPublicKey);

$data = 'my secret data';

$privateKey = PrivateKey::fromFile($pathToPrivateKey);
$encryptedData = $privateKey->encrypt($data); // returns something unreadable

$publicKey = PublicKey::fromFile($pathToPublicKey);
$decryptedData = $publicKey->decrypt($encryptedData); // returns 'my secret data'

You can also determine if the data can be decrypted and verify data as well:

// Can decrypt?
PrivateKey::fromFile($pathToPrivateKey)->canDecrypt($data); // returns a boolean;
PublicKey::fromFile($pathToPublicKey)->canDecrypt($data); // returns a boolean;

$signature = PrivateKey::fromFile($pathToPrivateKey)->sign('my message'); // returns a string
$publicKey = PublicKey::fromFile($pathToPublicKey);
$publicKey->verify('my message', $signature) // returns true;
$publicKey->verify('my modified message', $signature) // returns false;

You can learn more about this package, get full installation instructions, and view the source code on GitHub at spatie/crypto. Freek Van der Herten also wrote about this package on his blog.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.