search
HomeBackend DevelopmentPHP TutorialCode examples for implementing asymmetric encryption using php and openssl

The content of this article is about the code examples of asymmetric encryption implemented by PHP and openssl. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

<?php namespace MyObjSummary;
/**
 * 使用openssl实现非对称加密
 */
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=&#39;&#39;)
    {
        if (!empty($path)) {
            $this->_keyPath = $path;
        }
    }

    /**
     * 创建公钥和私钥
     * 
     */
    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);
    }

    /** 设置私钥
     * @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;
    }

    /** 设置公钥
     * @return bool
     */
    public function setupPubKey()
    {
        //从文件中获取
        /*$file = $this->_keyPath . DIRECTORY_SEPARATOR . 'pub.key';
        $pubKey = file_get_contents($file);*/
        //数据源
        $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 ;//原数据
        openssl_sign($original_str,$sign,$private_key);
        openssl_free_key($private_key);
        $sign=base64_encode($sign);//最终的签名
        return $sign ;
    }

    /** 公钥验签
     * @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 "私钥加密,公钥验签","<br>";
echo "待加密数据:testInfo","<br>";
$pre = $rsa->privEncrypt("testInfo");
echo "加密后的密文:<br>" . $pre . "<br>";
$pud = $rsa->pubDecrypt($pre);
echo "解密后数据:" . $pud . "<br>";
echo "<hr>";


//公钥加密,私钥解密
echo "openssl_public_encrypt,openssl_private_decrypt","<br>";
echo "公钥加密,私钥验签","<br>";
echo "待加密数据:ssh-test","<br>";
$pue = $rsa->pubEncrypt("ssh-test");
echo "加密后的密文:","<br>" . $pue . "<br>";
$prd = $rsa->privDecrypt($pue);
echo "解密后数据:" . $prd;

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

echo "openssl_sign,openssl_verify","<br>";
echo "私钥签名,公钥验签","<br>";
echo "待加密数据:test=32","<br>";
$pre = $rsa->priKeySign('test=32');
echo "加密后的密文:","<br>" . $pre . "<br>";
$pud = $rsa->pubKeyCheck($pre,'test=32');
echo "是否解密成功:" . $pud . "<br>";
echo "<hr>";

The above is the detailed content of Code examples for implementing asymmetric encryption using php and openssl. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

What is the importance of setting the httponly flag for session cookies?What is the importance of setting the httponly flag for session cookies?May 03, 2025 am 12:10 AM

Setting the httponly flag is crucial for session cookies because it can effectively prevent XSS attacks and protect user session information. Specifically, 1) the httponly flag prevents JavaScript from accessing cookies, 2) the flag can be set through setcookies and make_response in PHP and Flask, 3) Although it cannot be prevented from all attacks, it should be part of the overall security policy.

What problem do PHP sessions solve in web development?What problem do PHP sessions solve in web development?May 03, 2025 am 12:02 AM

PHPsessionssolvetheproblemofmaintainingstateacrossmultipleHTTPrequestsbystoringdataontheserverandassociatingitwithauniquesessionID.1)Theystoredataserver-side,typicallyinfilesordatabases,anduseasessionIDstoredinacookietoretrievedata.2)Sessionsenhances

What data can be stored in a PHP session?What data can be stored in a PHP session?May 02, 2025 am 12:17 AM

PHPsessionscanstorestrings,numbers,arrays,andobjects.1.Strings:textdatalikeusernames.2.Numbers:integersorfloatsforcounters.3.Arrays:listslikeshoppingcarts.4.Objects:complexstructuresthatareserialized.

How do you start a PHP session?How do you start a PHP session?May 02, 2025 am 12:16 AM

TostartaPHPsession,usesession_start()atthescript'sbeginning.1)Placeitbeforeanyoutputtosetthesessioncookie.2)Usesessionsforuserdatalikeloginstatusorshoppingcarts.3)RegeneratesessionIDstopreventfixationattacks.4)Considerusingadatabaseforsessionstoragei

What is session regeneration, and how does it improve security?What is session regeneration, and how does it improve security?May 02, 2025 am 12:15 AM

Session regeneration refers to generating a new session ID and invalidating the old ID when the user performs sensitive operations in case of session fixed attacks. The implementation steps include: 1. Detect sensitive operations, 2. Generate new session ID, 3. Destroy old session ID, 4. Update user-side session information.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),