Encrypt and Decrypt Data Using Keys

Encrypt and Decrypt Data Using Keys

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


Join 31,000+ others and never miss out on new tips, tutorials, and more.

Laravel News Partners

Laravel Jobs

Full Stack PHP (Mid-Level/Senior) Programmer
Software Developer
Remote, (US & Canada Only)
Patient Prism
Web Application Developer
Chicago Loop
Leading Real Estate Companies of the World
Multiple Laravel Developers (Part-Time)
Remote, USA Only
The Great Escape Room
Software Developer
Remote (US & Canada)