43 lines
1.0 KiB
PHP
43 lines
1.0 KiB
PHP
<?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;
|
||
}
|
||
|
||
} |