openIfEncrypted function

Future<SFMessage> openIfEncrypted(
  1. SFMessage message,
  2. PayloadEncryptor? encryptor
)

Returns message with its payload opened when it is flagged encrypted, checked against the envelope it arrived in; otherwise unchanged.

Throws PayloadDecryptException naming this layer when there is no encryptor to open it with, or the ciphertext does not open, or it was sealed for a different message.

Implementation

Future<SFMessage> openIfEncrypted(SFMessage message, PayloadEncryptor? encryptor) async {
  if (!message.flags.isEncrypted) return message;
  if (encryptor == null) {
    throw PayloadDecryptException(
        'message ${message.messageId} is encrypted and this client has no PayloadEncryptor to open it');
  }
  final opened = await encryptor.decryptBound(message.payload, PayloadBinding.of(message), message.senderPeerId);
  return message.withPayload(opened.payload, flags: message.flags.withoutFlag(SFMessageFlags.encrypted));
}