所以我需要对唯一用户进行身份验证,因此每个用户都有自己的priv / pub密钥对。我试图创建一个可以生成密钥对的轻量级类,然后加密或解密数据。
这是我到目前为止所做的:
class RSA
{
public $pubkey = '';
public $privkey = '';
public function genKeys()
{
/* Create the private and public key */
$res = openssl_pkey_new();
/* Extract the private key from $res to $privKey */
openssl_pkey_export($res, $privKey);
$this->privkey = $privKey;
/* Extract the public key from $res to $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;
}
}
我正在加密数据,然后解密和回显纯文本,但它总是返回空白?
$RSA = new RSA();
$RSA->genKeys();
$text = "Hello World.";
$e = $RSA->encrypt($text);
$m = $RSA->decrypt($e);
echo "Encrypted: $e <br />";
echo "Decrypted: $m <br />";
有什么想法吗?而且我不想使用繁重的库。尽可能轻量级是完美的。
答案 0 :(得分:0)
我删除了基本编码并让它工作:
class RSA
{
public $privKey = '';
public $pubKey = '';
public function genKeys()
{
$res = openssl_pkey_new();
// Get private key
openssl_pkey_export($res, $priv);
$this->privKey = $priv;
// Get 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 );