php rsa長文加密解密

tros發表於2024-04-12

金鑰型別:

1024bit:分段加密位元組數為117,分段解密位元組數為128。
2048bit:分段加密位元組數為245,分段解密位元組數為256。

class RsaBill
{

    private $public_key_resource;
    private $private_key_resource;

    public function __construct()
    {
        $this->public_key_resource = openssl_pkey_get_public(config('app.public_key'));
        $this->private_key_resource = openssl_pkey_get_private(config('app.private_key'));
    }

    //公鑰加密
    public function public_encrypt(string $source)
    {
        $maxLength = 245;
        $output = '';
        while ($source) {
            $input = substr($source, 0, $maxLength);
            $source = substr($source, $maxLength);
            $res = '';
            openssl_public_encrypt($input, $res, $this->public_key_resource, OPENSSL_PKCS1_PADDING);
            $output .= $res;
        }

        return base64_encode($output);
    }

    /**
     * 私鑰解密
     */
    public function private_decrypt(string $input)
    {
        $maxLength = 256;
        $content = base64_decode($input);
        $output = '';
        while ($content) {
            $str = substr($content, 0, $maxLength);
            $content = substr($content, $maxLength);
            $res = '';
            openssl_private_decrypt($str, $res, $this->private_key_resource, OPENSSL_PKCS1_PADDING);
            $output .= $res;
        }
        return $output;
    }
}

相關文章