Skip to content

Instantly share code, notes, and snippets.

@nim4n136
Last active August 3, 2018 07:11
Show Gist options
  • Save nim4n136/466504586291a3b55812587f6bbaadef to your computer and use it in GitHub Desktop.
Save nim4n136/466504586291a3b55812587f6bbaadef to your computer and use it in GitHub Desktop.
Encryption and Decryption OpenSSL with PHP
<?php
class Encryption
{
public $config = array(
"digest_alg" => "sha512",
"private_key_bits" => 2046,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
);
public $encrypted;
public $privateKey;
public $decrypted;
public function encrypt($data, $PlainPrivateKey){
$res = openssl_pkey_new($this->config);
openssl_pkey_export($res, $PlainPrivateKey);
$pubKey = openssl_pkey_get_details($res);
openssl_public_encrypt($data, $encrypted, $pubKey["key"]);
$this->privateKey = $PlainPrivateKey;
$this->encrypted = base64_encode($encrypted);
}
public function decrypt($encrypted,$privateKey){
$encrypted = base64_decode($encrypted);
openssl_private_decrypt($encrypted, $decrypted, $privateKey);
$this->decrypted = $decrypted;
}
}
$Encrypt = new Encryption;
$Encrypt->encrypt(
'Hello how are you?', // data plain Text
'secret key' // key
);
// result encrypted
echo $encrypted = $Encrypt->encrypted;
echo "<br/>";
// Get new private Key
$privateKey = $Encrypt->privateKey;
// get Decrypt
$Encrypt->decrypt($encrypted,$privateKey);
// result Decrypt
echo $Encrypt->decrypted;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment