使用密钥PHP加密和解密字符串

Bel*_*ish 6 php encryption

我正在寻找一些函数来使用指定的密钥加密和解密php中的字符串.

谢谢!

Mar*_*ark 5

我以前使用过的一个基本的 openssl 实现:

class MyEncryption
{

    public $pubkey = '...public key here...';
    public $privkey = '...private key here...';

    public function encrypt($data)
    {
        if (openssl_public_encrypt($data, $encrypted, $this->pubkey))
            $data = base64_encode($encrypted);
        else
            throw new Exception('Unable to encrypt data. Perhaps it is bigger than the key size?');

        return $data;
    }

    public function decrypt($data)
    {
        if (openssl_private_decrypt(base64_decode($data), $decrypted, $this->privkey))
            $data = $decrypted;
        else
            $data = '';

        return $data;
    }
}
Run Code Online (Sandbox Code Playgroud)

您需要生成 RSA 密钥对。有关如何执行此操作的信息请参见此处。将私钥存储在文件本身中是一个坏主意。这只是一个例子。理想情况下,您希望用户在解密时提供私钥