I am asking this because I don't really know php but must to somehow manage with. I have encrypted data in python and need to decrypt in php (serversite). python encryption:
import hashlib
from base64 import b64encode, b64decode, urlsafe_b64encode, urlsafe_b64decode
from Crypto.Cipher import AES
text = "secret"
secret_key = 'This is my secret key'
secret_iv = 'This is my secret iv'
key = hashlib.sha256(secret_key.encode('utf-8')).hexdigest()[:32].encode("utf-8")
iv = hashlib.sha256(secret_iv.encode('utf-8')).hexdigest()[:16].encode("utf-8")
_pad = lambda s: s + (AES.block_size - len(s) % AES.block_size) * chr(AES.block_size - len(s) % AES.block_size)
txt = _pad(text)
cipher = AES.new(key, AES.MODE_CBC, iv)
output = urlsafe_b64encode(cipher.encrypt(str.encode(txt))).rstrip(b'=')
this gives 'rtVabOaDdf528T63xOhhww' output, which is correctly AES encrypted.
and php which encrypts and decrypts in other way:
<?php
$string="secret";
class CryptService{
private static $encryptMethod = 'AES-256-CBC';
private $key;
private $iv;
public function __construct(){
echo '<br>: '.$this->key = substr(hash('sha256', 'This is my secret key'), 0, 32);
echo '<br>: '.$this->iv = substr(hash('sha256', 'This is my secret iv'), 0, 16).'<br>';
}
public function decrypt($string){
// $string = strtr($data, '-_', '+/');
$string = base64_decode($string);
return openssl_decrypt($string, self::$encryptMethod, $this->key, 0, $this->iv);
}
public function encrypt($string){
$output = openssl_encrypt($string, self::$encryptMethod, $this->key, 0, $this->iv);
$output = base64_encode($output);
return $output;
}
}
$a = new CryptService;
echo $ok=$a->encrypt('secret');
echo "\n";
echo 'TEST: '.$a->decrypt($string);
echo 'BACK ok: '.$a->decrypt($ok);
echo "\n\n";
There is some issue with openssl_decrypt() function because of "iv". Can someone help me figure this out...
You're assigning additional 4 characters <br>
to your $this->iv. This will fix it:
echo '<br>: ' . ($this->iv = substr(hash('sha256', 'This is my secret iv'), 0, 16)) . '<br>';
Basically, your . '<br>'
is concatenating the <br>
to your substr()
. I added ()
around the variable value assignment. Now it works
cnRWYWJPYURkZjUyOFQ2M3hPaGh3dz09 TEST: BACK ok: secret
I am not an expert on encryption, but... I think there's something in your code that doesn't quite belong in there. When I remove these two lines:
$string = base64_decode($string);
$output = base64_encode($output);
I get this output:
rtVabOaDdf528T63xOhhww==
Which, after a rtrim($ok, '=');
, would give you
rtVabOaDdf528T63xOhhww