Sodium 扩展
Libsodium 是一个现代、易用的加密库,PHP 7.2+ 通过 Sodium 扩展(ext-sodium)提供原生支持。它提供了经过安全审计的加密原语,包括对称加密、非对称加密、签名和密码哈希,是 PHP 中推荐使用的高级加密扩展。
前置知识
阅读本节前,建议先了解:OpenSSL 扩展、密码散列算法
对称加密 (Secretbox)
php
<?php
declare(strict_types=1);
// Sodium Secretbox (XSalsa20-Poly1305)
$key = sodium_crypto_secretbox_keygen();
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$plaintext = '这是一段需要加密的敏感数据';
$ciphertext = sodium_crypto_secretbox($plaintext, $nonce, $key);
// 解密
$decrypted = sodium_crypto_secretbox_open($ciphertext, $nonce, $key);
if ($decrypted === false) {
throw new RuntimeException("解密失败或数据被篡改");
}
echo "解密结果: {$decrypted}" . PHP_EOL;非对称加密 (Box)
php
<?php
declare(strict_types=1);
// 生成密钥对
$keyPair = sodium_crypto_box_keypair();
$publicKey = $keyPair['publicKey']; // 32 字节
$secretKey = $keyPair['secretKey']; // 32 字节
// 发送方使用接收方公钥加密
$nonce = random_bytes(SODIUM_CRYPTO_BOX_NONCEBYTES);
$encrypted = sodium_crypto_box('Hello World', $nonce, $publicKey, $secretKey);
// 接收方使用发送方公钥和自己的私钥解密
$decrypted = sodium_crypto_box_open($encrypted, $nonce, $publicKey, $secretKey);数字签名 (Sign)
php
<?php
declare(strict_types=1);
// Ed25519 签名
$keyPair = sodium_crypto_sign_keypair();
$publicKey = $keyPair['publicKey'];
$secretKey = $keyPair['secretKey'];
$message = '重要声明内容';
$signature = sodium_crypto_sign_detached($message, $secretKey);
// 验证签名
if (sodium_crypto_sign_verify_detached($signature, $message, $publicKey)) {
echo "签名有效" . PHP_EOL;
} else {
echo "签名无效" . PHP_EOL;
}密码哈希
php
<?php
declare(strict_types=1);
// Argon2id(推荐)
$hash = sodium_crypto_pwhash_str(
'my-password',
SODIUM_CRYPTO_PWHASH_OPSLIMIT_MODERATE,
SODIUM_CRYPTO_PWHASH_MEMLIMIT_MODERATE
);
// 验证
if (sodium_crypto_pwhash_str_verify($hash, 'my-password')) {
echo "密码正确" . PHP_EOL;
}
// 获取哈希信息
$info = sodium_crypto_pwhash_str_needs_rehash($hash);注意事项
- Sodium 需要系统安装 libsodium 库
- PHP 7.2+ 可通过 PECL 安装或在编译时启用
- 推荐使用 Sodium 代替 OpenSSL 进行新项目的加密操作
下一节
继续学习:密码散列算法