Skip to content

Instantly share code, notes, and snippets.

@datashaman
Last active July 24, 2020 16:58
Show Gist options
  • Save datashaman/1c4133928df1f7146f0921fa957e99b5 to your computer and use it in GitHub Desktop.
Save datashaman/1c4133928df1f7146f0921fa957e99b5 to your computer and use it in GitHub Desktop.
Asymmetric encryption example
<?php
class KeyHolder
{
private $key;
public function __construct()
{
$this->key = new class () {
private $resource;
public function __construct()
{
$this->resource = openssl_pkey_new(array('private_key_bits' => 2048));
}
public function getPublic(): string
{
return openssl_pkey_get_details($this->resource)['key'];
}
public function getPrivate(): string
{
openssl_pkey_export($this->resource, $key);
return $key;
}
};
}
public function getPublicKey(): string
{
return $this->key->getPublic();
}
public function encryptFor(string $publicKey, string $unencrypted): string
{
if (
openssl_public_encrypt(
$unencrypted,
$encrypted,
$publicKey
)
) {
return base64_encode($encrypted);
}
throw new Exception('Encryption failed');
}
public function decrypt(string $encrypted): string
{
if (
openssl_private_decrypt(
base64_decode($encrypted),
$decrypted,
$this->key->getPrivate()
)
) {
return $decrypted;
}
throw new Exception('Decryption failed');
}
}
$service = new KeyHolder();
$partner = new KeyHolder();
$encrypted = $partner->encryptFor($service->getPublicKey(), 'This is a test of the emergency broadcast system.');
// this succeeds
var_dump($service->decrypt($encrypted));
// this fails, only the recipient can decrypt the message
var_dump($partner->decrypt($encrypted));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment