blazemv/cryptx

用于使用私钥和公钥PEM文件加密和解密数据的简单PHP库

v1.1 2020-12-27 15:06 UTC

This package is auto-updated.

Last update: 2024-09-27 23:27:45 UTC


README

用于使用私钥和公钥PEM文件加密和解密数据的简单PHP库

要求

  • PHP 7.2 或更高版本
  • openssl PHP 扩展

安装

$ composer require blazemv/cryptx

用法

$ php artisan vendor:publish --provider="Blaze\Cryptx\CryptxServiceProvider"

$ php artisan cryptx:keys

Laravel

//anywhere in your app
$encrypted = \Cryptx::encrypt("My Secret String");
$decrypted = \Cryptx::decrypt($encrypted);

非Laravel

<?php

require_once 'vendor/autoload.php';

use Blaze\Cryptx\Cryptx;

// generate keys
$privateKeyPath = 'private.pem';
$publicKeyPath = 'public.pem';

if (!file_exists($publicKeyPath)) {
    $tempCryptx = new Cryptx();
    $keyPair = $tempCryptx->generateKeyPair();
    $privateKey = $tempCryptx->extractPrivateKey($keyPair);
    $publicKey = $tempCryptx->extractPublicKey($keyPair);

    file_put_contents($privateKeyPath, $privateKey);
    file_put_contents($publicKeyPath, $publicKey);
}

// usage
$cryptx = new Cryptx($privateKeyPath, $publicKeyPath);
$cryptx = new Cryptx($privateKeyPath, $publicKeyPath);
$encrypted = $cryptx->encrypt("My Secret String");
$decrypted = $cryptx->decrypt($encrypted);
echo "encrypted => $encrypted\r\n";
echo "decrypted => $decrypted\r\n";

重要

  • 加密方法将返回加密数据的base64编码字符串。
  • 解密方法将期望一个加密数据的base64编码字符串。
  • 您可以通过将两个方法的第二个参数都传递为false来避免base64编码和解码。
  • 需要私钥来编码数据。
  • 需要公钥来解密编码数据。公钥应从用于加密的私钥派生。
  • 将私钥和公钥路径传递给Cryptx构造函数。对于Laravel,在config/cryptx.php中声明这些路径。
  • 如果只想解密数据,私钥路径可以是null。提供正确的公钥路径。
  • 解密方法在失败时将返回false。(例如:不正确的公钥、无效的加密负载等...)。
  • 强烈建议使用绝对路径作为密钥路径。