PkwareTraditionalCryptoStream.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. using System;
  2. using System.IO;
  3. namespace SharpCompress.Common.Zip
  4. {
  5. internal enum CryptoMode
  6. {
  7. Encrypt,
  8. Decrypt
  9. }
  10. internal class PkwareTraditionalCryptoStream : Stream
  11. {
  12. private readonly PkwareTraditionalEncryptionData _encryptor;
  13. private readonly CryptoMode _mode;
  14. private readonly Stream _stream;
  15. private bool _isDisposed;
  16. public PkwareTraditionalCryptoStream(Stream stream, PkwareTraditionalEncryptionData encryptor, CryptoMode mode)
  17. {
  18. this._encryptor = encryptor;
  19. this._stream = stream;
  20. this._mode = mode;
  21. }
  22. public override bool CanRead => (_mode == CryptoMode.Decrypt);
  23. public override bool CanSeek => false;
  24. public override bool CanWrite => (_mode == CryptoMode.Encrypt);
  25. public override long Length => throw new NotSupportedException();
  26. public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
  27. public override int Read(byte[] buffer, int offset, int count)
  28. {
  29. if (_mode == CryptoMode.Encrypt)
  30. {
  31. throw new NotSupportedException("This stream does not encrypt via Read()");
  32. }
  33. if (buffer == null)
  34. {
  35. throw new ArgumentNullException(nameof(buffer));
  36. }
  37. byte[] temp = new byte[count];
  38. int readBytes = _stream.Read(temp, 0, count);
  39. byte[] decrypted = _encryptor.Decrypt(temp, readBytes);
  40. Buffer.BlockCopy(decrypted, 0, buffer, offset, readBytes);
  41. return readBytes;
  42. }
  43. public override void Write(byte[] buffer, int offset, int count)
  44. {
  45. if (_mode == CryptoMode.Decrypt)
  46. {
  47. throw new NotSupportedException("This stream does not Decrypt via Write()");
  48. }
  49. if (count == 0)
  50. {
  51. return;
  52. }
  53. byte[] plaintext = null;
  54. if (offset != 0)
  55. {
  56. plaintext = new byte[count];
  57. Buffer.BlockCopy(buffer, offset, plaintext, 0, count);
  58. }
  59. else
  60. {
  61. plaintext = buffer;
  62. }
  63. byte[] encrypted = _encryptor.Encrypt(plaintext, count);
  64. _stream.Write(encrypted, 0, encrypted.Length);
  65. }
  66. public override void Flush()
  67. {
  68. //throw new NotSupportedException();
  69. }
  70. public override long Seek(long offset, SeekOrigin origin)
  71. {
  72. throw new NotSupportedException();
  73. }
  74. public override void SetLength(long value)
  75. {
  76. throw new NotSupportedException();
  77. }
  78. protected override void Dispose(bool disposing)
  79. {
  80. if (_isDisposed)
  81. {
  82. return;
  83. }
  84. _isDisposed = true;
  85. base.Dispose(disposing);
  86. _stream.Dispose();
  87. }
  88. }
  89. }