message.dart 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import 'dart:convert';
  2. import 'package:e2ee_chat/common/cipher.dart';
  3. import 'package:json_annotation/json_annotation.dart';
  4. import 'package:dash_chat/dash_chat.dart';
  5. import 'package:encrypt/encrypt.dart';
  6. import 'package:pointycastle/asymmetric/api.dart';
  7. part 'message.g.dart';
  8. @JsonSerializable()
  9. class Message {
  10. Message(this.from, this.to, this.cipher, this.cipherText, this.publicKey, this.iv);
  11. factory Message.encrypt(String from, String to, String plaintext, String publicKey) {
  12. // TODO: encrypt
  13. String cipher = "";
  14. String cipherText = "";
  15. String publicKey = "";
  16. String iv = "";
  17. return Message(from, to, cipher, cipherText, publicKey, iv);
  18. }
  19. factory Message.fromJson(Map<String, dynamic> json) => _$MessageFromJson(json);
  20. Map<String, dynamic> toJson() => _$MessageToJson(this);
  21. String from;
  22. String to;
  23. String cipher;
  24. String cipherText;
  25. String publicKey;
  26. String iv;
  27. Future<ChatMessage?> get chatMessage async {
  28. ChatMessage? _message;
  29. final RSAPrivateKey? _privateKey = await getRSAPrivateKey(from);
  30. if (_privateKey != null) {
  31. final _publicKey = (await getRSAPublicKey(publicKey))!;
  32. final _rsaEncrypter = Encrypter(
  33. RSA(publicKey: _publicKey, privateKey: _privateKey));
  34. final _keyBase64 = _rsaEncrypter.decrypt64(cipher);
  35. final _key = Key.fromBase64(_keyBase64);
  36. final _iv = IV.fromBase64(iv);
  37. final _aesEncrypter = Encrypter(AES(_key));
  38. final _decrypted = _aesEncrypter.decrypt64(cipherText, iv: _iv);
  39. _message = ChatMessage.fromJson(jsonDecode(_decrypted));
  40. }
  41. return _message;
  42. }
  43. }
  44. /*
  45. class GroupMessage {
  46. int id = 0;
  47. String plaintext = "";
  48. final user = ToOne<User>();
  49. final group = ToOne<Group>();
  50. @Transient()
  51. ChatMessage get chatMessage => ChatMessage.fromJson(jsonDecode(plaintext));
  52. }
  53. */