What are the potential security risks of using JavaScript for encryption in PHP applications?

Using JavaScript for encryption in PHP applications can pose security risks because JavaScript runs on the client-side, making the encryption vulnerable to attacks such as man-in-the-middle or cross-site scripting. To mitigate this risk, encryption should be handled on the server-side using PHP's built-in encryption functions.

// Server-side encryption using PHP's built-in functions
$plaintext = "Hello, world!";
$key = "secretkey";
$method = "AES-256-CBC";
$iv = random_bytes(16);

$ciphertext = openssl_encrypt($plaintext, $method, $key, 0, $iv);
$decrypted = openssl_decrypt($ciphertext, $method, $key, 0, $iv);

echo "Encrypted: " . $ciphertext . "\n";
echo "Decrypted: " . $decrypted . "\n";