AES Common encryption and decryption between php and python

There are several common encryption and decryption algorithms that can be used between PHP and Python. Here is the example of AES:

AES encryption and decryption:

PHP example:

$key = 'mysecretkey';
$message = 'Hello, world!';

// Encrypt
$ciphertext = openssl_encrypt($message, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
$encoded = base64_encode($ciphertext);

// Decrypt
$ciphertext = base64_decode($encoded);
$plaintext = openssl_decrypt($ciphertext, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
echo $plaintext; // Output: Hello, world!

Python Example:

from Crypto.Cipher import AES
import base64

key = b'mysecretkey'
message = b'Hello, world!'
iv = b'1234567890123456'

# Encrypt
cipher = AES.new(key, AES.MODE_CBC, iv)
padded_message = message + b"\0" * (AES.block_size - len(message) % AES.block_size)
ciphertext = cipher.encrypt(padded_message)
encoded = base64.b64encode(ciphertext).decode('utf-8')

# Decrypt
ciphertext = base64.b64decode(encoded)
cipher = AES.new(key, AES.MODE_CBC, iv)
padded_plaintext = cipher.decrypt(ciphertext)
plaintext = padded_plaintext.rstrip(b"\0").decode('utf-8')
print(plaintext) # Output: Hello, world!

Did you find this article useful?