設計說明
- 算法:AES-128 / CBC / NoPadding(RIJNDAEL_128);
- 密鑰長度:16 字節(128 位),兼容 Java 僅支援 128 位;
- IV 生成:
substr(md5($key), 0, 16);
- 輸出:加密結果
base64_encode,解密先 base64_decode;
- 依賴:PHP
mcrypt 擴展(PHP 7.1+ 棄用,建議遷移至 OpenSSL/Sodium)。
完整類代碼
params['encryptKey'] : $key, 0, mcrypt_enc_get_key_size($module));
$iv = substr(md5($key), 0, mcrypt_enc_get_iv_size($module));
mcrypt_generic_init($module, $key, $iv);
$encrypted = mcrypt_generic($module, $plaintext);
mcrypt_generic_deinit($module);
mcrypt_module_close($module);
return base64_encode($encrypted);
}
public static function AesDecrypt($encrypted, $key = null) {
if ($encrypted === '') return '';
if (!extension_loaded('mcrypt'))
throw new Exception('mcrypt extension required');
$ciphertext_dec = base64_decode($encrypted);
$module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
$key = self::substr($key === null ? Yii::app()->params['encryptKey'] : $key, 0, mcrypt_enc_get_key_size($module));
$iv = substr(md5($key), 0, mcrypt_enc_get_iv_size($module));
mcrypt_generic_init($module, $key, $iv);
$decrypted = mdecrypt_generic($module, $ciphertext_dec);
mcrypt_generic_deinit($module);
mcrypt_module_close($module);
return rtrim($decrypted, "\0");
}
private static function strlen($string) {
return extension_loaded('mbstring') ? mb_strlen($string, '8bit') : strlen($string);
}
private static function substr($string, $start, $length) {
return extension_loaded('mbstring') ? mb_substr($string, $start, $length, '8bit') : substr($string, $start, $length);
}
}
使用說明
- 非 Yii 環境:將
Yii::app()->params['encryptKey'] 替換為項目配置的默認密鑰;
- Java 端需使用
AES/CBC/NoPadding 模式,IV 同樣取 MD5(key)[0:16];
- PHP 7.1+ 專案建議改用
openssl_encrypt / sodium_crypto_aead_aes256gcm_encrypt 替代 mcrypt。