Could anyone help me to figure out a decryption algorithm for data that is encrypted in PHP using AES-256-CBC. I have tried lots of different ways, but I think I am messing up when trying to replicate the method of recreating they Key/IV in Dart and keep getting exceptions such as:
RangeError (end): Invalid value: Not in inclusive range 0..16:
The PHP code that does the encryption (which cannot be changed as the encrypted strings are provided by a third party) is as follows:
function encrypt( $string, $encrypt=true) {
$secret_key = 'SuperSecretKey';
$secret_iv = 'SuperSecretBLOCK';
$output = false;
$encrypt_method = "AES-256-CBC";
$key = hash( 'sha256', $secret_key );
$iv = substr( hash( 'sha256', $secret_iv ), 0, 16 );
if($encrypt) {
$output = base64_encode( openssl_encrypt( $string, $encrypt_method, $key, 0, $iv ) );
} else {
$output = openssl_decrypt( base64_decode( $string ), $encrypt_method, $key, 0, $iv );
}
return $output;
}
For example, if the encryption routine in PHP were called to encrypt the string "This is a Test!", the result would be:
ZHArWURDY2FkelBtSGY5c1AzdTNBZz09
It is this result that I am attempting to decrypt in Dart and not having any luck!
Here is what I have so far that is resulting in the exception referenced above:
import 'package:encrypt/encrypt.dart';
import 'package:crypto/crypto.dart';
import 'dart:convert' show utf8;
String extractPayload(String payload) {
String strPwd = 'SuperSecretKey';
String strIv = 'SuperSecretBLOCK';
var iv = sha256.convert(utf8.encode(strIv));
var key = sha256.convert(utf8.encode(strPwd));
IV ivObj = IV.fromUtf8(iv.toString());
Key keyObj = Key.fromUtf8(key.toString());
final encrypter = Encrypter(AES(keyObj));
final decrypted = encrypter.decrypt(Encrypted.from64(payload), iv: ivObj);
print(decrypted);
return decrypted;
}
Any suggestions welcome, Thanks