Encrypted messaging app
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

108 lines
2.6 KiB

import 'dart:convert';
import 'package:pointycastle/export.dart';
import '/utils/encryption/crypto_utils.dart';
import '/utils/encryption/aes_helper.dart';
import '/utils/storage/database.dart';
import '/models/friends.dart';
const messageTypeSender = 'sender';
const messageTypeReceiver = 'receiver';
class Message {
String id;
String symmetricKey;
String messageThreadKey;
String data;
String senderId;
String senderUsername;
String createdAt;
Message({
required this.id,
required this.symmetricKey,
required this.messageThreadKey,
required this.data,
required this.senderId,
required this.senderUsername,
required this.createdAt,
});
factory Message.fromJson(Map<String, dynamic> json, RSAPrivateKey privKey) {
var symmetricKey = CryptoUtils.rsaDecrypt(
base64.decode(json['symmetric_key']),
privKey,
);
var data = AesHelper.aesDecrypt(
symmetricKey,
base64.decode(json['message_data']['data']),
);
var senderId = AesHelper.aesDecrypt(
symmetricKey,
base64.decode(json['message_data']['sender_id']),
);
return Message(
id: json['id'],
messageThreadKey: json['message_thread_key'],
symmetricKey: base64.encode(symmetricKey),
data: data,
senderId: senderId,
senderUsername: 'Unknown', // TODO
createdAt: json['created_at'],
);
}
@override
String toString() {
return '''
id: $id
data: $data
senderId: $senderId
senderUsername: $senderUsername
createdAt: $createdAt
''';
}
Map<String, dynamic> toMap() {
return {
'id': id,
'message_thread_key': messageThreadKey,
'symmetric_key': symmetricKey,
'data': data,
'sender_id': senderId,
'sender_username': senderUsername,
'created_at': createdAt,
};
}
}
Future<List<Message>> getMessagesForThread(String messageThreadKey) async {
final db = await getDatabaseConnection();
List<dynamic> whereArguments = [messageThreadKey];
final List<Map<String, dynamic>> maps = await db.query(
'messages',
where: 'message_thread_key = ?',
whereArgs: whereArguments,
orderBy: 'created_at DESC',
);
return List.generate(maps.length, (i) {
return Message(
id: maps[i]['id'],
messageThreadKey: maps[i]['message_thread_key'],
symmetricKey: maps[i]['symmetric_key'],
data: maps[i]['data'],
senderId: maps[i]['sender_id'],
senderUsername: maps[i]['sender_username'],
createdAt: maps[i]['created_at'],
);
});
}