Reputation: 37
I am trying to add encryption to my chat application . but facing an issue while doing so , i cant
add the data to firebase , it shows an error Unhandled Exception: Invalid argument: Instance of 'Encrypted'
. how can i send a message that is encrypted from client side and send it to firebase and then receive the message , then decrypt it . because i am using the library encrypt 5.0.0 for this and to decrypt it , it only accept the Encrypted
as parameter .
here is class for encryption and decryption .
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);
}
}
using it to send message to firebase as this ..
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);
and here are the Database functions ..
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);
}
Upvotes: 2
Views: 963
Reputation: 94018
Encrypted
is an object. You can retrieve actual value using the fields defined in the API of Encrypted
, e.g. the property bytes
to get the byte representation of the object or base64
if you require the ciphertext as text.
Of course, you can revert back to Encrypted
using one of the constructors: just the Encrypted
constructor for bytes or fromBase64
for text.
Upvotes: 2