本文目录导读:

- 基础方案:使用
base64简单加密(不推荐生产环境) - 推荐方案:使用 OpenSSL 加密
- 使用 PHP 扩展:Sodium(PHP 7.2+ 内置)
- 使用环境变量 + .env 文件(最推荐实际项目)
- 完整生产方案:配置管理器类
- 安全注意事项
- 推荐方案选择
在 PHP 中实现配置加密,主要有几种常见场景和对应方法,我帮你梳理下最实用的方案:
基础方案:使用 base64 简单加密(不推荐生产环境)
<?php
// 加密配置
$config = [
'db_host' => 'localhost',
'db_user' => 'admin',
'db_pass' => 'password123'
];
// 编码
$encoded = base64_encode(serialize($config));
file_put_contents('config.enc', $encoded);
// 解码使用
$decoded = unserialize(base64_decode(file_get_contents('config.enc')));
?>
缺点:这只是编码,不是真正加密,很容易被破解。
推荐方案:使用 OpenSSL 加密
加密配置
<?php
// 生成密钥(只需要执行一次)
$key = random_bytes(32); // 256位密钥
file_put_contents('secret.key', base64_encode($key));
// 加密配置
function encrypt_config($data, $key) {
$iv = random_bytes(16); // 初始化向量
$encrypted = openssl_encrypt(
json_encode($data),
'aes-256-cbc',
$key,
OPENSSL_RAW_DATA,
$iv
);
return base64_encode($iv . $encrypted);
}
// 使用示例
$config = [
'db_host' => 'localhost',
'db_port' => 3306,
'db_user' => 'root',
'db_pass' => 'secret_password',
'api_key' => 'your-api-key-here'
];
$key = base64_decode(file_get_contents('secret.key'));
$encrypted_config = encrypt_config($config, $key);
file_put_contents('config.encrypted', $encrypted_config);
?>
解密使用
<?php
function decrypt_config($encrypted_data, $key) {
$data = base64_decode($encrypted_data);
$iv = substr($data, 0, 16);
$encrypted = substr($data, 16);
$decrypted = openssl_decrypt(
$encrypted,
'aes-256-cbc',
$key,
OPENSSL_RAW_DATA,
$iv
);
return json_decode($decrypted, true);
}
// 加载配置
$key = base64_decode(file_get_contents('secret.key'));
$config = decrypt_config(file_get_contents('config.encrypted'), $key);
// 使用配置
echo $config['db_host']; // localhost
?>
使用 PHP 扩展:Sodium(PHP 7.2+ 内置)
<?php
// 生成密钥
$key = sodium_crypto_secretbox_keygen();
file_put_contents('sodium.key', base64_encode($key));
// 加密
function encrypt_sodium($data, $key) {
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$ciphertext = sodium_crypto_secretbox(
json_encode($data),
$nonce,
$key
);
return base64_encode($nonce . $ciphertext);
}
// 解密
function decrypt_sodium($encrypted, $key) {
$data = base64_decode($encrypted);
$nonce = substr($data, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$ciphertext = substr($data, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$decrypted = sodium_crypto_secretbox_open($ciphertext, $nonce, $key);
return json_decode($decrypted, true);
}
?>
使用环境变量 + .env 文件(最推荐实际项目)
创建 .env 文件(不上传到 Git)
DB_HOST=localhost DB_USER=root DB_PASS=secret123 API_KEY=your-api-key
使用 PHP 读取
<?php
// 使用 vlucas/phpdotenv 包(Composer 安装)
require 'vendor/autoload.php';
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
// 或者手动解析
function load_env($file) {
if (!file_exists($file)) return;
$lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
if (strpos(trim($line), '#') === 0) continue;
list($name, $value) = explode('=', $line, 2);
putenv("$name=$value");
$_ENV[$name] = $value;
}
}
load_env('.env');
$db_pass = getenv('DB_PASS');
?>
完整生产方案:配置管理器类
<?php
class ConfigManager {
private static $instance = null;
private $config = [];
private $key;
private function __construct() {
$this->key = $this->loadKey();
$this->loadConfig();
}
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
private function loadKey() {
// 密钥最好存储在环境变量或安全的位置
$key = getenv('APP_CONFIG_KEY');
if (!$key) {
throw new Exception('Config encryption key not found');
}
return base64_decode($key);
}
private function loadConfig() {
if (file_exists('config.encrypted')) {
$this->config = $this->decrypt(file_get_contents('config.encrypted'));
} else {
// 默认配置
$this->config = $this->getDefaultConfig();
}
}
public function get($key, $default = null) {
return $this->config[$key] ?? $default;
}
public function set($key, $value) {
$this->config[$key] = $value;
}
public function save() {
$encrypted = $this->encrypt($this->config);
file_put_contents('config.encrypted', $encrypted);
}
private function encrypt($data) {
$iv = random_bytes(16);
$encrypted = openssl_encrypt(
serialize($data),
'aes-256-cbc',
$this->key,
OPENSSL_RAW_DATA,
$iv
);
return base64_encode($iv . $encrypted);
}
private function decrypt($data) {
$data = base64_decode($data);
$iv = substr($data, 0, 16);
$encrypted = substr($data, 16);
return unserialize(openssl_decrypt(
$encrypted,
'aes-256-cbc',
$this->key,
OPENSSL_RAW_DATA,
$iv
));
}
private function getDefaultConfig() {
return [
'app_name' => 'MyApp',
'debug' => false,
// 其他默认配置
];
}
}
// 使用示例
$config = ConfigManager::getInstance();
echo $config->get('db_host');
$config->set('api_key', 'new-key');
$config->save(); // 保存加密后的配置
?>
安全注意事项
- 永远不要将密钥和加密文件一起提交到版本控制
- 密钥建议存储在环境变量或独立的密钥管理服务中
- 使用强加密算法(AES-256-CBC 或 Sodium)
- 定期轮换密钥
- 考虑使用专业的密钥管理服务(AWS KMS、HashiCorp Vault等)
推荐方案选择
- 开发环境:使用
.env文件 - 小型项目:OpenSSL 加密 + 密钥文件
- 生产环境:环境变量 + 外部密钥管理服务
- 微服务/云环境:AWS Secrets Manager / Azure Key Vault
最简单的生产方案是使用环境变量,配合 .env 文件管理开发配置,生产环境通过运维平台注入真实配置。