37 lines
1.1 KiB
PHP
37 lines
1.1 KiB
PHP
<?php
|
|
//Mcrypt已经在新版php中移除且处于不再维护状态
|
|
//后续会使用sodium代替
|
|
use Random\RandomException;
|
|
|
|
$str = '你好世界';
|
|
$password = "123456";
|
|
$salt = null;
|
|
|
|
try {
|
|
$salt = random_bytes(SODIUM_CRYPTO_PWHASH_SALTBYTES); // 生成盐值
|
|
// 使用相同的盐值生成密钥
|
|
$key = sodium_crypto_pwhash(
|
|
SODIUM_CRYPTO_SECRETBOX_KEYBYTES,
|
|
$password,
|
|
$salt,
|
|
SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE,
|
|
SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE
|
|
);
|
|
|
|
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
|
|
$encrypted = sodium_crypto_secretbox($str, $nonce, $key);
|
|
echo $encrypted.'<br>';
|
|
// 在解密时需要使用相同的盐值和密钥
|
|
$decrypted = sodium_crypto_secretbox_open($encrypted, $nonce, $key);
|
|
|
|
echo $decrypted; // 输出:你好世界
|
|
} catch (RandomException $e) {
|
|
// 处理随机数生成失败的异常
|
|
error_log('Random number generation failed: ' . $e->getMessage());
|
|
exit(1);
|
|
} catch (SodiumException $e) {
|
|
// 处理其他sodium相关的异常
|
|
error_log('Sodium error: ' . $e->getMessage());
|
|
}
|
|
|