composer插件之----phpseclib\Crypt加密

安装

composer require phpseclib/phpseclib

1.RSA

新建密钥对:

$rsa = new RSA();
$result = $rsa->createKey();
echo $result["privatekey"]    //私钥
$result["publickey"]    //公钥

加密:

$rsa = new RSA();
$rsa->loadKey($key); 
$rsa->setEncryptionMode(RSA::ENCRYPTION_NONE);    //选择加密的模式,可选模式参考官方文档
 
echo base64_encode($rsa->encrypt($msg));    //需要对结果进行base64转码,否则为乱码

解密:

$rsa = new RSA();
$rsa->loadKey($key);
$rsa->setEncryptionMode(RSA::ENCRYPTION_PKCS1);
echo $rsa->decrypt(base64_decode($msg));    //同理,解码时,需要先进行base64

解码

目前笔者测试能和PHPSeclib的 RSA配合的javascript包为: https://github.com/rzcoder/node-rsa 2.AES

加密:

$aes = new AES(MCRYPT_MODE_ECB);
$aes->setKey(self::KEY);
$aes->setIV(self::VECTOR);
echo base64_encode($aes->encrypt($msg));

解密:

$aes = new AES(MCRYPT_MODE_ECB);
$aes->setKey(self::KEY);
$aes->setIV(self::VECTOR);
echo $aes->decrypt(base64_decode($msg));
<?php
namespace common;
 
use phpseclib\Crypt\RSA;
use phpseclib\Crypt\AES;
 
class AuthTools
{
    /** 生成rsa密钥对
     * @return array privatekey,publickey
     */
    public static function rsaCreateKey()
    {
        $rsa = new RSA();
        $key = $rsa->createKey();
        return $key;
    }
 
    /** sa加密
     * @param $string
     * @param $key
     * @return string
     */
    public static function rsaEncrypt($string, $key)
    {
        $rsa = new RSA();
        $rsa->loadKey($key);
        $rsa->setEncryptionMode(RSA::ENCRYPTION_NONE);    //选择加密的模式
        return base64_encode($rsa->encrypt($string));    //需要对结果进行base64转码
    }
 
    /** rsa解密
     * @param $encryptStr
     * @param $key
     * @return mixed
     */
    public static function rsaDecrypt($encryptStr, $key)
    {
        $rsa = new RSA();
        $rsa->loadKey($key);
        $rsa->setEncryptionMode(RSA::ENCRYPTION_NONE);
        return $rsa->decrypt(base64_decode($encryptStr));
    }
 
    /** 随机字符串作为aes key
     * @param int $len
     * @return string
     */
    public static function aesCreateKey($len = 16)
    {
        return \phpseclib\Crypt\Random::string($len);
    }
 
    /** aes加密
     * @param $string
     * @param $aesKey
     * @return string
     */
    public static function aesEncrypt($string, $aesKey)
    {
        $aes = new AES();
        $aes->setKey($aesKey);
        return base64_encode($aes->encrypt($string));
    }
 
    /** aes解密
     * @param $encryptStr
     * @param $aesKey
     * @return string
     */
    public static function aesDecrypt($encryptStr, $aesKey)
    {
        $aes = new AES();
        $aes->setKey($aesKey);
        return $aes->decrypt(base64_decode($encryptStr));
    }
}

作者:会奔跑的羚羊 链接:https://www.jianshu.com/p/c7217576afa3 来源:简书 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

EJR博客
请先登录后发表评论
  • latest comments
  • 总共0条评论