【问题标题】:Unhandled Exception: Invalid argument: Instance of 'Encrypted'未处理的异常:无效的参数:“加密”的实例
【发布时间】:2021-10-04 21:43:06
【问题描述】:

我正在尝试为我的聊天应用程序添加加密。但是这样做时遇到问题,我不能 将数据添加到 firebase ,它会显示错误Unhandled Exception: Invalid argument: Instance of 'Encrypted'。我如何发送从客户端加密的消息并将其发送到 firebase,然后接收消息,然后解密它。因为我为此使用库 encrypt 5.0.0 并对其进行解密,所以它只接受 Encrypted 作为参数。

这里是加密解密类。

import 'package:encrypt/encrypt.dart' as encrypt;
class MyEncryptionDecryption{

  ///for encrption

 static final key = encrypt.Key.fromLength(32);
 static final iv = encrypt.IV.fromLength(16);
 static final  encrypter = encrypt.Encrypter(encrypt.AES(key));


  static encryptAES(message ){

   final encrypted =  encrypter.encrypt(message ,iv: iv);
      print(encrypted.base16);
      print(encrypted.base64);
      return encrypted;
  }
  static decryptedAES(message){

    return   encrypter.decrypt(message,iv: iv);

  }
  
}

使用它来向 firebase 发送消息 ..

var aes = MyEncryptionDecryption.encryptAES(message);
      Map<String, dynamic> messageInfoMap = {
        "message": aes,
        "sendBy": myUserName,
        "ts": lastMessageTs,
        "imgUrl": myProfilePic
      };


      DatabaseMethods()
          .addMessage(chatRoomId, messageId, messageInfoMap)
          .then((value) {


        Map<String, dynamic> lastMessageInfoMap = {
          "lastMessage": aes,
          "lastMessageSendTs": lastMessageTs,
          "lastMessageSendBy": myUserName,
          "readStatus" : false ,
          "count" : count,
          "show" : true,
        };

        DatabaseMethods().updateLastMessageSend(chatRoomId, lastMessageInfoMap);

这里是数据库函数..

Future addMessage(String chatRoomId , String messageId,messageInfoMap) async {
   return await FirebaseFirestore.instance.
   collection("chatrooms").
   doc(chatRoomId).collection('chats').doc(messageId).set(messageInfoMap);
 }
 updateLastMessageSend(String chatRoomId, lastMessageInfoMap){
   return FirebaseFirestore
       .instance.collection('chatrooms').doc(chatRoomId)
       .update(lastMessageInfoMap);
 }

【问题讨论】:

    标签: firebase flutter dart encryption google-cloud-firestore


    【解决方案1】:

    Encrypted 是一个对象。您可以使用the fields defined in the API of Encrypted 检索实际值,例如属性bytes 来获取对象的字节表示,或者base64 如果你需要密文作为文本。

    当然,您可以使用其中一种构造函数恢复为 Encrypted:对于字节仅使用 Encrypted 构造函数,对于文本使用 fromBase64

    【讨论】:

    • 虽然这是非常基本的东西,但我已经回答了,因为encrypt 功能的示例似乎都缺少Encrypted 密文表示所需的编码/解码,我同意这很容易错误的开发人员。
    猜你喜欢
    • 2020-07-26
    • 2021-09-22
    • 1970-01-01
    • 2023-03-17
    • 2019-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-12
    相关资源
    最近更新 更多