Skip to content

Instantly share code, notes, and snippets.

@VassilisPallas
Last active October 12, 2017 13:40
Show Gist options
  • Save VassilisPallas/0816dace471b73ddc97d28da4b564546 to your computer and use it in GitHub Desktop.
Save VassilisPallas/0816dace471b73ddc97d28da4b564546 to your computer and use it in GitHub Desktop.
Helper class to create RSA keys, encrypt and decrypt data with public and private key
class Encryption
{
private $path = 'CUSTOM PATH';
public static function generateKeys()
{
$privateKey = openssl_pkey_new(array(
'private_key_bits' => 2048, // Size of Key.
'private_key_type' => OPENSSL_KEYTYPE_RSA,
));
// Save the private key to private.key file. Never share this file with anyone.
openssl_pkey_export_to_file($privateKey, self::$path . '/rsa/id_rsa');
// Generate the public key for the private key
$a_key = openssl_pkey_get_details($privateKey);
// Save the public key in public.key file. Send this file to anyone who want to send you the encrypted data.
file_put_contents(self::$path . '/rsa/id_rsa.pub', $a_key['key']);
// Free the private Key.
openssl_free_key($privateKey);
}
public static function encrypt($value)
{
// Compress the data to be sent
$plaintext = gzcompress($value);
// Get the public Key of the recipient
$publicKey = openssl_pkey_get_public('file://' . self::$path . '/rsa/id_rsa.pub');
$a_key = openssl_pkey_get_details($publicKey);
// Encrypt the data in small chunks and then combine and send it.
$chunkSize = ceil($a_key['bits'] / 8) - 11;
$output = '';
while ($plaintext) {
$chunk = substr($plaintext, 0, $chunkSize);
$plaintext = substr($plaintext, $chunkSize);
$encrypted = '';
if (!openssl_public_encrypt($chunk, $encrypted, $publicKey)) {
die('Failed to encrypt data');
}
$output .= $encrypted;
}
openssl_free_key($publicKey);
return $output;
}
public static function decrypt($encrypted)
{
// Get the private Key
if (!$privateKey = openssl_pkey_get_private('file://' . self::$path . '/rsa/id_rsa')) {
die('Private Key failed');
}
$a_key = openssl_pkey_get_details($privateKey);
// Decrypt the data in the small chunks
$chunkSize = ceil($a_key['bits'] / 8);
$output = '';
while ($encrypted) {
$chunk = substr($encrypted, 0, $chunkSize);
$encrypted = substr($encrypted, $chunkSize);
$decrypted = '';
if (!openssl_private_decrypt($chunk, $decrypted, $privateKey)) {
die('Failed to decrypt data');
}
$output .= $decrypted;
}
openssl_free_key($privateKey);
// Uncompress the unencrypted data.
return gzuncompress($output);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment