I need to encrypt a message in PHP and then later decode it with a Python script. The problem is that the decryption is not working (or maybe I'm doing the encryption wrong).
Here is the PHP test script.
<?php
$pass = "password";
$salt = "salt";
$data = "here is a test message";
$cipher = "aes-256-cbc";
$options = OPENSSL_RAW_DATA;
$rnds = 1024;
$klen = 64;
$key = hash_pbkdf2("sha256", $pass, $salt, $rnds, $klen, FALSE);
echo("Key = '" . $key . "'<br>");
$iv = openssl_random_pseudo_bytes(16);
$enc = openssl_encrypt($data, $cipher, $key, $options, $iv);
echo("IV = '" . base64_encode($iv) . "'<br>");
echo("Encrypted = '" . base64_encode($enc) . "'<br>");
?>
The output will be different each time but here is an example output
Key = '231afb7dcd2e860cfd58ab13372bd12c923076c3598a121960320f6fec8a5698'
IV = 'zBSQYEZ5p10COkbRC9O32Q=='
Encrypted = 'tLMg1MXNGwPgVdPIOiKwkS8WVVWpcAiZUT8FlSL8LO8='
And here is the Python test script using the above values.
import base64
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=b'salt',
iterations=1024
)
key = kdf.derive(b'password')
print(key.hex()) #231afb7dcd2e860cfd58ab13372bd12c923076c3598a121960320f6fec8a5698
iv = base64.b64decode('zBSQYEZ5p10COkbRC9O32Q==')
enc = base64.b64decode('tLMg1MXNGwPgVdPIOiKwkS8WVVWpcAiZUT8FlSL8LO8=')
cipher = Cipher(algorithms.AES(key), modes.CBC(iv))
decryptor = cipher.decryptor()
plain = decryptor.update(enc) + decryptor.finalize()
print(plain)
#b'\x0f"\xb1\x99\x00\xd8\x06\xe3\xe1))\xb06\xab\x83\x8d\x89\t\x014\x8a\xfb\x9b\xb6\x0e\ns\xd9\xe2\x97\xf9n'
The pbkdf2 key derivation outputs match between the two scripts and so does the IV obviously. But there seems to be something basic I'm overlooking because it's not all that complicated code.
source https://stackoverflow.com/questions/76806209/trouble-with-decrypting-from-php-openssl-encrypt-with-python-pyca-cryptography
No comments:
Post a Comment