$algorithmName, 'key' => $key, 'options' => OPENSSL_RAW_DATA, 'iv' => '' // ECB模式不需要IV ]; } /** * 生成SM4密钥 * @param int $keySize 密钥大小 * @return string 随机密钥 */ public static function generateKey($keySize = self::DEFAULT_KEY_SIZE) { return openssl_random_pseudo_bytes($keySize / 8); } /** * SM4 ECB模式加密 * @param string $hexKey 16进制密钥 * @param string $paramStr 待加密字符串 * @return string 16进制加密结果 */ public static function encryptEcb($hexKey, $paramStr) { $key = hex2bin($hexKey); $srcData = $paramStr; $cipherParams = self::generateEcbCipher(self::ALGORITHM_NAME_ECB_PADDING, OPENSSL_ENCRYPT, $key); $cipherArray = openssl_encrypt($srcData, $cipherParams['cipher'], $cipherParams['key'], $cipherParams['options'], $cipherParams['iv']); return bin2hex($cipherArray); } /** * SM4 ECB模式加密(字节数组接口) * @param string $data 待加密数据 * @param string $key 密钥 * @return string 加密结果 */ public static function encrypt_Ecb($data, $key) { $cipherParams = self::generateEcbCipher(self::ALGORITHM_NAME_ECB_PADDING, OPENSSL_ENCRYPT, $key); return openssl_encrypt($data, $cipherParams['cipher'], $cipherParams['key'], $cipherParams['options'], $cipherParams['iv']); } /** * SM4 ECB模式解密 * @param string $hexKey 16进制密钥 * @param string $cipherText 16进制加密字符串 * @return string 解密后的字符串 */ public static function decryptEcb($hexKey, $cipherText) { $key = hex2bin($hexKey); $cipherData = hex2bin($cipherText); $cipherParams = self::generateEcbCipher(self::ALGORITHM_NAME_ECB_PADDING, OPENSSL_DECRYPT, $key); $srcData = openssl_decrypt($cipherData, $cipherParams['cipher'], $cipherParams['key'], $cipherParams['options'], $cipherParams['iv']); return $srcData; } /** * SM4 ECB模式解密(字节数组接口) * @param string $cipherText 加密数据 * @param string $key 密钥 * @return string 解密结果 */ public static function decrypt_Ecb($cipherText, $key) { $cipherParams = self::generateEcbCipher(self::ALGORITHM_NAME_ECB_PADDING, OPENSSL_DECRYPT, $key); return openssl_decrypt($cipherText, $cipherParams['cipher'], $cipherParams['key'], $cipherParams['options'], $cipherParams['iv']); } /** * 验证加密前后的字符串是否为同一数据 * @param string $hexKey 16进制密钥 * @param string $cipherText 16进制加密后的字符串 * @param string $paramStr 加密前的字符串 * @return bool 是否为同一数据 */ public static function verifyEcb($hexKey, $cipherText, $paramStr) { $decryptStr = self::decryptEcb($hexKey, $cipherText); return $decryptStr === $paramStr; } }