Skip to content

Instantly share code, notes, and snippets.

@sokil
Last active January 12, 2022 07:40
Show Gist options
  • Save sokil/3eb004e3d3f59a815bc41a6fb09c8419 to your computer and use it in GitHub Desktop.
Save sokil/3eb004e3d3f59a815bc41a6fb09c8419 to your computer and use it in GitHub Desktop.
PHP And Python Compatible OpenSSL AES Encoding and decoding
<?php
$passphrase = 'some-passphrase';
$text = 'Hello world!';
$method = 'AES-256-CBC';
// passphrase
$passphrase = hash('sha256', $passphrase, true);
// encrypt
$ivLength = openssl_cipher_iv_length($method);
$iv = openssl_random_pseudo_bytes($ivLength);
$encryptedData = openssl_encrypt($text, $method, $passphrase, OPENSSL_RAW_DATA, $iv);
// pack to message
$packedEncryptedMessage = $iv . $encryptedData;
# convert to base64
$base64encodedMessage = base64_encode($packedEncryptedMessage);
# convert from base64
$packedEncryptedMessage = base64_decode($base64encodedMessage);
// unpack message
$iv = substr($packedEncryptedMessage, 0, $ivLength);
$encryptedData = substr($packedEncryptedMessage, $ivLength);
// decrypt
$text = openssl_decrypt($encryptedData, $method, $passphrase, OPENSSL_RAW_DATA, $iv);
var_dump($text);
# pip3 install -U PyCryptodome
from Crypto.Cipher import AES
from Crypto import Random
import hashlib
import base64
pad = lambda message, block_size: message + (block_size - len(message) % block_size) * chr(block_size - len(message) % block_size)
unpad = lambda message: message[:-ord(message[len(message) - 1:])]
passphrase = 'some-passphrase'
text = 'Hello world!'
# AES-256-CBC
passphrase = hashlib.sha256(passphrase.encode()).digest()
# encrypt
iv = Random.new().read(AES.block_size)
cipher = AES.new(passphrase, AES.MODE_CBC, iv)
encryptedData = cipher.encrypt(pad(text, AES.block_size).encode())
# pack to message
packedEncryptedMessage = iv + encryptedData
# convert to base64
base64EncodedMessage = base64.b64encode(packedEncryptedMessage)
# convert from base64
packedEncryptedMessage = base64.b64decode(base64EncodedMessage)
# unpack message
iv = packedEncryptedMessage[:AES.block_size]
encryptedData = packedEncryptedMessage[AES.block_size:]
# decrypt
cipher = AES.new(passphrase, AES.MODE_CBC, iv)
text = cipher.decrypt(encryptedData)
text = unpad(text)
print(text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment