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

SodiumDecryptStream.cs 1.6 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. namespace Discord.Audio.Streams
  5. {
  6. ///<summary> Decrypts an RTP frame using libsodium </summary>
  7. public class SodiumDecryptStream : AudioOutStream
  8. {
  9. private readonly AudioClient _client;
  10. private readonly AudioStream _next;
  11. private readonly byte[] _nonce;
  12. public override bool CanRead => true;
  13. public override bool CanSeek => false;
  14. public override bool CanWrite => true;
  15. public SodiumDecryptStream(AudioStream next, IAudioClient client)
  16. {
  17. _next = next;
  18. _client = (AudioClient)client;
  19. _nonce = new byte[24];
  20. }
  21. public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancelToken)
  22. {
  23. cancelToken.ThrowIfCancellationRequested();
  24. if (_client.SecretKey == null)
  25. return;
  26. Buffer.BlockCopy(buffer, 0, _nonce, 0, 12); //Copy RTP header to nonce
  27. count = SecretBox.Decrypt(buffer, offset + 12, count - 12, buffer, offset + 12, _nonce, _client.SecretKey);
  28. await _next.WriteAsync(buffer, 0, count + 12, cancelToken).ConfigureAwait(false);
  29. }
  30. public override async Task FlushAsync(CancellationToken cancelToken)
  31. {
  32. await _next.FlushAsync(cancelToken).ConfigureAwait(false);
  33. }
  34. public override async Task ClearAsync(CancellationToken cancelToken)
  35. {
  36. await _next.ClearAsync(cancelToken).ConfigureAwait(false);
  37. }
  38. }
  39. }