我想使用我以前的代码在 Flutter 中进行加密和解密

i want to do encrypt & decrypt in flutter using my previous code

提问人:M. Ibnu Wildan 提问时间:11/16/2023 更新时间:11/16/2023 访问量:49

问:

我在另一个项目上有加密和解密功能。功能如下:

    public static function encrypt_decrypt($action, $string) {
        $output = false;

        $encrypt_method = "AES-256-CBC";
        $secret_key = 'R4haSIA';
        $secret_iv = 'r$h4sia';

        $key = hash('sha256', $secret_key);

        $iv = substr(hash('sha256', $secret_iv), 0, 16);

        if ($action == 'encrypt') {
            $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
            $output = base64_encode($output);
        } else if ($action == 'decrypt') {
            $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
        }

        return $output;
    }

我想做的是,在我的 Flutter 项目中使用我之前的函数执行相同的加密和解密功能。我试过这个,但它不起作用。

  String encryptPassword(String password) {
    final key = encrypt.Key.fromUtf8('R4haSIA');
    final iv = encrypt.IV.fromUtf8('r\$h4sia12345678'); // Panjang IV 16 byte
    final encrypter =
        encrypt.Encrypter(encrypt.AES(key, mode: encrypt.AESMode.cbc));
    final encrypted = encrypter.encrypt(password, iv: iv);

    return encrypted.base64;
  }

  Future<void> _login() async {
    var url = Uri.parse("http://10.0.2.2/config/db/login.php");
    var pass_enkripsi = encryptPassword(passwordController.text);
    var response = await http.post(url, body: {
      "username": usernameController.text,
      "password": pass_enkripsi,
    });
    var datauser = jsonDecode(response.body);

    if (datauser != '') {
      print('Login Success');

      Navigator.pushReplacement(
        context,
        MaterialPageRoute(builder: (context) => const homepage()),
      );
    } else {
      print('Login failed');
      //print('Login Failed');
      // Navigator.push<void>(
      //   context,
      //   MaterialPageRoute<void>(
      //     builder: (BuildContext context) => MyApp2(),
      //   ),
      // );
    }
  }

这是我在 Flutter 中运行代码时的错误消息:

I/AssistStructure( 9703): Flattened final assist data: 384 bytes, containing 1 windows, 3 views
E/flutter ( 9703): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Invalid argument(s): Initialization vector must be the same length as block size
Flutter 加密

评论

1赞 Topaco 11/16/2023
PHP 代码有几个漏洞:硬编码的密钥和 IV 材料、快速摘要作为密钥派生、直接使用十六进制编码的字符串作为密钥......在 Dart 代码中,缺少通过摘要导出 key 和 IV,可能会出现进一步的错误。如果修复后问题仍然存在,请发布测试数据:明文和密文(对于已发布的密钥和 IV 材料)。

答: 暂无答案