Skip to content

Instantly share code, notes, and snippets.

@alikuro
Last active April 19, 2022 06:58
Show Gist options
  • Save alikuro/99a43398e5ca5c0a30f819f7c9bb0b7f to your computer and use it in GitHub Desktop.
Save alikuro/99a43398e5ca5c0a30f819f7c9bb0b7f to your computer and use it in GitHub Desktop.
Encrypt - Decrypt AES on PHP openssl vs Python Crypto
// let say key and iv is shared securely between end
// iv - encrypt method AES-256-CBC expects 16 bytes
private $secret_key = 'secret';
private $secret_iv = 'salt-secret';
function aes_encrypt($string) {
$key = hash('sha256', $this->secret_key);
$iv = substr(hash('sha256', $this->secret_iv), 0, 16);
return base64_encode(openssl_encrypt($string, 'AES-256-CBC', $key, 0, $iv));
// incase you don't want to use double encode
// return openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
}
function aes_decrypt($string) {
$key = hash('sha256', $this->secret_key);
$iv = substr(hash('sha256', $this->secret_iv), 0, 16);
return openssl_decrypt(base64_decode($string), 'AES-256-CBC', $key, 0, $iv);
// incase you don't want to use double encode
// return openssl_decrypt($string, 'AES-256-CBC', $key, 0, $iv);
}
#!/usr/bin/env python3
# pip install pycrypto
import hashlib
from base64 import b64encode, b64decode
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from Crypto.Util.Padding import unpad
# let say key and iv is shared securely between end.
# keep in mind AES supports multiple key sizes: 16 (AES128), 24 (AES192), or 32 (AES256).
# and iv - encrypt method AES-256-CBC expects 16 bytes
secret_key = 'secret'
secret_iv = 'salt-secret'
def aes_encrypt(plain_string):
try:
hash_key = hashlib.sha256(secret_key.encode('utf-8')).hexdigest()[:32].encode("utf-8")
hash_iv = hashlib.sha256(secret_iv.encode('utf-8')).hexdigest()[:16].encode("utf-8")
cipher = AES.new(hash_key, AES.MODE_CBC, hash_iv)
return b64encode(b64encode(cipher.encrypt(pad(plain_string.encode('utf-8'), AES.block_size)))).decode('utf-8')
# incase you don't want to use double encode
# return b64encode(cipher.encrypt(pad(plain_string.encode('utf-8'), AES.block_size))).decode('utf-8')
except Exception as e:
return None
def aes_decrypt(plain_string):
try:
hash_key = hashlib.sha256(secret_key.encode('utf-8')).hexdigest()[:32].encode("utf-8")
hash_iv = hashlib.sha256(secret_iv.encode('utf-8')).hexdigest()[:16].encode("utf-8")
cipher = AES.new(hash_key, AES.MODE_CBC, hash_iv)
return unpad(cipher.decrypt( b64decode( b64decode( plain_string ) ) ), AES.block_size).decode('utf-8')
# incase you don't want to use double encode
# return unpad(cipher.decrypt( b64decode( plain_string ) ), AES.block_size).decode('utf-8')
except Exception as e:
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment