2 // Mono.Security.Cryptography.SymmetricTransform implementation
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-2008 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.
32 using System.Security.Cryptography;
34 namespace Mono.Security.Cryptography {
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...
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;
51 private byte[] workBuff;
52 private byte[] workout;
53 #if !NET_2_1 || MONOTOUCH
54 // Silverlight 2.0 does not support any feedback mode
55 private int FeedBackByte;
56 private int FeedBackIter;
58 private bool m_disposed = false;
59 private bool lastBlock;
61 public SymmetricTransform (SymmetricAlgorithm symmAlgo, bool encryption, byte[] rgbIV)
65 BlockSizeByte = (algo.BlockSize >> 3);
68 rgbIV = KeyBuilder.IV (BlockSizeByte);
70 rgbIV = (byte[]) rgbIV.Clone ();
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);
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 !NET_2_1 || MONOTOUCH
84 FeedBackByte = (algo.FeedbackSize >> 3);
85 if (FeedBackByte != 0)
86 FeedBackIter = (int) BlockSizeByte / FeedBackByte;
89 workBuff = new byte [BlockSizeByte];
90 workout = new byte [BlockSizeByte];
93 ~SymmetricTransform ()
98 void IDisposable.Dispose ()
101 GC.SuppressFinalize (this); // Finalization is now unnecessary
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)
110 // dispose managed object: zeroize and free
111 Array.Clear (temp, 0, BlockSizeByte);
113 Array.Clear (temp2, 0, BlockSizeByte);
120 public virtual bool CanTransformMultipleBlocks {
124 public virtual bool CanReuseTransform {
125 get { return false; }
128 public virtual int InputBlockSize {
129 get { return BlockSizeByte; }
132 public virtual int OutputBlockSize {
133 get { return BlockSizeByte; }
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)
140 #if NET_2_1 && !MONOTOUCH
141 // Silverlight 2.0 only supports CBC
161 throw new NotImplementedException ("Unkown CipherMode" + algo.Mode.ToString ());
166 // Electronic Code Book (ECB)
167 protected abstract void ECB (byte[] input, byte[] output);
169 // Cipher-Block-Chaining (CBC)
170 protected virtual void CBC (byte[] input, byte[] output)
173 for (int i = 0; i < BlockSizeByte; i++)
176 Buffer.BlockCopy (output, 0, temp, 0, BlockSizeByte);
179 Buffer.BlockCopy (input, 0, temp2, 0, BlockSizeByte);
181 for (int i = 0; i < BlockSizeByte; i++)
182 output[i] ^= temp[i];
183 Buffer.BlockCopy (temp2, 0, temp, 0, BlockSizeByte);
187 #if !NET_2_1 || MONOTOUCH
188 // Cipher-FeedBack (CFB)
189 protected virtual void CFB (byte[] input, byte[] output)
192 for (int x = 0; x < FeedBackIter; x++) {
193 // temp is first initialized with the IV
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);
203 for (int x = 0; x < FeedBackIter; x++) {
204 // we do not really decrypt this data!
206 // temp is first initialized with the IV
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]);
218 // Output-FeedBack (OFB)
219 protected virtual void OFB (byte[] input, byte[] output)
221 throw new CryptographicException ("OFB isn't supported by the framework");
224 // Cipher Text Stealing (CTS)
225 protected virtual void CTS (byte[] input, byte[] output)
227 throw new CryptographicException ("CTS isn't supported by the framework");
231 private void CheckInput (byte[] inputBuffer, int inputOffset, int inputCount)
233 if (inputBuffer == null)
234 throw new ArgumentNullException ("inputBuffer");
236 throw new ArgumentOutOfRangeException ("inputOffset", "< 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"));
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)
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");
256 // ordered to avoid possible integer overflow
257 int len = outputBuffer.Length - inputCount - outputOffset;
258 #if NET_2_1 && !MONOTOUCH
259 // only PKCS7 is supported Silverlight 2.0
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) {
266 if (0 > len + BlockSizeByte) {
267 throw new CryptographicException ("outputBuffer", Locale.GetText ("Overflow"));
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;
275 throw new CryptographicException ("outputBuffer", Locale.GetText ("Overflow"));
278 return InternalTransformBlock (inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
281 private bool KeepLastBlock {
283 #if NET_2_1 && !MONOTOUCH
284 // only PKCS7 is supported Silverlight 2.0
287 return ((!encrypt) && (algo.Padding != PaddingMode.None) && (algo.Padding != PaddingMode.Zeros));
292 private int InternalTransformBlock (byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
294 int offs = inputOffset;
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.");
303 full = inputCount / BlockSizeByte;
314 Transform (workBuff, workout);
315 Buffer.BlockCopy (workout, 0, outputBuffer, outputOffset, BlockSizeByte);
316 outputOffset += BlockSizeByte;
317 total += BlockSizeByte;
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;
331 Buffer.BlockCopy (inputBuffer, offs, workBuff, 0, BlockSizeByte);
338 #if (!NET_2_1 || MONOTOUCH)
339 RandomNumberGenerator _rng;
341 private void Random (byte[] buffer, int start, int length)
344 _rng = RandomNumberGenerator.Create ();
346 byte[] random = new byte [length];
347 _rng.GetBytes (random);
348 Buffer.BlockCopy (random, 0, buffer, start, length);
351 private void ThrowBadPaddingException (PaddingMode padding, int length, int position)
353 string msg = String.Format (Locale.GetText ("Bad {0} padding."), padding);
355 msg += String.Format (Locale.GetText (" Invalid length {0}."), length);
357 msg += String.Format (Locale.GetText (" Error found at position {0}."), position);
358 throw new CryptographicException (msg);
362 private byte[] FinalEncrypt (byte[] inputBuffer, int inputOffset, int inputCount)
364 // are there still full block to process ?
365 int full = (inputCount / BlockSizeByte) * BlockSizeByte;
366 int rem = inputCount - full;
369 #if NET_2_1 && !MONOTOUCH
370 // only PKCS7 is supported Silverlight 2.0
371 total += BlockSizeByte;
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;
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;
391 inputCount = paddedInput.Length;
398 byte[] res = new byte [total];
399 int outputOffset = 0;
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;
409 // now we only have a single last block to encrypt
410 byte padding = (byte) (BlockSizeByte - rem);
411 #if NET_2_1 && !MONOTOUCH
412 // only PKCS7 is supported Silverlight 2.0
413 for (int i = res.Length; --i >= (res.Length - padding);)
415 Buffer.BlockCopy (inputBuffer, inputOffset, res, full, rem);
416 InternalTransformBlock (res, full, BlockSizeByte, res, full);
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);
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);
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);)
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);
443 InternalTransformBlock (inputBuffer, inputOffset, BlockSizeByte, res, outputOffset);
450 private byte[] FinalDecrypt (byte[] inputBuffer, int inputOffset, int inputCount)
452 if ((inputCount % BlockSizeByte) > 0)
453 throw new CryptographicException ("Invalid input block size.");
455 int total = inputCount;
457 total += BlockSizeByte;
459 byte[] res = new byte [total];
460 int outputOffset = 0;
462 while (inputCount > 0) {
463 int len = InternalTransformBlock (inputBuffer, inputOffset, BlockSizeByte, res, outputOffset);
464 inputOffset += BlockSizeByte;
466 inputCount -= BlockSizeByte;
470 Transform (workBuff, workout);
471 Buffer.BlockCopy (workout, 0, res, outputOffset, BlockSizeByte);
472 outputOffset += BlockSizeByte;
476 // total may be 0 (e.g. PaddingMode.None)
477 byte padding = ((total > 0) ? res [total - 1] : (byte) 0);
478 #if NET_2_1 && !MONOTOUCH
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));
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);
498 case PaddingMode.ISO10126:
499 if ((padding == 0) || (padding > BlockSizeByte))
500 ThrowBadPaddingException (algo.Padding, padding, -1);
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);
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
518 // return output without padding
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);
530 public virtual byte[] TransformFinalBlock (byte[] inputBuffer, int inputOffset, int inputCount)
533 throw new ObjectDisposedException ("Object is disposed");
534 CheckInput (inputBuffer, inputOffset, inputCount);
537 return FinalEncrypt (inputBuffer, inputOffset, inputCount);
539 return FinalDecrypt (inputBuffer, inputOffset, inputCount);