Lightweight RSA Encryption PHP -
so need authenticate unique users, each user have own priv/pub keypair. i'm trying make lightweight class can generate key pair, , encrypt or decrypt data.
here have far:
class rsa { public $pubkey = ''; public $privkey = ''; public function genkeys() { /* create private , public key */ $res = openssl_pkey_new(); /* extract private key $res $privkey */ openssl_pkey_export($res, $privkey); $this->privkey = $privkey; /* extract public key $res $pubkey */ $pubkey = openssl_pkey_get_details($res); $pubkey = $pubkey["key"]; $this->pubkey = $pubkey; } public function encrypt($data) { $data = ''; if (openssl_private_encrypt($data, $encrypted, $this->privkey)) $data = base64_encode($encrypted); return $data; } public function decrypt($data) { $data = ''; if (openssl_public_decrypt(base64_decode($data), $decrypted, $this->pubkey)) $data = $decrypted; return $data; } }
i'm encrypting data , decrypting , echoing plain text returns blank?
$rsa = new rsa(); $rsa->genkeys(); $text = "hello world."; $e = $rsa->encrypt($text); $m = $rsa->decrypt($e); echo "encrypted: $e <br />"; echo "decrypted: $m <br />";
any ideas? , don't want use heavy extensive libraries. lightweight possible perfect.
i removed base encoding , got work:
class rsa { public $privkey = ''; public $pubkey = ''; public function genkeys() { $res = openssl_pkey_new(); // private key openssl_pkey_export($res, $priv); $this->privkey = $priv; // public key $pubkey = openssl_pkey_get_details($res); $this->pubkey = $pubkey["key"]; } public function private_encrypt( $tocrypt ) { $output = ""; openssl_private_encrypt($tocrypt, $output, $this->privkey); return $output; } public function public_decrypt( $tocrypt ) { $output = ""; openssl_public_decrypt($tocrypt, $output, $this->pubkey); return $output; } } $rsa = new rsa(); $rsa->genkeys(); $m = "hi"; $e = $rsa->private_encrypt( $m ); echo $rsa->public_decrypt( $e );
Comments
Post a Comment