BindingFlags.Public needed here as Exception.HResult is now public in .NET 4.5. This...
[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                                 _workingBlock = new byte [transform.InputBlockSize];
75                         }
76                 }
77
78                 ~CryptoStream () 
79                 {
80                         Dispose (false);
81                 }
82                 
83                 public override bool CanRead {
84                         get { return (_mode == CryptoStreamMode.Read); }
85                 }
86
87                 public override bool CanSeek {
88                         get { return false; }
89                 }
90
91                 public override bool CanWrite {
92                         get { return (_mode == CryptoStreamMode.Write); }
93                 }
94                 
95                 public override long Length {
96                         get { throw new NotSupportedException ("Length"); }
97                 }
98
99                 public override long Position {
100                         get { throw new NotSupportedException ("Position"); }
101                         set { throw new NotSupportedException ("Position"); }
102                 }
103
104                 public void Clear () 
105                 {
106                         Close ();
107                 }
108
109                 public override int Read ([In,Out] byte[] buffer, int offset, int count)
110                 {
111                         if (_mode != CryptoStreamMode.Read) {
112                                 throw new NotSupportedException (
113                                         Locale.GetText ("not in Read mode"));
114                         }
115                         if (offset < 0) {
116                                 throw new ArgumentOutOfRangeException ("offset", 
117                                         Locale.GetText ("negative"));
118                         }
119                         if (count < 0) {
120                                 throw new ArgumentOutOfRangeException ("count",
121                                         Locale.GetText ("negative"));
122                         }
123                         // yes - buffer.Length will throw a NullReferenceException if buffer is null
124                         // but by doing so we match MS implementation
125                         // re-ordered to avoid integer overflow
126                         if (offset > buffer.Length - count) {
127                                 throw new ArgumentException ("(offset+count)", 
128                                         Locale.GetText ("buffer overflow"));
129                         }
130                         // for some strange reason ObjectDisposedException isn't throw
131                         if (_workingBlock == null) {
132                                 return 0;
133                         }
134
135                         int result = 0;
136                         if ((count == 0) || ((_transformedPos == _transformedCount) && (_endOfStream)))
137                                 return result;
138
139                         if (_waitingBlock == null) {
140                                 _transformedBlock = new byte [_transform.OutputBlockSize << 2];
141                                 _transformedPos = 0;
142                                 _transformedCount = 0;
143                                 _waitingBlock = new byte [_transform.InputBlockSize];
144                                 _waitingCount = _stream.Read (_waitingBlock, 0, _waitingBlock.Length);
145                         }
146                         
147                         while (count > 0) {
148                                 // transformed but not yet returned
149                                 int length = (_transformedCount - _transformedPos);
150
151                                 // need more data - at least one full block must be available if we haven't reach the end of the stream
152                                 if (length < _transform.InputBlockSize) {
153                                         int transformed = 0;
154
155                                         // load a new block
156                                         _workingCount = _stream.Read (_workingBlock, 0, _transform.InputBlockSize);
157                                         _endOfStream = (_workingCount < _transform.InputBlockSize);
158
159                                         if (!_endOfStream) {
160                                                 // transform the waiting block
161                                                 transformed = _transform.TransformBlock (_waitingBlock, 0, _waitingBlock.Length, _transformedBlock, _transformedCount);
162
163                                                 // transfer temporary to waiting
164                                                 Buffer.BlockCopy (_workingBlock, 0, _waitingBlock, 0, _workingCount);
165                                                 _waitingCount = _workingCount;
166                                         }
167                                         else {
168                                                 if (_workingCount > 0) {
169                                                         // transform the waiting block
170                                                         transformed = _transform.TransformBlock (_waitingBlock, 0, _waitingBlock.Length, _transformedBlock, _transformedCount);
171
172                                                         // transfer temporary to waiting
173                                                         Buffer.BlockCopy (_workingBlock, 0, _waitingBlock, 0, _workingCount);
174                                                         _waitingCount = _workingCount;
175
176                                                         length += transformed;
177                                                         _transformedCount += transformed;
178                                                 }
179                                                 if (!_flushedFinalBlock) {
180                                                         byte[] input = _transform.TransformFinalBlock (_waitingBlock, 0, _waitingCount);
181                                                         transformed = input.Length;
182                                                         Buffer.BlockCopy (input, 0, _transformedBlock, _transformedCount, input.Length);
183                                                         // zeroize this last block
184                                                         Array.Clear (input, 0, input.Length);
185                                                         _flushedFinalBlock = true;
186                                                 }
187                                         }
188
189                                         length += transformed;
190                                         _transformedCount += transformed;
191                                 }
192                                 // compaction
193                                 if (_transformedPos > _transform.OutputBlockSize) {
194                                         Buffer.BlockCopy (_transformedBlock, _transformedPos, _transformedBlock, 0, length);
195                                         _transformedCount -= _transformedPos;
196                                         _transformedPos = 0;
197                                 }
198
199                                 length = ((count < length) ? count : length);
200                                 if (length > 0) {
201                                         Buffer.BlockCopy (_transformedBlock, _transformedPos, buffer, offset, length);
202                                         _transformedPos += length;
203
204                                         result += length;
205                                         offset += length;
206                                         count -= length;
207                                 }
208
209                                 // there may not be enough data in the stream for a 
210                                 // complete block
211                                 if (((length != _transform.InputBlockSize) && (_waitingCount != _transform.InputBlockSize)) || (_endOfStream)) {
212                                         count = 0;      // no more data can be read
213                                 }
214                         }
215                         
216                         return result;
217                 }
218
219                 public override void Write (byte[] buffer, int offset, int count)
220                 {
221                         if (_mode != CryptoStreamMode.Write) {
222                                 throw new NotSupportedException (
223                                         Locale.GetText ("not in Write mode"));
224                         }
225                         if (offset < 0) { 
226                                 throw new ArgumentOutOfRangeException ("offset", 
227                                         Locale.GetText ("negative"));
228                         }
229                         if (count < 0) {
230                                 throw new ArgumentOutOfRangeException ("count", 
231                                         Locale.GetText ("negative"));
232                         }
233                         // re-ordered to avoid integer overflow
234                         if (offset > buffer.Length - count) {
235                                 throw new ArgumentException ("(offset+count)", 
236                                         Locale.GetText ("buffer overflow"));
237                         }
238
239                         if (_stream == null)
240                                 throw new ArgumentNullException ("inner stream was disposed");
241
242                         int buffer_length = count;
243
244                         // partial block (in progress)
245                         if ((_partialCount > 0) && (_partialCount != _transform.InputBlockSize)) {
246                                 int remainder = _transform.InputBlockSize - _partialCount;
247                                 remainder = ((count < remainder) ? count : remainder);
248                                 Buffer.BlockCopy (buffer, offset, _workingBlock, _partialCount, remainder);
249                                 _partialCount += remainder;
250                                 offset += remainder;
251                                 count -= remainder;
252                         }
253
254                         int bufferPos = offset;
255                         while (count > 0) {
256                                 if (_partialCount == _transform.InputBlockSize) {
257                                         if (_currentBlock == null)
258                                                 _currentBlock = new byte [_transform.OutputBlockSize];
259
260                                         // use partial block to avoid (re)allocation
261                                         int len = _transform.TransformBlock (_workingBlock, 0, _partialCount, _currentBlock, 0);
262                                         _stream.Write (_currentBlock, 0, len);
263                                         // reset
264                                         _partialCount = 0;
265                                 }
266
267                                 if (_transform.CanTransformMultipleBlocks) {
268                                         // get the biggest multiple of InputBlockSize in count (without mul or div)
269                                         int size = (count & ~(_transform.InputBlockSize - 1));
270                                         int rem = (count & (_transform.InputBlockSize - 1));
271                                         // avoid reallocating memory at each call (reuse same buffer whenever possible)
272                                         int sizeWorkingBlock = (1 + size / _transform.InputBlockSize) * _transform.OutputBlockSize;
273                                         if (_workingBlock.Length < sizeWorkingBlock) {
274                                                 Array.Clear (_workingBlock, 0, _workingBlock.Length);
275                                                 _workingBlock = new byte [sizeWorkingBlock];
276                                         }
277
278                                         if (size > 0) {
279                                                 int len = _transform.TransformBlock (buffer, offset, size, _workingBlock, 0);
280                                                 _stream.Write (_workingBlock, 0, len);
281                                         }
282
283                                         if (rem > 0)
284                                                 Buffer.BlockCopy (buffer, buffer_length - rem, _workingBlock, 0, rem);
285                                         _partialCount = rem;
286                                         count = 0; // the last block, if any, is in _workingBlock
287                                 } else {
288                                         int len = Math.Min (_transform.InputBlockSize - _partialCount, count);
289                                         Buffer.BlockCopy (buffer, bufferPos, _workingBlock, _partialCount, len);
290                                         bufferPos += len;
291                                         _partialCount += len;
292                                         count -= len;
293                                         // here block may be full, but we wont TransformBlock it until next iteration
294                                         // so that the last block will be called in FlushFinalBlock using TransformFinalBlock
295                                 }
296                         }
297                 }
298
299                 public override void Flush ()
300                 {
301                 }
302
303                 public void FlushFinalBlock ()
304                 {
305                         if (_flushedFinalBlock)
306                                 throw new NotSupportedException (Locale.GetText ("This method cannot be called twice."));
307                         if (_disposed)
308                                 throw new NotSupportedException (Locale.GetText ("CryptoStream was disposed."));
309
310                         _flushedFinalBlock = true;
311                         byte[] finalBuffer = _transform.TransformFinalBlock (_workingBlock, 0, _partialCount);
312                         if (_stream != null && _mode == CryptoStreamMode.Write) {
313                                 _stream.Write (finalBuffer, 0, finalBuffer.Length);
314                         }
315                         if (_stream is CryptoStream) {
316                                 // for cascading crypto streams
317                                 (_stream as CryptoStream).FlushFinalBlock ();
318                         } else {
319                                 _stream.Flush ();
320                         }
321                         // zeroize
322                         Array.Clear (finalBuffer, 0, finalBuffer.Length);
323                 }
324
325                 public override long Seek (long offset, SeekOrigin origin)
326                 {
327                         throw new NotSupportedException ("Seek");
328                 }
329                 
330                 // LAMESPEC: Exception NotSupportedException not documented
331                 public override void SetLength (long value)
332                 {
333                         throw new NotSupportedException ("SetLength");
334                 }
335
336                 protected override void Dispose (bool disposing) 
337                 {
338                         if (!_disposed) {
339                                 if (disposing) {
340                                         if (!_flushedFinalBlock) {
341                                                 FlushFinalBlock ();
342                                         }
343
344                                         if (_stream != null)
345                                                 _stream.Close ();
346                                 }
347                                 _disposed = true;
348                                 // always cleared for security reason
349                                 if (_workingBlock != null)
350                                         Array.Clear (_workingBlock, 0, _workingBlock.Length);
351                                 if (_currentBlock != null)
352                                         Array.Clear (_currentBlock, 0, _currentBlock.Length);
353                                 if (disposing) {
354                                         _stream = null;
355                                         _workingBlock = null;
356                                         _currentBlock = null;
357                                 }
358                         }
359                 }
360 #if NET_4_0
361                 public bool HasFlushedFinalBlock {
362                         get { return _flushedFinalBlock; }
363                 }
364 #endif
365         }
366 }