溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

php和openssl實(shí)現(xiàn)非對稱加密的案例

發(fā)布時間:2020-10-15 17:36:49 來源:億速云 閱讀:208 作者:小新 欄目:編程語言

這篇文章給大家分享的是有關(guān)php和openssl實(shí)現(xiàn)非對稱加密的案例的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個參考。一起跟隨小編過來看看吧。

<?php
namespace MyObjSummary;
/**
 * 使用openssl實(shí)現(xiàn)非對稱加密
 */
class Rsa
{
    /**
     * 私鑰
     * 
     */
    private $_privKey;

    /**
     * 公鑰
     * 
     */
    private $_pubKey;

    /** 保存文件地址
     * @var
     */
    private $_keyPath;

    /** 公鑰
     * @var string
     */
    private $_pubKeyLink = "-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCF4sz1eu4XgLeIK9Aiu4+rfglt
k1gmNhUytOtk3kbzPoy2XoR5sQIRXBYnIagwBVOLPWDacVJoqjfeK6xGvL17745u
Z7RubcZIW62ocgX3swIDAQAB
-----END PUBLIC KEY-----";
    /**私鑰
     * @var string
     */
    private $_priKeyLink = "-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQCF4sz1eu4XgLeIK9Aiu4+rfgltk1gmNhUytOtk3kbzPoy2XoR5
sQIRXBYnIagwBVOLPWDacVJoqjfeK6xGvL17745uwNSw3eKLl1qm+w2z5KhNEnpg
LWxKxSPMfekt1Aj3Te0Ct652Scr42Coca/ld2mGkZ7RubcZIW62ocgX3swIDAQAB
AoGAHinbvU6Fx5vDPZWJXdnd42gQ3bP9fxZeLj9ebSo61+B2uTuQIw6DBcA2aXiG
uNLqYItif7RaOaRn09EJDiLFmYwRBXAGnEdSnxWRy/IMrtKATV+dLnyFDVrIzsn+
/9l3HQXKhlSqTc4v7o1sWAM9GW2vjB3X432BjzbgqCyplOECQQC7UnvQUZYT+sum
PStREJt85krUKgeFwyQdji+BdAXhv9xz3PiSWsAvw87zFrpBKcWbTimSH38onKGa
htuYE08xAkEAtvjx7t05TiVusPcsgABxoABKRKZpcY5QQIXTT3oigvCMuz41nBDm
EXeot+TXBGwG0QNS7p5BwkrXfCFJJONkIwJAUbcItfZxPqQAJLO4arOQ8KpRaD4x
a+OVpKL7DEC9tB4LICv773RRNET5yUdX1sdPIZG2Rr0grmmtgYhk0PFTcQJBAI8I
uv2VL3fMBI4SGWWN/LPSeZkUdPbh0GmRCSo4nPOfxK8=
-----END RSA PRIVATE KEY-----";
    /**
     * Rsa constructor.
     * @param string $path
     */
    public function __construct($path='')
    {
        if (!empty($path)) {
            $this->_keyPath = $path;
        }
    }

    /**
     * 創(chuàng)建公鑰和私鑰
     * 
     */
    public function createKey()
    {
        $config = [
            "config" => 'D:\Min\Install\wamp\wamp64\bin\php\php5.6.25\extras\ssl\openssl.cnf',
            "digest_alg" => "sha512",
            "private_key_bits" => 4096,
            "private_key_type" => OPENSSL_KEYTYPE_RSA,

        ];
        // 生成私鑰
        $rsa = openssl_pkey_new($config);
        openssl_pkey_export($rsa, $privKey, NULL, $config);
        file_put_contents($this->_keyPath . DIRECTORY_SEPARATOR . 'priv.key', $privKey);
        $this->_privKey = openssl_pkey_get_public($privKey);
        // 生成公鑰
        $rsaPri = openssl_pkey_get_details($rsa);
        $pubKey = $rsaPri['key'];
        file_put_contents($this->_keyPath . DIRECTORY_SEPARATOR . 'pub.key', $pubKey);
        $this->_pubKey = openssl_pkey_get_public($pubKey);
    }

    /** 設(shè)置私鑰
     * @return bool
     */
    public function setupPrivKey()
    {
        if (is_resource($this->_privKey)) {
            return true;
        }
        //從文件中獲取
        /*$file = $this->_keyPath . DIRECTORY_SEPARATOR . 'priv.key';
        $privKey = file_get_contents($file);*/
        $privKey = $this->_priKeyLink;
        $this->_privKey = openssl_pkey_get_private($privKey);
        return true;
    }

    /** 設(shè)置公鑰
     * @return bool
     */
    public function setupPubKey()
    {
        //從文件中獲取
        /*$file = $this->_keyPath . DIRECTORY_SEPARATOR . 'pub.key';
        $pubKey = file_get_contents($file);*/
        //數(shù)據(jù)源
        $pubKey = $this->_pubKeyLink;
        $this->_pubKey = openssl_pkey_get_public($pubKey);
        return true;
    }

    /** 用私鑰加密
     * @param $data
     * @return null|string
     */
    public function privEncrypt($data)
    {
        if (!is_string($data)) {
            return null;
        }
        $this->setupPrivKey();
        $result = openssl_private_encrypt($data, $encrypted, $this->_privKey);
        if ($result) {
            return base64_encode($encrypted);
        }
        return null;
    }

    /** 私鑰解密
     * @param $encrypted
     * @return null
     */
    public function privDecrypt($encrypted)
    {
        if (!is_string($encrypted)) {
            return null;
        }
        $this->setupPrivKey();
        $encrypted = base64_decode($encrypted);
        $result = openssl_private_decrypt($encrypted, $decrypted, $this->_privKey);
        if ($result) {
            return $decrypted;
        }
        return null;
    }

    /** 公鑰加密
     * @param $data
     * @return null|string
     */
    public function pubEncrypt($data)
    {
        if (!is_string($data)) {
            return null;
        }
        $this->setupPubKey();
        $result = openssl_public_encrypt($data, $encrypted, $this->_pubKey);
        if ($result) {
            return base64_encode($encrypted);
        }
        return null;
    }

    /** 公鑰解密
     * @param $crypted
     * @return null
     */
    public function pubDecrypt($crypted)
    {
        if (!is_string($crypted)) {
            return null;
        }
        $this->setupPubKey();
        $crypted = base64_decode($crypted);
        $result = openssl_public_decrypt($crypted, $decrypted, $this->_pubKey);
        if ($result) {
            return $decrypted;
        }
        return null;
    }

    /** 私鑰簽名
     * @param $data
     * @return string
     */
    public function priKeySign($data)
    {
        if(!is_string($data)) return null;
        $private_key=openssl_get_privatekey($this->_priKeyLink);
        $original_str= $data ;//原數(shù)據(jù)
        openssl_sign($original_str,$sign,$private_key);
        openssl_free_key($private_key);
        $sign=base64_encode($sign);//最終的簽名
        return $sign ;
    }

    /** 公鑰驗(yàn)簽
     * @param $sign
     * @param $data
     * @return bool
     */
    public  function pubKeyCheck($sign,$data)
    {
        if(!is_string($sign) || !is_string($data)) return null;
        $public_key=openssl_get_publickey($this->_pubKeyLink);
        $sign=base64_decode($sign);//得到的簽名
        $original_str=$data;
        $result=(bool)openssl_verify($original_str,$sign,$public_key);
        openssl_free_key($public_key);
        return $result ;
    }

    /**
     * __destruct
     * 
     */
    public function __destruct() {
        @fclose($this->_privKey);
        @fclose($this->_pubKey);
    }
}
$rsa = new Rsa();

echo "openssl_private_encrypt,openssl_public_decrypt","<br />";
//私鑰加密,公鑰解密
echo "私鑰加密,公鑰驗(yàn)簽","<br />";
echo "待加密數(shù)據(jù):testInfo","<br />";
$pre = $rsa->privEncrypt("testInfo");
echo "加密后的密文:<br />" . $pre . "<br />";
$pud = $rsa->pubDecrypt($pre);
echo "解密后數(shù)據(jù):" . $pud . "<br />";
echo "<hr>";


//公鑰加密,私鑰解密
echo "openssl_public_encrypt,openssl_private_decrypt","<br />";
echo "公鑰加密,私鑰驗(yàn)簽","<br />";
echo "待加密數(shù)據(jù):ssh-test","<br />";
$pue = $rsa->pubEncrypt("ssh-test");
echo "加密后的密文:","<br />" . $pue . "<br />";
$prd = $rsa->privDecrypt($pue);
echo "解密后數(shù)據(jù):" . $prd;

echo "<hr>";echo "<hr>";

echo "openssl_sign,openssl_verify","<br />";
echo "私鑰簽名,公鑰驗(yàn)簽","<br />";
echo "待加密數(shù)據(jù):test=32","<br />";
$pre = $rsa->priKeySign('test=32');
echo "加密后的密文:","<br />" . $pre . "<br />";
$pud = $rsa->pubKeyCheck($pre,'test=32');
echo "是否解密成功:" . $pud . "<br />";
echo "<hr>";

感謝各位的閱讀!關(guān)于php和openssl實(shí)現(xiàn)非對稱加密的案例就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

php
AI