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:

1use Spatie\Crypto\Rsa\KeyPair;
2use Spatie\Crypto\Rsa\PrivateKey;
3use Spatie\Crypto\Rsa\PublicKey;
4 
5// generating an RSA key pair
6[$privateKey, $publicKey] = (new KeyPair())->generate();
7 
8// when passing paths, the generated keys will be written those paths
9(new KeyPair())->generate($pathToPrivateKey, $pathToPublicKey);
10 
11$data = 'my secret data';
12 
13$privateKey = PrivateKey::fromFile($pathToPrivateKey);
14$encryptedData = $privateKey->encrypt($data); // returns something unreadable
15 
16$publicKey = PublicKey::fromFile($pathToPublicKey);
17$decryptedData = $publicKey->decrypt($encryptedData); // returns 'my secret data'

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

1// Can decrypt?
2PrivateKey::fromFile($pathToPrivateKey)->canDecrypt($data); // returns a boolean;
3PublicKey::fromFile($pathToPublicKey)->canDecrypt($data); // returns a boolean;
4 
5$signature = PrivateKey::fromFile($pathToPrivateKey)->sign('my message'); // returns a string
6$publicKey = PublicKey::fromFile($pathToPublicKey);
7$publicKey->verify('my message', $signature) // returns true;
8$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.