PHP

php gmssl库的使用案例有哪些

小樊
136
2024-09-09 02:07:11
栏目: 云计算

PHP的gmssl库是一个基于国密算法(SM2、SM3、SM4)的加密库,它提供了一系列的加密、解密、签名和验证等功能。以下是一些使用PHP gmssl库的示例:

  1. 生成SM2密钥对
<?php
require_once 'vendor/autoload.php';
use Gmssl\SM2;

$sm2 = new SM2();
$keyPair = $sm2->generateKeyPair();
echo "公钥: " . $keyPair['publicKey'] . "\n";
echo "私钥: " . $keyPair['privateKey'] . "\n";
?>
  1. SM2加密和解密
<?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";
?>
  1. SM2签名和验证
<?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";
?>
  1. SM3哈希计算
<?php
require_once 'vendor/autoload.php';
use Gmssl\SM3;

$sm3 = new SM3();
$data = "Hello, world!";
$hash = $sm3->hash($data);
echo "哈希值: " . $hash . "\n";
?>
  1. SM4加密和解密
<?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

0
看了该问题的人还看了