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