2 // System.Security.Cryptography CryptoStream.cs
5 // Thomas Neidhart (tome@sbox.tugraz.at)
6 // Sebastien Pouliot (sebastien@ximian.com)
8 // Portions (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com)
9 // Copyright (C) 2004-2005, 2007 Novell, Inc (http://www.novell.com)
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:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
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.
31 using System.Globalization;
33 using System.Runtime.InteropServices;
35 namespace System.Security.Cryptography {
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;
48 private byte[] _waitingBlock;
49 private int _waitingCount;
51 private byte[] _transformedBlock;
52 private int _transformedPos;
53 private int _transformedCount;
55 private byte[] _workingBlock;
56 private int _workingCount;
58 public CryptoStream (Stream stream, ICryptoTransform transform, CryptoStreamMode mode)
60 if (mode == CryptoStreamMode.Read) {
62 throw new ArgumentException (Locale.GetText ("Can't read on stream"));
63 } else if (mode == CryptoStreamMode.Write) {
65 throw new ArgumentException (Locale.GetText ("Can't write on stream"));
67 throw new ArgumentException ("mode");
70 _transform = transform;
73 if (transform != null) {
74 _workingBlock = new byte [transform.InputBlockSize];
83 public override bool CanRead {
84 get { return (_mode == CryptoStreamMode.Read); }
87 public override bool CanSeek {
91 public override bool CanWrite {
92 get { return (_mode == CryptoStreamMode.Write); }
95 public override long Length {
96 get { throw new NotSupportedException ("Length"); }
99 public override long Position {
100 get { throw new NotSupportedException ("Position"); }
101 set { throw new NotSupportedException ("Position"); }
109 // LAMESPEC: A CryptoStream can be close in read mode
110 public override void Close ()
115 public override int Read ([In,Out] byte[] buffer, int offset, int count)
117 if (_mode != CryptoStreamMode.Read) {
118 throw new NotSupportedException (
119 Locale.GetText ("not in Read mode"));
122 throw new ArgumentOutOfRangeException ("offset",
123 Locale.GetText ("negative"));
126 throw new ArgumentOutOfRangeException ("count",
127 Locale.GetText ("negative"));
129 // yes - buffer.Length will throw a NullReferenceException if buffer is null
130 // but by doing so we match MS implementation
131 // re-ordered to avoid integer overflow
132 if (offset > buffer.Length - count) {
133 throw new ArgumentException ("(offset+count)",
134 Locale.GetText ("buffer overflow"));
136 // for some strange reason ObjectDisposedException isn't throw
137 if (_workingBlock == null) {
142 if ((count == 0) || ((_transformedPos == _transformedCount) && (_endOfStream)))
145 if (_waitingBlock == null) {
146 _transformedBlock = new byte [_transform.OutputBlockSize << 2];
148 _transformedCount = 0;
149 _waitingBlock = new byte [_transform.InputBlockSize];
150 _waitingCount = _stream.Read (_waitingBlock, 0, _waitingBlock.Length);
154 // transformed but not yet returned
155 int length = (_transformedCount - _transformedPos);
157 // need more data - at least one full block must be available if we haven't reach the end of the stream
158 if (length < _transform.InputBlockSize) {
162 _workingCount = _stream.Read (_workingBlock, 0, _transform.InputBlockSize);
163 _endOfStream = (_workingCount < _transform.InputBlockSize);
166 // transform the waiting block
167 transformed = _transform.TransformBlock (_waitingBlock, 0, _waitingBlock.Length, _transformedBlock, _transformedCount);
169 // transfer temporary to waiting
170 Buffer.BlockCopy (_workingBlock, 0, _waitingBlock, 0, _workingCount);
171 _waitingCount = _workingCount;
174 if (_workingCount > 0) {
175 // transform the waiting block
176 transformed = _transform.TransformBlock (_waitingBlock, 0, _waitingBlock.Length, _transformedBlock, _transformedCount);
178 // transfer temporary to waiting
179 Buffer.BlockCopy (_workingBlock, 0, _waitingBlock, 0, _workingCount);
180 _waitingCount = _workingCount;
182 length += transformed;
183 _transformedCount += transformed;
185 if (!_flushedFinalBlock) {
186 byte[] input = _transform.TransformFinalBlock (_waitingBlock, 0, _waitingCount);
187 transformed = input.Length;
188 Buffer.BlockCopy (input, 0, _transformedBlock, _transformedCount, input.Length);
189 // zeroize this last block
190 Array.Clear (input, 0, input.Length);
191 _flushedFinalBlock = true;
195 length += transformed;
196 _transformedCount += transformed;
199 if (_transformedPos > _transform.OutputBlockSize) {
200 Buffer.BlockCopy (_transformedBlock, _transformedPos, _transformedBlock, 0, length);
201 _transformedCount -= _transformedPos;
205 length = ((count < length) ? count : length);
207 Buffer.BlockCopy (_transformedBlock, _transformedPos, buffer, offset, length);
208 _transformedPos += length;
215 // there may not be enough data in the stream for a
217 if (((length != _transform.InputBlockSize) && (_waitingCount != _transform.InputBlockSize)) || (_endOfStream)) {
218 count = 0; // no more data can be read
225 public override void Write (byte[] buffer, int offset, int count)
227 if (_mode != CryptoStreamMode.Write) {
228 throw new NotSupportedException (
229 Locale.GetText ("not in Write mode"));
232 throw new ArgumentOutOfRangeException ("offset",
233 Locale.GetText ("negative"));
236 throw new ArgumentOutOfRangeException ("count",
237 Locale.GetText ("negative"));
239 // re-ordered to avoid integer overflow
240 if (offset > buffer.Length - count) {
241 throw new ArgumentException ("(offset+count)",
242 Locale.GetText ("buffer overflow"));
246 throw new ArgumentNullException ("inner stream was disposed");
248 int buffer_length = count;
250 // partial block (in progress)
251 if ((_partialCount > 0) && (_partialCount != _transform.InputBlockSize)) {
252 int remainder = _transform.InputBlockSize - _partialCount;
253 remainder = ((count < remainder) ? count : remainder);
254 Buffer.BlockCopy (buffer, offset, _workingBlock, _partialCount, remainder);
255 _partialCount += remainder;
260 int bufferPos = offset;
262 if (_partialCount == _transform.InputBlockSize) {
263 if (_currentBlock == null)
264 _currentBlock = new byte [_transform.OutputBlockSize];
266 // use partial block to avoid (re)allocation
267 int len = _transform.TransformBlock (_workingBlock, 0, _partialCount, _currentBlock, 0);
268 _stream.Write (_currentBlock, 0, len);
273 if (_transform.CanTransformMultipleBlocks) {
274 // get the biggest multiple of InputBlockSize in count (without mul or div)
275 int size = (count & ~(_transform.InputBlockSize - 1));
276 int rem = (count & (_transform.InputBlockSize - 1));
277 // avoid reallocating memory at each call (reuse same buffer whenever possible)
278 int sizeWorkingBlock = (1 + size / _transform.InputBlockSize) * _transform.OutputBlockSize;
279 if (_workingBlock.Length < sizeWorkingBlock) {
280 Array.Clear (_workingBlock, 0, _workingBlock.Length);
281 _workingBlock = new byte [sizeWorkingBlock];
285 int len = _transform.TransformBlock (buffer, offset, size, _workingBlock, 0);
286 _stream.Write (_workingBlock, 0, len);
290 Buffer.BlockCopy (buffer, buffer_length - rem, _workingBlock, 0, rem);
292 count = 0; // the last block, if any, is in _workingBlock
294 int len = Math.Min (_transform.InputBlockSize - _partialCount, count);
295 Buffer.BlockCopy (buffer, bufferPos, _workingBlock, _partialCount, len);
297 _partialCount += len;
299 // here block may be full, but we wont TransformBlock it until next iteration
300 // so that the last block will be called in FlushFinalBlock using TransformFinalBlock
305 public override void Flush ()
309 public void FlushFinalBlock ()
311 if (_flushedFinalBlock)
312 throw new NotSupportedException (Locale.GetText ("This method cannot be called twice."));
314 throw new NotSupportedException (Locale.GetText ("CryptoStream was disposed."));
316 _flushedFinalBlock = true;
317 byte[] finalBuffer = _transform.TransformFinalBlock (_workingBlock, 0, _partialCount);
318 if (_stream != null && _mode == CryptoStreamMode.Write) {
319 _stream.Write (finalBuffer, 0, finalBuffer.Length);
321 if (_stream is CryptoStream) {
322 // for cascading crypto streams
323 (_stream as CryptoStream).FlushFinalBlock ();
328 Array.Clear (finalBuffer, 0, finalBuffer.Length);
331 public override long Seek (long offset, SeekOrigin origin)
333 throw new NotSupportedException ("Seek");
336 // LAMESPEC: Exception NotSupportedException not documented
337 public override void SetLength (long value)
339 throw new NotSupportedException ("SetLength");
342 protected override void Dispose (bool disposing)
346 if (!_flushedFinalBlock) {
354 // always cleared for security reason
355 if (_workingBlock != null)
356 Array.Clear (_workingBlock, 0, _workingBlock.Length);
357 if (_currentBlock != null)
358 Array.Clear (_currentBlock, 0, _currentBlock.Length);
361 _workingBlock = null;
362 _currentBlock = null;