PHP的gmssl庫是一個基于國密算法(SM2、SM3、SM4)的加密庫,它提供了一系列的加密、解密、簽名和驗證等功能。以下是一些使用PHP gmssl庫的示例:
<?php
require_once 'vendor/autoload.php';
use Gmssl\SM2;
$sm2 = new SM2();
$keyPair = $sm2->generateKeyPair();
echo "公鑰: " . $keyPair['publicKey'] . "\n";
echo "私鑰: " . $keyPair['privateKey'] . "\n";
?>
<?php
require_once 'vendor/autoload.php';
use Gmssl\SM2;
$sm2 = new SM2();
$keyPair = $sm2->generateKeyPair();
$publicKey = $keyPair['publicKey'];
$privateKey = $keyPair['privateKey'];
$data = "Hello, world!";
$encryptedData = $sm2->encrypt($data, $publicKey);
echo "加密后的數據: " . $encryptedData . "\n";
$decryptedData = $sm2->decrypt($encryptedData, $privateKey);
echo "解密后的數據: " . $decryptedData . "\n";
?>
<?php
require_once 'vendor/autoload.php';
use Gmssl\SM2;
$sm2 = new SM2();
$keyPair = $sm2->generateKeyPair();
$publicKey = $keyPair['publicKey'];
$privateKey = $keyPair['privateKey'];
$data = "Hello, world!";
$signature = $sm2->sign($data, $privateKey);
echo "簽名: " . $signature . "\n";
$isValid = $sm2->verify($data, $signature, $publicKey);
echo "驗證簽名: " . ($isValid ? "有效" : "無效") . "\n";
?>
<?php
require_once 'vendor/autoload.php';
use Gmssl\SM3;
$sm3 = new SM3();
$data = "Hello, world!";
$hash = $sm3->hash($data);
echo "哈希值: " . $hash . "\n";
?>
<?php
require_once 'vendor/autoload.php';
use Gmssl\SM4;
$sm4 = new SM4();
$key = '0123456789abcdeffedcba9876543210'; // 16字節的密鑰
$data = "Hello, world!";
$encryptedData = $sm4->encrypt($data, $key);
echo "加密后的數據: " . $encryptedData . "\n";
$decryptedData = $sm4->decrypt($encryptedData, $key);
echo "解密后的數據: " . $decryptedData . "\n";
?>
請注意,這些示例需要先安裝PHP的gmssl庫。你可以通過Composer來安裝:
composer require gmssl/gmssl