[CryptoStream] Invalid enum in ctor
[mono.git] / mcs / class / corlib / System.Security.Cryptography / CryptoStream.cs
1 //
2 // System.Security.Cryptography CryptoStream.cs
3 //
4 // Authors:
5 //      Thomas Neidhart (tome@sbox.tugraz.at)
6 //      Sebastien Pouliot (sebastien@ximian.com)
7 //
8 // Portions (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com)
9 // Copyright (C) 2004-2005, 2007 Novell, Inc (http://www.novell.com)
10 //
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
18 // 
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
21 // 
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29 //
30
31 using System.Globalization;
32 using System.IO;
33 using System.Runtime.InteropServices;
34
35 namespace System.Security.Cryptography {
36
37         [ComVisible (true)]
38         public class CryptoStream : Stream {
39                 private Stream _stream;
40                 private ICryptoTransform _transform;
41                 private CryptoStreamMode _mode;
42                 private byte[] _currentBlock;
43                 private bool _disposed;
44                 private bool _flushedFinalBlock;
45                 private int _partialCount;
46                 private bool _endOfStream;
47
48                 private byte[] _waitingBlock;
49                 private int _waitingCount;
50
51                 private byte[] _transformedBlock;
52                 private int _transformedPos;
53                 private int _transformedCount;
54
55                 private byte[] _workingBlock;
56                 private int _workingCount;
57                 
58                 public CryptoStream (Stream stream, ICryptoTransform transform, CryptoStreamMode mode)
59                 {
60                         if (mode == CryptoStreamMode.Read) {
61                                 if (!stream.CanRead)
62                                         throw new ArgumentException (Locale.GetText ("Can't read on stream"));
63                         } else if (mode == CryptoStreamMode.Write) {
64                                 if (!stream.CanWrite)
65                                         throw new ArgumentException (Locale.GetText ("Can't write on stream"));
66                         } else {
67                                 throw new ArgumentException ("mode");
68                         }
69                         _stream = stream;
70                         _transform = transform;
71                         _mode = mode;
72                         _disposed = false;
73                         if (transform != null) {
74                                 if (mode == CryptoStreamMode.Read) {
75                                         _currentBlock = new byte [transform.InputBlockSize];
76                                         _workingBlock = new byte [transform.InputBlockSize];
77                                 }
78                                 else if (mode == CryptoStreamMode.Write) {
79                                         _currentBlock = new byte [transform.OutputBlockSize];
80                                         _workingBlock = new byte [transform.OutputBlockSize];
81                                 }
82                         }
83                 }
84
85                 ~CryptoStream () 
86                 {
87                         Dispose (false);
88                 }
89                 
90                 public override bool CanRead {
91                         get { return (_mode == CryptoStreamMode.Read); }
92                 }
93
94                 public override bool CanSeek {
95                         get { return false; }
96                 }
97
98                 public override bool CanWrite {
99                         get { return (_mode == CryptoStreamMode.Write); }
100                 }
101                 
102                 public override long Length {
103                         get { throw new NotSupportedException ("Length"); }
104                 }
105
106                 public override long Position {
107                         get { throw new NotSupportedException ("Position"); }
108                         set { throw new NotSupportedException ("Position"); }
109                 }
110
111                 public void Clear () 
112                 {
113                         Close ();
114                 }
115
116                 // LAMESPEC: A CryptoStream can be close in read mode
117                 public override void Close () 
118                 {
119                         base.Close ();
120                 }
121
122                 public override int Read ([In,Out] byte[] buffer, int offset, int count)
123                 {
124                         if (_mode != CryptoStreamMode.Read) {
125                                 throw new NotSupportedException (
126                                         Locale.GetText ("not in Read mode"));
127                         }
128                         if (offset < 0) {
129                                 throw new ArgumentOutOfRangeException ("offset", 
130                                         Locale.GetText ("negative"));
131                         }
132                         if (count < 0) {
133                                 throw new ArgumentOutOfRangeException ("count",
134                                         Locale.GetText ("negative"));
135                         }
136                         // yes - buffer.Length will throw a NullReferenceException if buffer is null
137                         // but by doing so we match MS implementation
138                         // re-ordered to avoid integer overflow
139                         if (offset > buffer.Length - count) {
140                                 throw new ArgumentException ("(offset+count)", 
141                                         Locale.GetText ("buffer overflow"));
142                         }
143                         // for some strange reason ObjectDisposedException isn't throw
144                         if (_workingBlock == null) {
145                                 return 0;
146                         }
147
148                         int result = 0;
149                         if ((count == 0) || ((_transformedPos == _transformedCount) && (_endOfStream)))
150                                 return result;
151
152                         if (_waitingBlock == null) {
153                                 _transformedBlock = new byte [_transform.OutputBlockSize << 2];
154                                 _transformedPos = 0;
155                                 _transformedCount = 0;
156                                 _waitingBlock = new byte [_transform.InputBlockSize];
157                                 _waitingCount = _stream.Read (_waitingBlock, 0, _waitingBlock.Length);
158                         }
159                         
160                         while (count > 0) {
161                                 // transformed but not yet returned
162                                 int length = (_transformedCount - _transformedPos);
163
164                                 // need more data - at least one full block must be available if we haven't reach the end of the stream
165                                 if (length < _transform.InputBlockSize) {
166                                         int transformed = 0;
167
168                                         // load a new block
169                                         _workingCount = _stream.Read (_workingBlock, 0, _transform.InputBlockSize);
170                                         _endOfStream = (_workingCount < _transform.InputBlockSize);
171
172                                         if (!_endOfStream) {
173                                                 // transform the waiting block
174                                                 transformed = _transform.TransformBlock (_waitingBlock, 0, _waitingBlock.Length, _transformedBlock, _transformedCount);
175
176                                                 // transfer temporary to waiting
177                                                 Buffer.BlockCopy (_workingBlock, 0, _waitingBlock, 0, _workingCount);
178                                                 _waitingCount = _workingCount;
179                                         }
180                                         else {
181                                                 if (_workingCount > 0) {
182                                                         // transform the waiting block
183                                                         transformed = _transform.TransformBlock (_waitingBlock, 0, _waitingBlock.Length, _transformedBlock, _transformedCount);
184
185                                                         // transfer temporary to waiting
186                                                         Buffer.BlockCopy (_workingBlock, 0, _waitingBlock, 0, _workingCount);
187                                                         _waitingCount = _workingCount;
188
189                                                         length += transformed;
190                                                         _transformedCount += transformed;
191                                                 }
192                                                 if (!_flushedFinalBlock) {
193                                                         byte[] input = _transform.TransformFinalBlock (_waitingBlock, 0, _waitingCount);
194                                                         transformed = input.Length;
195                                                         Buffer.BlockCopy (input, 0, _transformedBlock, _transformedCount, input.Length);
196                                                         // zeroize this last block
197                                                         Array.Clear (input, 0, input.Length);
198                                                         _flushedFinalBlock = true;
199                                                 }
200                                         }
201
202                                         length += transformed;
203                                         _transformedCount += transformed;
204                                 }
205                                 // compaction
206                                 if (_transformedPos > _transform.OutputBlockSize) {
207                                         Buffer.BlockCopy (_transformedBlock, _transformedPos, _transformedBlock, 0, length);
208                                         _transformedCount -= _transformedPos;
209                                         _transformedPos = 0;
210                                 }
211
212                                 length = ((count < length) ? count : length);
213                                 if (length > 0) {
214                                         Buffer.BlockCopy (_transformedBlock, _transformedPos, buffer, offset, length);
215                                         _transformedPos += length;
216
217                                         result += length;
218                                         offset += length;
219                                         count -= length;
220                                 }
221
222                                 // there may not be enough data in the stream for a 
223                                 // complete block
224                                 if (((length != _transform.InputBlockSize) && (_waitingCount != _transform.InputBlockSize)) || (_endOfStream)) {
225                                         count = 0;      // no more data can be read
226                                 }
227                         }
228                         
229                         return result;
230                 }
231
232                 public override void Write (byte[] buffer, int offset, int count)
233                 {
234                         if (_mode != CryptoStreamMode.Write) {
235                                 throw new NotSupportedException (
236                                         Locale.GetText ("not in Write mode"));
237                         }
238                         if (offset < 0) { 
239                                 throw new ArgumentOutOfRangeException ("offset", 
240                                         Locale.GetText ("negative"));
241                         }
242                         if (count < 0) {
243                                 throw new ArgumentOutOfRangeException ("count", 
244                                         Locale.GetText ("negative"));
245                         }
246                         // re-ordered to avoid integer overflow
247                         if (offset > buffer.Length - count) {
248                                 throw new ArgumentException ("(offset+count)", 
249                                         Locale.GetText ("buffer overflow"));
250                         }
251
252                         if (_stream == null)
253                                 throw new ArgumentNullException ("inner stream was diposed");
254
255                         int buffer_length = count;
256
257                         // partial block (in progress)
258                         if ((_partialCount > 0) && (_partialCount != _transform.InputBlockSize)) {
259                                 int remainder = _transform.InputBlockSize - _partialCount;
260                                 remainder = ((count < remainder) ? count : remainder);
261                                 Buffer.BlockCopy (buffer, offset, _workingBlock, _partialCount, remainder);
262                                 _partialCount += remainder;
263                                 offset += remainder;
264                                 count -= remainder;
265                         }
266
267                         int bufferPos = offset;
268                         while (count > 0) {
269                                 if (_partialCount == _transform.InputBlockSize) {
270                                         // use partial block to avoid (re)allocation
271                                         int len = _transform.TransformBlock (_workingBlock, 0, _partialCount, _currentBlock, 0);
272                                         _stream.Write (_currentBlock, 0, len);
273                                         // reset
274                                         _partialCount = 0;
275                                 }
276
277                                 if (_transform.CanTransformMultipleBlocks) {
278                                         // get the biggest multiple of InputBlockSize in count (without mul or div)
279                                         int size = (count & ~(_transform.InputBlockSize - 1));
280                                         int rem = (count & (_transform.InputBlockSize - 1));
281                                         // avoid reallocating memory at each call (reuse same buffer whenever possible)
282                                         int sizeWorkingBlock = (1 + size / _transform.InputBlockSize) * _transform.OutputBlockSize;
283                                         if (_workingBlock.Length < sizeWorkingBlock) {
284                                                 Array.Clear (_workingBlock, 0, _workingBlock.Length);
285                                                 _workingBlock = new byte [sizeWorkingBlock];
286                                         }
287
288                                         if (size > 0) {
289                                                 int len = _transform.TransformBlock (buffer, offset, size, _workingBlock, 0);
290                                                 _stream.Write (_workingBlock, 0, len);
291                                         }
292
293                                         if (rem > 0)
294                                                 Buffer.BlockCopy (buffer, buffer_length - rem, _workingBlock, 0, rem);
295                                         _partialCount = rem;
296                                         count = 0; // the last block, if any, is in _workingBlock
297                                 } else {
298                                         int len = Math.Min (_transform.InputBlockSize - _partialCount, count);
299                                         Buffer.BlockCopy (buffer, bufferPos, _workingBlock, _partialCount, len);
300                                         bufferPos += len;
301                                         _partialCount += len;
302                                         count -= len;
303                                         // here block may be full, but we wont TransformBlock it until next iteration
304                                         // so that the last block will be called in FlushFinalBlock using TransformFinalBlock
305                                 }
306                         }
307                 }
308
309                 public override void Flush ()
310                 {
311                 }
312
313                 public void FlushFinalBlock ()
314                 {
315                         if (_flushedFinalBlock)
316                                 throw new NotSupportedException (Locale.GetText ("This method cannot be called twice."));
317                         if (_disposed)
318                                 throw new NotSupportedException (Locale.GetText ("CryptoStream was disposed."));
319
320                         _flushedFinalBlock = true;
321                         byte[] finalBuffer = _transform.TransformFinalBlock (_workingBlock, 0, _partialCount);
322                         if (_stream != null && _mode == CryptoStreamMode.Write) {
323                                 _stream.Write (finalBuffer, 0, finalBuffer.Length);
324                         }
325                         if (_stream is CryptoStream) {
326                                 // for cascading crypto streams
327                                 (_stream as CryptoStream).FlushFinalBlock ();
328                         } else {
329                                 _stream.Flush ();
330                         }
331                         // zeroize
332                         Array.Clear (finalBuffer, 0, finalBuffer.Length);
333                 }
334
335                 public override long Seek (long offset, SeekOrigin origin)
336                 {
337                         throw new NotSupportedException ("Seek");
338                 }
339                 
340                 // LAMESPEC: Exception NotSupportedException not documented
341                 public override void SetLength (long value)
342                 {
343                         throw new NotSupportedException ("SetLength");
344                 }
345
346                 protected override void Dispose (bool disposing) 
347                 {
348                         if (!_disposed) {
349                                 if (disposing) {
350                                         if (!_flushedFinalBlock) {
351                                                 FlushFinalBlock ();
352                                         }
353
354                                         if (_stream != null)
355                                                 _stream.Close ();
356                                 }
357                                 _disposed = true;
358                                 // always cleared for security reason
359                                 if (_workingBlock != null)
360                                         Array.Clear (_workingBlock, 0, _workingBlock.Length);
361                                 if (_currentBlock != null)
362                                         Array.Clear (_currentBlock, 0, _currentBlock.Length);
363                                 if (disposing) {
364                                         _stream = null;
365                                         _workingBlock = null;
366                                         _currentBlock = null;
367                                 }
368                         }
369                 }
370         }
371 }