Merge branch 'master' of github.com:mono/mono
[mono.git] / mcs / class / Mono.Security / Mono.Security.Cryptography / SymmetricTransform.cs
1 //
2 // Mono.Security.Cryptography.SymmetricTransform implementation
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-2008 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;
32 using System.Security.Cryptography;
33
34 namespace Mono.Security.Cryptography {
35
36         // This class implement most of the common code required for symmetric
37         // algorithm transforms, like:
38         // - CipherMode: Builds CBC and CFB on top of (descendant supplied) ECB
39         // - PaddingMode, transform properties, multiple blocks, reuse...
40         //
41         // Descendants MUST:
42         // - intialize themselves (like key expansion, ...)
43         // - override the ECB (Electronic Code Book) method which will only be
44         //   called using BlockSize byte[] array.
45         internal abstract class SymmetricTransform : ICryptoTransform {
46                 protected SymmetricAlgorithm algo;
47                 protected bool encrypt;
48                 private int BlockSizeByte;
49                 private byte[] temp;
50                 private byte[] temp2;
51                 private byte[] workBuff;
52                 private byte[] workout;
53 #if !MOONLIGHT
54                 // Silverlight 2.0 does not support any feedback mode
55                 private int FeedBackByte;
56                 private int FeedBackIter;
57 #endif
58                 private bool m_disposed = false;
59                 private bool lastBlock;
60
61                 public SymmetricTransform (SymmetricAlgorithm symmAlgo, bool encryption, byte[] rgbIV) 
62                 {
63                         algo = symmAlgo;
64                         encrypt = encryption;
65                         BlockSizeByte = (algo.BlockSize >> 3);
66
67                         if (rgbIV == null) {
68                                 rgbIV = KeyBuilder.IV (BlockSizeByte);
69                         } else {
70                                 rgbIV = (byte[]) rgbIV.Clone ();
71                         }
72                         // compare the IV length with the "currently selected" block size and *ignore* IV that are too big
73                         if (rgbIV.Length < BlockSizeByte) {
74                                 string msg = Locale.GetText ("IV is too small ({0} bytes), it should be {1} bytes long.",
75                                         rgbIV.Length, BlockSizeByte);
76                                 throw new CryptographicException (msg);
77                         }
78
79                         // mode buffers
80                         temp = new byte [BlockSizeByte];
81                         Buffer.BlockCopy (rgbIV, 0, temp, 0, System.Math.Min (BlockSizeByte, rgbIV.Length));
82                         temp2 = new byte [BlockSizeByte];
83 #if !MOONLIGHT
84                         FeedBackByte = (algo.FeedbackSize >> 3);
85                         if (FeedBackByte != 0)
86                                 FeedBackIter = (int) BlockSizeByte / FeedBackByte;
87 #endif
88                         // transform buffers
89                         workBuff = new byte [BlockSizeByte];
90                         workout =  new byte [BlockSizeByte];
91                 }
92
93                 ~SymmetricTransform () 
94                 {
95                         Dispose (false);
96                 }
97
98                 void IDisposable.Dispose () 
99                 {
100                         Dispose (true);
101                         GC.SuppressFinalize (this);  // Finalization is now unnecessary
102                 }
103
104                 // MUST be overriden by classes using unmanaged ressources
105                 // the override method must call the base class
106                 protected virtual void Dispose (bool disposing) 
107                 {
108                         if (!m_disposed) {
109                                 if (disposing) {
110                                         // dispose managed object: zeroize and free
111                                         Array.Clear (temp, 0, BlockSizeByte);
112                                         temp = null;
113                                         Array.Clear (temp2, 0, BlockSizeByte);
114                                         temp2 = null;
115                                 }
116                                 m_disposed = true;
117                         }
118                 }
119
120                 public virtual bool CanTransformMultipleBlocks {
121                         get { return true; }
122                 }
123
124                 public virtual bool CanReuseTransform {
125                         get { return false; }
126                 }
127
128                 public virtual int InputBlockSize {
129                         get { return BlockSizeByte; }
130                 }
131
132                 public virtual int OutputBlockSize {
133                         get { return BlockSizeByte; }
134                 }
135
136                 // note: Each block MUST be BlockSizeValue in size!!!
137                 // i.e. Any padding must be done before calling this method
138                 protected virtual void Transform (byte[] input, byte[] output) 
139                 {
140 #if MOONLIGHT
141                         // Silverlight 2.0 only supports CBC
142                         CBC (input, output);
143 #else
144                         switch (algo.Mode) {
145                         case CipherMode.ECB:
146                                 ECB (input, output);
147                                 break;
148                         case CipherMode.CBC:
149                                 CBC (input, output);
150                                 break;
151                         case CipherMode.CFB:
152                                 CFB (input, output);
153                                 break;
154                         case CipherMode.OFB:
155                                 OFB (input, output);
156                                 break;
157                         case CipherMode.CTS:
158                                 CTS (input, output);
159                                 break;
160                         default:
161                                 throw new NotImplementedException ("Unkown CipherMode" + algo.Mode.ToString ());
162                         }
163 #endif
164                 }
165
166                 // Electronic Code Book (ECB)
167                 protected abstract void ECB (byte[] input, byte[] output); 
168
169                 // Cipher-Block-Chaining (CBC)
170                 protected virtual void CBC (byte[] input, byte[] output) 
171                 {
172                         if (encrypt) {
173                                 for (int i = 0; i < BlockSizeByte; i++)
174                                         temp[i] ^= input[i];
175                                 ECB (temp, output);
176                                 Buffer.BlockCopy (output, 0, temp, 0, BlockSizeByte);
177                         }
178                         else {
179                                 Buffer.BlockCopy (input, 0, temp2, 0, BlockSizeByte);
180                                 ECB (input, output);
181                                 for (int i = 0; i < BlockSizeByte; i++)
182                                         output[i] ^= temp[i];
183                                 Buffer.BlockCopy (temp2, 0, temp, 0, BlockSizeByte);
184                         }
185                 }
186
187 #if !MOONLIGHT
188                 // Cipher-FeedBack (CFB)
189                 protected virtual void CFB (byte[] input, byte[] output) 
190                 {
191                         if (encrypt) {
192                                 for (int x = 0; x < FeedBackIter; x++) {
193                                         // temp is first initialized with the IV
194                                         ECB (temp, temp2);
195
196                                         for (int i = 0; i < FeedBackByte; i++)
197                                                 output[i + x] = (byte)(temp2[i] ^ input[i + x]);
198                                         Buffer.BlockCopy (temp, FeedBackByte, temp, 0, BlockSizeByte - FeedBackByte);
199                                         Buffer.BlockCopy (output, x, temp, BlockSizeByte - FeedBackByte, FeedBackByte);
200                                 }
201                         }
202                         else {
203                                 for (int x = 0; x < FeedBackIter; x++) {
204                                         // we do not really decrypt this data!
205                                         encrypt = true;
206                                         // temp is first initialized with the IV
207                                         ECB (temp, temp2);
208                                         encrypt = false;
209
210                                         Buffer.BlockCopy (temp, FeedBackByte, temp, 0, BlockSizeByte - FeedBackByte);
211                                         Buffer.BlockCopy (input, x, temp, BlockSizeByte - FeedBackByte, FeedBackByte);
212                                         for (int i = 0; i < FeedBackByte; i++)
213                                                 output[i + x] = (byte)(temp2[i] ^ input[i + x]);
214                                 }
215                         }
216                 }
217
218                 // Output-FeedBack (OFB)
219                 protected virtual void OFB (byte[] input, byte[] output) 
220                 {
221                         throw new CryptographicException ("OFB isn't supported by the framework");
222                 }
223
224                 // Cipher Text Stealing (CTS)
225                 protected virtual void CTS (byte[] input, byte[] output) 
226                 {
227                         throw new CryptographicException ("CTS isn't supported by the framework");
228                 }
229 #endif
230
231                 private void CheckInput (byte[] inputBuffer, int inputOffset, int inputCount)
232                 {
233                         if (inputBuffer == null)
234                                 throw new ArgumentNullException ("inputBuffer");
235                         if (inputOffset < 0)
236                                 throw new ArgumentOutOfRangeException ("inputOffset", "< 0");
237                         if (inputCount < 0)
238                                 throw new ArgumentOutOfRangeException ("inputCount", "< 0");
239                         // ordered to avoid possible integer overflow
240                         if (inputOffset > inputBuffer.Length - inputCount)
241                                 throw new ArgumentException ("inputBuffer", Locale.GetText ("Overflow"));
242                 }
243
244                 // this method may get called MANY times so this is the one to optimize
245                 public virtual int TransformBlock (byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) 
246                 {
247                         if (m_disposed)
248                                 throw new ObjectDisposedException ("Object is disposed");
249                         CheckInput (inputBuffer, inputOffset, inputCount);
250                         // check output parameters
251                         if (outputBuffer == null)
252                                 throw new ArgumentNullException ("outputBuffer");
253                         if (outputOffset < 0)
254                                 throw new ArgumentOutOfRangeException ("outputOffset", "< 0");
255
256                         // ordered to avoid possible integer overflow
257                         int len = outputBuffer.Length - inputCount - outputOffset;
258 #if MOONLIGHT
259                         // only PKCS7 is supported Silverlight 2.0
260                         if (KeepLastBlock) {
261 #else
262                         if (!encrypt && (0 > len) && ((algo.Padding == PaddingMode.None) || (algo.Padding == PaddingMode.Zeros))) {
263                                 throw new CryptographicException ("outputBuffer", Locale.GetText ("Overflow"));
264                         } else if (KeepLastBlock) {
265 #endif
266                                 if (0 > len + BlockSizeByte) {
267                                         throw new CryptographicException ("outputBuffer", Locale.GetText ("Overflow"));
268                                 }
269                         } else {
270                                 if (0 > len) {
271                                         // there's a special case if this is the end of the decryption process
272                                         if (inputBuffer.Length - inputOffset - outputBuffer.Length == BlockSizeByte)
273                                                 inputCount = outputBuffer.Length - outputOffset;
274                                         else
275                                                 throw new CryptographicException ("outputBuffer", Locale.GetText ("Overflow"));
276                                 }
277                         }
278                         return InternalTransformBlock (inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
279                 }
280
281                 private bool KeepLastBlock {
282                         get {
283 #if MOONLIGHT
284                                 // only PKCS7 is supported Silverlight 2.0
285                                 return !encrypt;
286 #else
287                                 return ((!encrypt) && (algo.Padding != PaddingMode.None) && (algo.Padding != PaddingMode.Zeros));
288 #endif
289                         }
290                 }
291
292                 private int InternalTransformBlock (byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) 
293                 {
294                         int offs = inputOffset;
295                         int full;
296
297                         // this way we don't do a modulo every time we're called
298                         // and we may save a division
299                         if (inputCount != BlockSizeByte) {
300                                 if ((inputCount % BlockSizeByte) != 0)
301                                         throw new CryptographicException ("Invalid input block size.");
302
303                                 full = inputCount / BlockSizeByte;
304                         }
305                         else
306                                 full = 1;
307
308                         if (KeepLastBlock)
309                                 full--;
310
311                         int total = 0;
312
313                         if (lastBlock) {
314                                 Transform (workBuff, workout);
315                                 Buffer.BlockCopy (workout, 0, outputBuffer, outputOffset, BlockSizeByte);
316                                 outputOffset += BlockSizeByte;
317                                 total += BlockSizeByte;
318                                 lastBlock = false;
319                         }
320
321                         for (int i = 0; i < full; i++) {
322                                 Buffer.BlockCopy (inputBuffer, offs, workBuff, 0, BlockSizeByte);
323                                 Transform (workBuff, workout);
324                                 Buffer.BlockCopy (workout, 0, outputBuffer, outputOffset, BlockSizeByte);
325                                 offs += BlockSizeByte;
326                                 outputOffset += BlockSizeByte;
327                                 total += BlockSizeByte;
328                         }
329
330                         if (KeepLastBlock) {
331                                 Buffer.BlockCopy (inputBuffer, offs, workBuff, 0, BlockSizeByte);
332                                 lastBlock = true;
333                         }
334
335                         return total;
336                 }
337
338 #if !MOONLIGHT
339                 RandomNumberGenerator _rng;
340
341                 private void Random (byte[] buffer, int start, int length)
342                 {
343                         if (_rng == null) {
344                                 _rng = RandomNumberGenerator.Create ();
345                         }
346                         byte[] random = new byte [length];
347                         _rng.GetBytes (random);
348                         Buffer.BlockCopy (random, 0, buffer, start, length);
349                 }
350
351                 private void ThrowBadPaddingException (PaddingMode padding, int length, int position)
352                 {
353                         string msg = String.Format (Locale.GetText ("Bad {0} padding."), padding);
354                         if (length >= 0)
355                                 msg += String.Format (Locale.GetText (" Invalid length {0}."), length);
356                         if (position >= 0)
357                                 msg += String.Format (Locale.GetText (" Error found at position {0}."), position);
358                         throw new CryptographicException (msg);
359                 }
360 #endif
361
362                 private byte[] FinalEncrypt (byte[] inputBuffer, int inputOffset, int inputCount) 
363                 {
364                         // are there still full block to process ?
365                         int full = (inputCount / BlockSizeByte) * BlockSizeByte;
366                         int rem = inputCount - full;
367                         int total = full;
368
369 #if MOONLIGHT
370                         // only PKCS7 is supported Silverlight 2.0
371                         total += BlockSizeByte;
372 #else
373                         switch (algo.Padding) {
374                         case PaddingMode.ANSIX923:
375                         case PaddingMode.ISO10126:
376                         case PaddingMode.PKCS7:
377                                 // we need to add an extra block for padding
378                                 total += BlockSizeByte;
379                                 break;
380                         default:
381                                 if (inputCount == 0)
382                                         return new byte [0];
383                                 if (rem != 0) {
384                                         if (algo.Padding == PaddingMode.None)
385                                                 throw new CryptographicException ("invalid block length");
386                                         // zero padding the input (by adding a block for the partial data)
387                                         byte[] paddedInput = new byte [full + BlockSizeByte];
388                                         Buffer.BlockCopy (inputBuffer, inputOffset, paddedInput, 0, inputCount);
389                                         inputBuffer = paddedInput;
390                                         inputOffset = 0;
391                                         inputCount = paddedInput.Length;
392                                         total = inputCount;
393                                 }
394                                 break;
395                         }
396 #endif // NET_2_1
397
398                         byte[] res = new byte [total];
399                         int outputOffset = 0;
400
401                         // process all blocks except the last (final) block
402                         while (total > BlockSizeByte) {
403                                 InternalTransformBlock (inputBuffer, inputOffset, BlockSizeByte, res, outputOffset);
404                                 inputOffset += BlockSizeByte;
405                                 outputOffset += BlockSizeByte;
406                                 total -= BlockSizeByte;
407                         }
408
409                         // now we only have a single last block to encrypt
410                         byte padding = (byte) (BlockSizeByte - rem);
411 #if MOONLIGHT
412                         // only PKCS7 is supported Silverlight 2.0
413                         for (int i = res.Length; --i >= (res.Length - padding);) 
414                                 res [i] = padding;
415                         Buffer.BlockCopy (inputBuffer, inputOffset, res, full, rem);
416                         InternalTransformBlock (res, full, BlockSizeByte, res, full);
417 #else
418                         switch (algo.Padding) {
419                         case PaddingMode.ANSIX923:
420                                 // XX 00 00 00 00 00 00 07 (zero + padding length)
421                                 res [res.Length - 1] = padding;
422                                 Buffer.BlockCopy (inputBuffer, inputOffset, res, full, rem);
423                                 // the last padded block will be transformed in-place
424                                 InternalTransformBlock (res, full, BlockSizeByte, res, full);
425                                 break;
426                         case PaddingMode.ISO10126:
427                                 // XX 3F 52 2A 81 AB F7 07 (random + padding length)
428                                 Random (res, res.Length - padding, padding - 1);
429                                 res [res.Length - 1] = padding;
430                                 Buffer.BlockCopy (inputBuffer, inputOffset, res, full, rem);
431                                 // the last padded block will be transformed in-place
432                                 InternalTransformBlock (res, full, BlockSizeByte, res, full);
433                                 break;
434                         case PaddingMode.PKCS7:
435                                 // XX 07 07 07 07 07 07 07 (padding length)
436                                 for (int i = res.Length; --i >= (res.Length - padding);) 
437                                         res [i] = padding;
438                                 Buffer.BlockCopy (inputBuffer, inputOffset, res, full, rem);
439                                 // the last padded block will be transformed in-place
440                                 InternalTransformBlock (res, full, BlockSizeByte, res, full);
441                                 break;
442                         default:
443                                 InternalTransformBlock (inputBuffer, inputOffset, BlockSizeByte, res, outputOffset);
444                                 break;
445                         }
446 #endif // NET_2_1
447                         return res;
448                 }
449
450                 private byte[] FinalDecrypt (byte[] inputBuffer, int inputOffset, int inputCount) 
451                 {
452                         if ((inputCount % BlockSizeByte) > 0)
453                                 throw new CryptographicException ("Invalid input block size.");
454
455                         int total = inputCount;
456                         if (lastBlock)
457                                 total += BlockSizeByte;
458
459                         byte[] res = new byte [total];
460                         int outputOffset = 0;
461
462                         while (inputCount > 0) {
463                                 int len = InternalTransformBlock (inputBuffer, inputOffset, BlockSizeByte, res, outputOffset);
464                                 inputOffset += BlockSizeByte;
465                                 outputOffset += len;
466                                 inputCount -= BlockSizeByte;
467                         }
468
469                         if (lastBlock) {
470                                 Transform (workBuff, workout);
471                                 Buffer.BlockCopy (workout, 0, res, outputOffset, BlockSizeByte);
472                                 outputOffset += BlockSizeByte;
473                                 lastBlock = false;
474                         }
475
476                         // total may be 0 (e.g. PaddingMode.None)
477                         byte padding = ((total > 0) ? res [total - 1] : (byte) 0);
478 #if MOONLIGHT
479                         // only PKCS7 is supported Silverlight 2.0
480                         if ((padding == 0) || (padding > BlockSizeByte))
481                                 throw new CryptographicException (Locale.GetText ("Bad padding length."));
482                         for (int i = padding - 1; i > 0; i--) {
483                                 if (res [total - 1 - i] != padding)
484                                         throw new CryptographicException (Locale.GetText ("Bad padding at position {0}.", i));
485                         }
486                         total -= padding;
487 #else
488                         switch (algo.Padding) {
489                         case PaddingMode.ANSIX923:
490                                 if ((padding == 0) || (padding > BlockSizeByte))
491                                         ThrowBadPaddingException (algo.Padding, padding, -1);
492                                 for (int i = padding - 1; i > 0; i--) {
493                                         if (res [total - 1 - i] != 0x00)
494                                                 ThrowBadPaddingException (algo.Padding, -1, i);
495                                 }
496                                 total -= padding;
497                                 break;
498                         case PaddingMode.ISO10126:
499                                 if ((padding == 0) || (padding > BlockSizeByte))
500                                         ThrowBadPaddingException (algo.Padding, padding, -1);
501                                 total -= padding;
502                                 break;
503                         case PaddingMode.PKCS7:
504                                 if ((padding == 0) || (padding > BlockSizeByte))
505                                         ThrowBadPaddingException (algo.Padding, padding, -1);
506                                 for (int i = padding - 1; i > 0; i--) {
507                                         if (res [total - 1 - i] != padding)
508                                                 ThrowBadPaddingException (algo.Padding, -1, i);
509                                 }
510                                 total -= padding;
511                                 break;
512                         case PaddingMode.None:  // nothing to do - it's a multiple of block size
513                         case PaddingMode.Zeros: // nothing to do - user must unpad himself
514                                 break;
515                         }
516 #endif // NET_2_1
517
518                         // return output without padding
519                         if (total > 0) {
520                                 byte[] data = new byte [total];
521                                 Buffer.BlockCopy (res, 0, data, 0, total);
522                                 // zeroize decrypted data (copy with padding)
523                                 Array.Clear (res, 0, res.Length);
524                                 return data;
525                         }
526                         else
527                                 return new byte [0];
528                 }
529
530                 public virtual byte[] TransformFinalBlock (byte[] inputBuffer, int inputOffset, int inputCount) 
531                 {
532                         if (m_disposed)
533                                 throw new ObjectDisposedException ("Object is disposed");
534                         CheckInput (inputBuffer, inputOffset, inputCount);
535
536                         if (encrypt)
537                                 return FinalEncrypt (inputBuffer, inputOffset, inputCount);
538                         else
539                                 return FinalDecrypt (inputBuffer, inputOffset, inputCount);
540                 }
541         }
542 }