evit / php-gm-crypto

完全兼容openssl的sm4-cbc和sm4-ecb国家秘密SM算法。当openssl >= 1.1.1支持国家秘密算法时,直接调用openssl进行SM4加密和解密,否则调用自定义算法。

1.0.4 2023-06-02 03:13 UTC

This package is auto-updated.

Last update: 2024-10-01 00:14:43 UTC


README

  • PHP后端:composer require evit/php-gm-crypto
  • 对应前端:npm install evit-gm-crypt

php-gm-crypto

PHP Style GuideLicense: MIT

基于PHP的国家加密算法实现。

在PHP中实现中国加密算法。

完全兼容openssl的sm4-cbc和sm4-ecb国家秘密SM算法,openssl >= 1.1.1支持国家秘密算法时直接调用openssl进行SM4加解密,否则调用自定义算法。

完全兼容openssl的sm4-cbc和sm4-ecb国家秘密SM算法。当openssl >= 1.1.1支持国家秘密算法时,直接调用openssl进行SM4加密和解密,否则调用自定义算法。

新增SM3实现,openssl >= 1.1.1支持国家秘密算法时直接调用openssl进行SM3杂凑,否则调用自定义算法。

openssl_encryptopenssl_decrypt保持一致性,当密码长度小于16时,静默填充NUL;当密码长度大于16时,静默截断。

与openssl_encrypt和openssl_decrypt保持一致,当密码长度小于16时,静默填充NUL;当密码长度大于16时,静默截断。

要使用openssl国家秘密算法,openssl库需 >= 1.1.1。

要使用openssl国家秘密算法,openssl库需 >= 1.1.1。

路线图

  • SM4
  • SM3
  • SM2

文档

安装

composer require evit/php-gm-crypto

SM4

初始化

<?php
// If you are using a framework that does not support psr-4 autoloader, you need to explicitly import package from the vendor directory.
require_once __DIR__ . "/vendor/autoload.php";

use Evit\PhpGmCrypto\Encryption\EvitSM4Encryption;

$config = [
    // mode string 'cbc' or 'ecb' is supported, default is 'cbc'.
    'mode'  => 'cbc',
    // password, will be processed by substr(md5($key), 0, 16) if $config['hash']
    'key'   => '{replace-your-key-here}',
    // the iv used by 'cbc' mode, will be will be processed by substr(md5($iv), 0, 16) if $config['hash']
    'iv'    => '{replace-your-iv-here}',
    // weather do md5 to key and iv or not
    'hash'  => false
];

$sm4 = new EvitSM4Encryption($config);

加密

// Encrypt
$start = microtime(true);
$encypted = $sm4->sm4encrypt('{replace-your-plaintext-here}');
$end = microtime(true);
var_dump('Encrypt time elapsed:' . number_format($end - $start, 8) . ' s');
var_dump("Cipher text:{$encypted}");

解密

// Decrypt
$decStart = microtime(true);
$decrypted = $sm4->sm4decrypt($encypted);
$end = microtime(true);
var_dump('Decrypt time elapsed:' . number_format($end - $decStart, 8) . ' s');
var_dump("Plain text:{$decrypted}");

算法

// Determine whether openssl library is used
$algorithm = $sm4->isOpenssl() ? 'openssl' : 'php-gm-crypto';
var_dump("Algrithm is:{$algorithm}");
var_dump('Total time elapsed:' . number_format($end - $start, 8) . ' s');

SM3

// If you are using a framework that does not support psr-4 autoloader, you need to explicitly import package from the vendor directory.
require_once __DIR__ . "/vendor/autoload.php";

use Evit\PhpGmCrypto\Encryption\EvitSM3Encryption;

$sm3 = new EvitSM3Encryption();
$input = 'abc';

$output = $sm3->sm3($input);
var_dump("SM3 hash result of '{$input}' is '{$output}'");

对应的前端安装

npm install evit-gm-crypt

传送门:evit-gm-crypt

许可

MIT