title: Flutter / Dart AES-256-CBC decrypting from encryption in PHP
body: <p>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:</p>
  <pre><code>RangeError (end): Invalid value: Not in inclusive range 0..16:
  </code></pre>
  <p>The PHP code that does the encryption (which cannot be changed as the encrypted strings are provided by a third party) is as follows:</p>
  <pre><code>function encrypt( $string, $encrypt=true) {
      $secret_key = 'SuperSecretKey';
      $secret_iv = 'SuperSecretBLOCK';
      $output = false;
      $encrypt_method = &quot;AES-256-CBC&quot;;
      $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;
  }
  </code></pre>
  <p>For example, if the encryption routine in PHP were called to encrypt the string &quot;This is a Test!&quot;, the result would be:</p>
  <pre><code>ZHArWURDY2FkelBtSGY5c1AzdTNBZz09
  </code></pre>
  <p>It is this result that I am attempting to decrypt in Dart and not having any luck!</p>
  <p>Here is what I have so far that is resulting in the exception referenced above:</p>
  <pre><code>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;
  }
  </code></pre>
  <p>Any suggestions welcome,
  Thanks</p>