RSA 非對稱加密&解密

Rancy發表於2020-12-18

封裝一個非對稱加密和解密實用類

<?php

class RsaServer
{
    /**
     * @var false|resource
     */
    protected $key;

    /**
     * 獲取祕鑰
     * RsaServer constructor.
     * @param string $key_file
     * @param bool $is_pub
     * @throws FileNotFoundException
     */
    public function __construct(string $key_file, $is_pub = false)
    {
        if (!is_file($key_file)) {
            throw new \Exception('key path is invalid');
        }
        $content = file_get_contents($key_file);
        if ($is_pub) {
            $this->key = openssl_pkey_get_public($content);
        } else {
            $this->key = openssl_pkey_get_private($content);
        }

        return $this;
    }

    /**
     * 私鑰加密
     * @param string $data
     * @return null|string
     */
    public function privateEncrypt($data = '')
    {
        if (!is_string($data)) {
            return null;
        }
        return openssl_private_encrypt($data, $encrypted, $this->key) ? base64_encode($encrypted) : null;
    }

    /**
     * 公鑰加密
     * @param string $data
     * @return null|string
     */
    public function publicEncrypt($data = '')
    {
        if (!is_string($data)) {
            return null;
        }
        return openssl_public_encrypt($data, $encrypted, $this->key) ? base64_encode($encrypted) : null;
    }

    /**
     * 私鑰解密
     * @param string $encrypted
     * @return null
     */
    public function privateDecrypt($encrypted = '')
    {
        if (!is_string($encrypted)) {
            return null;
        }
        return (openssl_private_decrypt(base64_decode($encrypted), $decrypted, $this->key)) ? $decrypted : null;
    }

    /**
     * 公鑰解密
     * @param string $encrypted
     * @return null
     */
    public function publicDecrypt($encrypted = '')
    {
        if (!is_string($encrypted)) {
            return null;
        }
        return (openssl_public_decrypt(base64_decode($encrypted), $decrypted, $this->key)) ? $decrypted : null;
    }
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章