在Ubuntu系統中,你可以使用PHP的內置函數進行加密和解密。這里有一個簡單的例子,使用openssl_encrypt和openssl_decrypt函數進行加密和解密。
首先,確保你的PHP安裝包含了OpenSSL擴展。你可以通過運行以下命令來檢查:
php -m | grep openssl
如果輸出中包含openssl,那么你已經安裝了這個擴展。如果沒有,請安裝它:
sudo apt-get update
sudo apt-get install php-openssl
然后,你可以使用以下代碼進行加密和解密:
<?php
// 加密
function encrypt($data, $key) {
$cipher = "AES-256-CBC";
$ivlen = openssl_cipher_iv_length($cipher);
$iv = openssl_random_pseudo_bytes($ivlen);
$encrypted = openssl_encrypt($data, $cipher, $key, OPENSSL_RAW_DATA, $iv);
return base64_encode($iv . $encrypted);
}
// 解密
function decrypt($data, $key) {
$cipher = "AES-256-CBC";
$data = base64_decode($data);
$ivlen = openssl_cipher_iv_length($cipher);
$iv = substr($data, 0, $ivlen);
$encrypted = substr($data, $ivlen);
return openssl_decrypt($encrypted, $cipher, $key, OPENSSL_RAW_DATA, $iv);
}
// 示例
$key = "your-secret-key"; // 請使用一個安全的密鑰
$data = "Hello, World!";
$encrypted_data = encrypt($data, $key);
echo "Encrypted data: " . $encrypted_data . PHP_EOL;
$decrypted_data = decrypt($encrypted_data, $key);
echo "Decrypted data: " . $decrypted_data . PHP_EOL;
?>
這個例子使用了AES-256-CBC加密算法,你可以根據需要更改$cipher變量來選擇其他算法。請確保使用一個安全的密鑰,以保證加密和解密的安全性。