Files
annnj-company 130c1026c4 first commit
2026-04-17 18:29:53 +08:00

43 lines
1.0 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace app\lib;
class MySm4 {
public function __construct($key) {
$this->key = $key;
}
/**
* 加密
* @param $plaintext
* @return string
*/
public function encrypt($plaintext) {
// 将密钥从十六进制转换为二进制
$key = hex2bin($this->key);
// 使用OpenSSL进行SM4加密这里使用ECB模式
$ciphertext = openssl_encrypt($plaintext, 'sm4-ecb', $key, OPENSSL_RAW_DATA);
// 返回加密后的密文
return bin2hex($ciphertext);
}
/**
* 解密
* @param $ciphertext
* @return false|string
*/
public function decrypt($ciphertext) {
// 将密钥从十六进制转换为二进制
$key = hex2bin($this->key);
// 将密文从十六进制转换为二进制
$ciphertext = hex2bin($ciphertext);
// 使用OpenSSL进行SM4解密
$plaintext = openssl_decrypt($ciphertext, 'sm4-ecb', $key, OPENSSL_RAW_DATA);
// 返回解密后的明文
return $plaintext;
}
}