在PHP中使用OpenSSL加密和解密數據可以通過以下步驟實現:
$data = 'Hello World';
$key = 'secret_key';
$method = 'AES-256-CBC';
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($method));
$encrypted = openssl_encrypt($data, $method, $key, 0, $iv);
// Store the encrypted data and IV for later decryption
$encryptedData = base64_encode($encrypted);
$ivData = base64_encode($iv);
$encrypted = base64_decode($encryptedData);
$iv = base64_decode($ivData);
$decrypted = openssl_decrypt($encrypted, $method, $key, 0, $iv);
echo $decrypted; // Output: Hello World
請注意,確保在加密和解密數據時使用相同的加密算法、密鑰和初始化向量(IV)。此外,建議在存儲和傳輸加密數據時進行base64編碼以確保數據的完整性。