Skip to content
PHP Logo

How can you ensure compatibility between Java and PHP when encrypting and decrypting data?

To ensure compatibility between Java and PHP when encrypting and decrypting data, you can use standardized encryption algorithms such as AES with the same key size and mode of operation in both languages. This will ensure that the encrypted data can be decrypted successfully by both Java and PHP.

php
// PHP code snippet using AES encryption with a 256-bit key
$key = 'abcdefghijklmnopqrstuvwx'; // 256-bit key
$data = 'Hello, World!';
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));

$encrypted = openssl_encrypt($data, 'aes-256-cbc', $key, 0, $iv);
echo "Encrypted data: $encrypted\n";

$decrypted = openssl_decrypt($encrypted, 'aes-256-cbc', $key, 0, $iv);
echo "Decrypted data: $decrypted\n";