繁体   English   中英

如何像在 php 上一样在 dart/flutter 上加密和解密?

[英]How can I encrypt and decrypt on dart/flutter the same way I have on php?

我有以下api:

class AESEncrypter
{
    public static function EncryptString($plainText, $phrase)
    {
       if(strlen($phrase) < 32)
       {
           while(strlen($phrase) < 32)
           {
               $phrase .= $phrase;
           }
           $phrase = substr($phrase,0,32);
       }
       if(strlen($phrase) > 32)
       {
           $phrase = substr($phrase,0,32);
       }
       $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
       echo('valor: '.openssl_cipher_iv_length('aes-256-cbc'));
       $string = openssl_encrypt($plainText,"aes-256-cbc",$phrase, OPENSSL_RAW_DATA , $iv);
       return base64_encode($iv.$string);
    }

    public static function DecryptString($plainText, $phrase)
    {
        if(strlen($phrase) < 32)
        {
            while(strlen($phrase) < 32)
            {
                $phrase .= $phrase;
            }
            $phrase = substr($phrase,0,32);
        }
        if(strlen($phrase) > 32)
        {
            $phrase = substr($phrase,0,32);
        }

        $plainText = base64_decode($plainText);
        $encodedData = substr($plainText, openssl_cipher_iv_length('aes-256-cbc'));
        $iv = substr($plainText,0,openssl_cipher_iv_length('aes-256-cbc'));
        $decrypted = openssl_decrypt($encodedData, "aes-256-cbc", $phrase, OPENSSL_RAW_DATA, $iv);
        return $decrypted;
    }
}

我需要一个 .dart 文件才能与 api 正确通信。

我试过了:

class AESEncrypter {
  static encryptString(plainText, phrase) {
    if ((phrase.length) < 32) {
      while ((phrase.length) < 32) {
        phrase = phrase + phrase;
      }
      phrase = phrase.substring(0, 32);
    }
    if ((phrase.length) > 32) {
      phrase = phrase.substring(0, 32);
    }
    final iv = IV.fromSecureRandom(16);
    final key = Key.fromUtf8(phrase);
    final encrypter = Encrypter(AES(key));
    final encrypted = encrypter.encrypt(plainText, iv: iv);
    return encrypted.base64;
    //return "${iv.base64}${encrypted.base64}";
  }
}

但不工作。 我不知道如何在 dart 上编写代码来执行相同的加密/解密过程。 当我在 dart 上加密并在 php 上解密时,我没有得到相同的文本。

有什么建议么? 谢谢<3

试试这个加密

import 'package:encrypt/encrypt.dart';

void main() {
  final plainText = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit';
  final key = Key.fromUtf8('my 32 length key................');
  final iv = IV.fromLength(16);

  final encrypter = Encrypter(AES(key));

  final encrypted = encrypter.encrypt(plainText, iv: iv);
  final decrypted = encrypter.decrypt(encrypted, iv: iv);

  print(decrypted); // Lorem ipsum dolor sit amet, consectetur adipiscing elit
  print(encrypted.base64); // R4PxiU3h8YoIRqVowBXm36ZcCeNeZ4s1OvVBTfFlZRdmohQqOpPQqD1YecJeZMAop/hZ4OxqgC1WtwvX/hP9mw==
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM