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-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.
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 private int FeedBackByte;
54 private int FeedBackIter;
55 private bool m_disposed = false;
56 private bool lastBlock;
58 public SymmetricTransform (SymmetricAlgorithm symmAlgo, bool encryption, byte[] rgbIV)
62 BlockSizeByte = (algo.BlockSize >> 3);
65 rgbIV = KeyBuilder.IV (BlockSizeByte);
67 rgbIV = (byte[]) rgbIV.Clone ();
70 // compare the IV length with the "currently selected" block size and *ignore* IV that are too big
71 if (rgbIV.Length < BlockSizeByte) {
72 string msg = Locale.GetText ("IV is too small ({0} bytes), it should be {1} bytes long.",
73 rgbIV.Length, BlockSizeByte);
74 throw new CryptographicException (msg);
78 temp = new byte [BlockSizeByte];
79 Buffer.BlockCopy (rgbIV, 0, temp, 0, System.Math.Min (BlockSizeByte, rgbIV.Length));
80 temp2 = new byte [BlockSizeByte];
81 FeedBackByte = (algo.FeedbackSize >> 3);
82 if (FeedBackByte != 0)
83 FeedBackIter = (int) BlockSizeByte / FeedBackByte;
85 workBuff = new byte [BlockSizeByte];
86 workout = new byte [BlockSizeByte];
89 ~SymmetricTransform ()
94 void IDisposable.Dispose ()
97 GC.SuppressFinalize (this); // Finalization is now unnecessary
100 // MUST be overriden by classes using unmanaged ressources
101 // the override method must call the base class
102 protected virtual void Dispose (bool disposing)
106 // dispose managed object: zeroize and free
107 Array.Clear (temp, 0, BlockSizeByte);
109 Array.Clear (temp2, 0, BlockSizeByte);
116 public virtual bool CanTransformMultipleBlocks {
120 public virtual bool CanReuseTransform {
121 get { return false; }
124 public virtual int InputBlockSize {
125 get { return BlockSizeByte; }
128 public virtual int OutputBlockSize {
129 get { return BlockSizeByte; }
132 // note: Each block MUST be BlockSizeValue in size!!!
133 // i.e. Any padding must be done before calling this method
134 protected virtual void Transform (byte[] input, byte[] output)
153 throw new NotImplementedException ("Unkown CipherMode" + algo.Mode.ToString ());
157 // Electronic Code Book (ECB)
158 protected abstract void ECB (byte[] input, byte[] output);
160 // Cipher-Block-Chaining (CBC)
161 protected virtual void CBC (byte[] input, byte[] output)
164 for (int i = 0; i < BlockSizeByte; i++)
167 Buffer.BlockCopy (output, 0, temp, 0, BlockSizeByte);
170 Buffer.BlockCopy (input, 0, temp2, 0, BlockSizeByte);
172 for (int i = 0; i < BlockSizeByte; i++)
173 output[i] ^= temp[i];
174 Buffer.BlockCopy (temp2, 0, temp, 0, BlockSizeByte);
178 // Cipher-FeedBack (CFB)
179 protected virtual void CFB (byte[] input, byte[] output)
182 for (int x = 0; x < FeedBackIter; x++) {
183 // temp is first initialized with the IV
186 for (int i = 0; i < FeedBackByte; i++)
187 output[i + x] = (byte)(temp2[i] ^ input[i + x]);
188 Buffer.BlockCopy (temp, FeedBackByte, temp, 0, BlockSizeByte - FeedBackByte);
189 Buffer.BlockCopy (output, x, temp, BlockSizeByte - FeedBackByte, FeedBackByte);
193 for (int x = 0; x < FeedBackIter; x++) {
194 // we do not really decrypt this data!
196 // temp is first initialized with the IV
200 Buffer.BlockCopy (temp, FeedBackByte, temp, 0, BlockSizeByte - FeedBackByte);
201 Buffer.BlockCopy (input, x, temp, BlockSizeByte - FeedBackByte, FeedBackByte);
202 for (int i = 0; i < FeedBackByte; i++)
203 output[i + x] = (byte)(temp2[i] ^ input[i + x]);
208 // Output-FeedBack (OFB)
209 protected virtual void OFB (byte[] input, byte[] output)
211 throw new CryptographicException ("OFB isn't supported by the framework");
214 // Cipher Text Stealing (CTS)
215 protected virtual void CTS (byte[] input, byte[] output)
217 throw new CryptographicException ("CTS isn't supported by the framework");
220 private void CheckInput (byte[] inputBuffer, int inputOffset, int inputCount)
222 if (inputBuffer == null)
223 throw new ArgumentNullException ("inputBuffer");
225 throw new ArgumentOutOfRangeException ("inputOffset", "< 0");
227 throw new ArgumentOutOfRangeException ("inputCount", "< 0");
228 // ordered to avoid possible integer overflow
229 if (inputOffset > inputBuffer.Length - inputCount)
230 throw new ArgumentException ("inputBuffer", Locale.GetText ("Overflow"));
233 // this method may get called MANY times so this is the one to optimize
234 public virtual int TransformBlock (byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
237 throw new ObjectDisposedException ("Object is disposed");
238 CheckInput (inputBuffer, inputOffset, inputCount);
239 // check output parameters
240 if (outputBuffer == null)
241 throw new ArgumentNullException ("outputBuffer");
242 if (outputOffset < 0)
243 throw new ArgumentOutOfRangeException ("outputOffset", "< 0");
244 // ordered to avoid possible integer overflow
245 if (outputOffset > outputBuffer.Length - inputCount) {
246 // there's a special case if this is the end of the decryption process
247 if (inputBuffer.Length - inputOffset - outputBuffer.Length == BlockSizeByte)
248 inputCount = inputCount = outputBuffer.Length - outputOffset;
250 throw new CryptographicException ("outputBuffer", Locale.GetText ("Overflow"));
252 return InternalTransformBlock (inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
255 private bool KeepLastBlock {
257 return ((!encrypt) && (algo.Mode != CipherMode.ECB) && (algo.Padding != PaddingMode.None));
261 private int InternalTransformBlock (byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
263 int offs = inputOffset;
266 // this way we don't do a modulo every time we're called
267 // and we may save a division
268 if (inputCount != BlockSizeByte) {
269 if ((inputCount % BlockSizeByte) != 0)
270 throw new CryptographicException ("Invalid input block size.");
272 full = inputCount / BlockSizeByte;
283 Transform (workBuff, workout);
284 Buffer.BlockCopy (workout, 0, outputBuffer, outputOffset, BlockSizeByte);
285 outputOffset += BlockSizeByte;
286 total += BlockSizeByte;
290 for (int i = 0; i < full; i++) {
291 Buffer.BlockCopy (inputBuffer, offs, workBuff, 0, BlockSizeByte);
292 Transform (workBuff, workout);
293 Buffer.BlockCopy (workout, 0, outputBuffer, outputOffset, BlockSizeByte);
294 offs += BlockSizeByte;
295 outputOffset += BlockSizeByte;
296 total += BlockSizeByte;
300 Buffer.BlockCopy (inputBuffer, offs, workBuff, 0, BlockSizeByte);
308 RandomNumberGenerator _rng;
310 private void Random (byte[] buffer, int start, int length)
313 _rng = RandomNumberGenerator.Create ();
315 byte[] random = new byte [length];
316 _rng.GetBytes (random);
317 Buffer.BlockCopy (random, 0, buffer, start, length);
320 private void ThrowBadPaddingException (PaddingMode padding, int length, int position)
322 string msg = String.Format (Locale.GetText ("Bad {0} padding."), padding);
324 msg += String.Format (Locale.GetText (" Invalid length {0}."), length);
326 msg += String.Format (Locale.GetText (" Error found at position {0}."), position);
327 throw new CryptographicException (msg);
331 private byte[] FinalEncrypt (byte[] inputBuffer, int inputOffset, int inputCount)
333 // are there still full block to process ?
334 int full = (inputCount / BlockSizeByte) * BlockSizeByte;
335 int rem = inputCount - full;
338 switch (algo.Padding) {
340 case PaddingMode.ANSIX923:
341 case PaddingMode.ISO10126:
343 case PaddingMode.PKCS7:
344 // we need to add an extra block for padding
345 total += BlockSizeByte;
351 if (algo.Padding == PaddingMode.None)
352 throw new CryptographicException ("invalid block length");
353 // zero padding the input (by adding a block for the partial data)
354 byte[] paddedInput = new byte [full + BlockSizeByte];
355 Buffer.BlockCopy (inputBuffer, inputOffset, paddedInput, 0, inputCount);
356 inputBuffer = paddedInput;
358 inputCount = paddedInput.Length;
364 byte[] res = new byte [total];
365 int outputOffset = 0;
367 // process all blocks except the last (final) block
368 while (total > BlockSizeByte) {
369 InternalTransformBlock (inputBuffer, inputOffset, BlockSizeByte, res, outputOffset);
370 inputOffset += BlockSizeByte;
371 outputOffset += BlockSizeByte;
372 total -= BlockSizeByte;
375 // now we only have a single last block to encrypt
376 byte padding = (byte) (BlockSizeByte - rem);
377 switch (algo.Padding) {
379 case PaddingMode.ANSIX923:
380 // XX 00 00 00 00 00 00 07 (zero + padding length)
381 res [res.Length - 1] = padding;
382 Buffer.BlockCopy (inputBuffer, inputOffset, res, full, rem);
383 // the last padded block will be transformed in-place
384 InternalTransformBlock (res, full, BlockSizeByte, res, full);
386 case PaddingMode.ISO10126:
387 // XX 3F 52 2A 81 AB F7 07 (random + padding length)
388 Random (res, res.Length - padding, padding - 1);
389 res [res.Length - 1] = padding;
390 Buffer.BlockCopy (inputBuffer, inputOffset, res, full, rem);
391 // the last padded block will be transformed in-place
392 InternalTransformBlock (res, full, BlockSizeByte, res, full);
395 case PaddingMode.PKCS7:
396 // XX 07 07 07 07 07 07 07 (padding length)
397 for (int i = res.Length; --i >= (res.Length - padding);)
399 Buffer.BlockCopy (inputBuffer, inputOffset, res, full, rem);
400 // the last padded block will be transformed in-place
401 InternalTransformBlock (res, full, BlockSizeByte, res, full);
404 InternalTransformBlock (inputBuffer, inputOffset, BlockSizeByte, res, outputOffset);
410 private byte[] FinalDecrypt (byte[] inputBuffer, int inputOffset, int inputCount)
412 if ((inputCount % BlockSizeByte) > 0)
413 throw new CryptographicException ("Invalid input block size.");
415 int total = inputCount;
417 total += BlockSizeByte;
419 byte[] res = new byte [total];
420 int outputOffset = 0;
422 while (inputCount > 0) {
423 int len = InternalTransformBlock (inputBuffer, inputOffset, BlockSizeByte, res, outputOffset);
424 inputOffset += BlockSizeByte;
426 inputCount -= BlockSizeByte;
430 Transform (workBuff, workout);
431 Buffer.BlockCopy (workout, 0, res, outputOffset, BlockSizeByte);
432 outputOffset += BlockSizeByte;
436 // total may be 0 (e.g. PaddingMode.None)
437 byte padding = ((total > 0) ? res [total - 1] : (byte) 0);
438 switch (algo.Padding) {
440 case PaddingMode.ANSIX923:
441 if ((padding == 0) || (padding > BlockSizeByte))
442 ThrowBadPaddingException (algo.Padding, padding, -1);
443 for (int i=padding; i > 0; i--) {
444 if (res [total - 1 - i] != 0x00)
445 ThrowBadPaddingException (algo.Padding, -1, i);
449 case PaddingMode.ISO10126:
450 if ((padding == 0) || (padding > BlockSizeByte))
451 ThrowBadPaddingException (algo.Padding, padding, -1);
454 case PaddingMode.PKCS7:
455 if ((padding == 0) || (padding > BlockSizeByte))
456 ThrowBadPaddingException (algo.Padding, padding, -1);
457 for (int i=padding - 1; i > 0; i--) {
458 if (res [total - 1 - i] != padding)
459 ThrowBadPaddingException (algo.Padding, -1, i);
464 case PaddingMode.PKCS7:
468 case PaddingMode.None: // nothing to do - it's a multiple of block size
469 case PaddingMode.Zeros: // nothing to do - user must unpad himself
473 // return output without padding
475 byte[] data = new byte [total];
476 Buffer.BlockCopy (res, 0, data, 0, total);
477 // zeroize decrypted data (copy with padding)
478 Array.Clear (res, 0, res.Length);
485 public virtual byte[] TransformFinalBlock (byte[] inputBuffer, int inputOffset, int inputCount)
488 throw new ObjectDisposedException ("Object is disposed");
489 CheckInput (inputBuffer, inputOffset, inputCount);
492 return FinalEncrypt (inputBuffer, inputOffset, inputCount);
494 return FinalDecrypt (inputBuffer, inputOffset, inputCount);