PHP sha256WithRsa加解密

//生成 sha256WithRSA 签名
    public function getSign($content, $privateKey){
        $privateKey = "-----BEGIN RSA PRIVATE KEY-----\n" .
            wordwrap($privateKey, 64, "\n", true) .
            "\n-----END RSA PRIVATE KEY-----";

        $key = openssl_get_privatekey($privateKey);

//        openssl_private_encrypt($content, $signature, $privateKey, OPENSSL_PKCS1_PADDING);
        openssl_sign($content, $signature, $key, OPENSSL_ALGO_SHA256);
        openssl_free_key($key);
        $sign = base64_encode($signature);
        return $sign;
    }

    //验证 sha256WithRSA 签名
    public function verify($content, $sign, $publicKey){

        $publicKey = "-----BEGIN PUBLIC KEY-----\n" .
            wordwrap($publicKey, 64, "\n", true) .
            "\n-----END PUBLIC KEY-----";

        $key = openssl_get_publickey($publicKey);
        $ok = openssl_verify($content,base64_decode($sign), $key, 'SHA256');
        openssl_free_key($key);
        return $ok;
    }

    /**
     * 平台公钥加密
     * @param $content
     * @param $publicKey
     * @return string
     */
    public function encrypt($content, $platpublicKey)
    {
        $platpublicKey = "-----BEGIN PUBLIC KEY-----\n" .
            wordwrap($platpublicKey, 64, "\n", true) .
            "\n-----END PUBLIC KEY-----";

        openssl_public_encrypt($content, $encrypted, $platpublicKey, OPENSSL_PKCS1_PADDING);

        return base64_encode($encrypted);
    }

/**
     * 平台公钥加密
     * @param $content
     * @param $publicKey
     * @return string
     */
    public function encrypt($content, $publicKey)
    {
        $publicKey = "-----BEGIN PUBLIC KEY-----\n" .
            wordwrap($publicKey, 64, "\n", true) .
            "\n-----END PUBLIC KEY-----";
        $crypto='';
        foreach (str_split($content, 117) as $chunk) {

            openssl_public_encrypt($chunk, $encrypted, $publicKey, OPENSSL_PKCS1_PADDING);

            $crypto .= $encrypted;
        }

        return base64_encode($crypto);
    }

 

你可能感兴趣的:(加解密)