Home  >  Article  >  Backend Development  >  Example sharing of RSA2 signature algorithm in php

Example sharing of RSA2 signature algorithm in php

黄舟
黄舟Original
2017-09-08 09:39:231991browse

RSA2 is based on the original SHA1WithRSA signature algorithm and adds a new signature algorithm that supports SHA256WithRSA.

This algorithm has stronger security capabilities than SHA1WithRSA in terms of digest algorithm.

The SHA1WithRSA signature algorithm will continue to be supported, but for the security of your application, it is strongly recommended to use the SHA256WithRSA signature algorithm.

RSA Class

<?php
/**
 * Created by PhpStorm.
 * User: webff
 * Date: 2017/5/12
 * Time: 20:03
 */class Rsa2
{    
private static $PRIVATE_KEY ="私钥内容";    
private static $PUBLIC_KEY  ="公钥内容";    
/**
     * 获取私钥
     * @return bool|resource
     */
    private static function getPrivateKey()
    {
        $privKey = self::$PRIVATE_KEY;        
        return openssl_pkey_get_private($privKey);
    }    
    /**
     * 获取公钥
     * @return bool|resource
     */
    private static function getPublicKey()
    {

        $publicKey = self::$PUBLIC_KEY;        
        return openssl_pkey_get_public($publicKey);
    }    /**
     * 创建签名
     * @param string $data 数据
     * @return null|string
     */
    public function createSign($data = &#39;&#39;)
    {      //  var_dump(self::getPrivateKey());die;
        if (!is_string($data)) {            
        return null;
        }        
        return openssl_sign($data, $sign, self::getPrivateKey(),OPENSSL_ALGO_SHA256 ) ? base64_encode($sign) : null;
    }    
    /**
     * 验证签名
     * @param string $data 数据
     * @param string $sign 签名
     * @return bool
     */
    public function verifySign($data = &#39;&#39;, $sign = &#39;&#39;)
    {        
    if (!is_string($sign) || !is_string($sign)) {            
    return false;
        }        
        return (bool)openssl_verify(
            $data,
            base64_decode($sign),
            self::getPublicKey(),
            OPENSSL_ALGO_SHA256
        );
    }
}

PHP Call

$rsa2 = new Rsa2();$data = &#39;mydata&#39;; //待签名字符串
$strSign = $rsa2->createSign($data);      //生成签名
$is_ok = $rsa2->verifySign($data, $strSign); //验证签名

The above is the detailed content of Example sharing of RSA2 signature algorithm in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn