一、Composer 下载 phpseclib
composer require phpseclib/phpseclib
二、RSA 加密解密
use phpseclib3\ Crypt\ RSA ; $type = 'PKCS8' ;
$rsaObj = RSA :: createKey ( ) ;
$rsa_public = $rsaObj -> getPublicKey ( ) ;
$private_key = $rsaObj -> toString ( $type ) ;
$public_key = $rsa_public -> toString ( $type ) ; $plaintext = '测试加密文本' ;
$ciphertext = $rsa_public -> encrypt ( $plaintext ) ;
echo $rsaObj -> decrypt ( $ciphertext ) ;
$rsa_public_obj = RSA :: loadPublicKey ( $public_key ) ;
$plaintext = '测试加密文本' ;
$ciphertext = base64_encode ( $rsa_public_obj -> encrypt ( $plaintext ) ) ;
$rsa_private_obj = RSA :: loadPrivateKey ( $private_key ) ;
$text = $rsa_private_obj -> decrypt ( base64_decode ( $ciphertext ) ) ;
三、DES 加密解密
use phpseclib3\ Crypt\ DES ;
$token_data = [ 'status' => 1 , 'expire_time' => 2024 - 08 - 01 12 : 00 : 00
] ; $type = 'ecb' ;
$key = 'HF@w2f#1' ;
$des_obj = new DES ( $type ) ;
$des_obj -> setKey ( $key ) ;
$token = base64_encode ( $des_obj -> encrypt ( json_encode ( $token_data ) ) ) ;
$token_decode = json_decode ( $des_obj -> decrypt ( base64_decode ( $token ) ) , true ) ;