Skip to content

Commit

Permalink
Decrypt messages asynchronously
Browse files Browse the repository at this point in the history
  • Loading branch information
Jack-Edwards committed May 6, 2024
1 parent 163ff7a commit 940e91a
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ public async Task<Either<DownloadTransferCiphertextError, DecryptionStream>> Dow

return await response.MatchAsync<Either<DownloadTransferCiphertextError, DecryptionStream>>(
error => error,
async response => await DecryptionStream.OpenAsync(response.Stream, response.StreamSize, symmetricKey, CryptoProvider.StreamEncryptionFactory),
async streamDownloadResponse => await DecryptionStream.OpenAsync(streamDownloadResponse.Stream, streamDownloadResponse.StreamSize, symmetricKey, CryptoProvider.StreamEncryptionFactory),
DownloadTransferCiphertextError.UnknownError);
}
}
22 changes: 17 additions & 5 deletions Crypter.Common.Client/Transfer/Handlers/DownloadMessageHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
using Crypter.Common.Contracts.Features.Transfer;
using Crypter.Common.Enums;
using Crypter.Crypto.Common;
using Crypter.Crypto.Common.StreamEncryption;
using EasyMonads;

namespace Crypter.Common.Client.Transfer.Handlers;
Expand Down Expand Up @@ -83,12 +84,23 @@ public async Task<Either<DownloadTransferCiphertextError, string>> DownloadCiphe
};
#pragma warning restore CS8524

return response.Match<Either<DownloadTransferCiphertextError, string>>(
left => left,
right =>
return await response.MatchAsync<Either<DownloadTransferCiphertextError, string>>(
error => error,
async streamDownloadResponse =>
{
byte[] plaintext = Decrypt(symmetricKey, right.Stream, right.StreamSize);
return Encoding.UTF8.GetString(plaintext);
await using DecryptionStream decryptionStream = await DecryptionStream.OpenAsync(streamDownloadResponse.Stream,
streamDownloadResponse.StreamSize, symmetricKey, CryptoProvider.StreamEncryptionFactory);

byte[] plaintextBuffer = new byte[checked((int)streamDownloadResponse.StreamSize)];
int plaintextPosition = 0;
int bytesRead;
do
{
bytesRead = await decryptionStream.ReadAsync(plaintextBuffer.AsMemory(plaintextPosition));
plaintextPosition += bytesRead;
} while (bytesRead > 0);

return Encoding.UTF8.GetString(plaintextBuffer[..plaintextPosition]);
},
DownloadTransferCiphertextError.UnknownError);
}
Expand Down

0 comments on commit 940e91a

Please sign in to comment.