php中rsa加密解密

    /**获取私钥是否可用
     * @return bool
     */
    public function isPrivateKey()
    {
        if ( !openssl_pkey_get_private( $this -> privateKey ) ) {
            return false;
        }
        return true;
    }

    /**获取公钥是否可用
     * @return bool
     */
    public function isPublicKey()
    {
        if ( !openssl_pkey_get_public( $this -> publicKey ) ) {
            return false;
        }
        return true;
    }

    /**
     * @param        $str
     * @param string $encrypt_data
     *
     * @return string
     */
    public function publicKeyEncrypt( $str , $encrypt_data = '' )
    {
        openssl_public_encrypt( $str , $encrypt_data , $this -> publicKey );
        return base64_encode( $encrypt_data );
    }

    /**
     * @param        $cipherText
     * @param string $decrypted
     *
     * @return string
     */
    public function privateKeyDecrypt( $cipherText , $decrypted = '' )
    {
        $cryptData = base64_decode( $cipherText );
        openssl_private_decrypt( $cryptData , $decrypted , $this -> privateKey );
        return $decrypted;
    }

    /**将字符串格式公私钥格式化为pem格式公私钥
     *
     * @param        $key
     * @param string $type
     *
     * @return string
     */
    public static function stringToSecretKey( $key , $type = '' )
    {
        // 64个英文字符后接换行符"\n",最后再接换行符"\n"
        $k = empty( $type ) ? "-----BEGIN PUBLIC KEY-----\n" : "-----BEGIN RSA PRIVATE KEY-----\n";
        foreach ( str_split( $key , 64 ) as $str ) {
            $k .= $str . "\n";
        }
        $k .= empty( $type ) ? "-----END PUBLIC KEY-----" : "-----END RSA PRIVATE KEY-----";
        return $k;
    }

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容