2 // TripleDESCryptoServiceProvider.cs: Default TripleDES implementation
5 // Sebastien Pouliot (spouliot@motus.com)
7 // (C) 2002 Motus Technologies Inc. (http://www.motus.com)
12 namespace System.Security.Cryptography {
15 // a. FIPS PUB 46-3: TripleDES
16 // http://csrc.nist.gov/publications/fips/fips46-3/fips46-3.pdf
19 // http://webstore.ansi.org/ansidocstore/product.asp?sku=ANSI+X9%2E52%2D1998
21 public sealed class TripleDESCryptoServiceProvider : TripleDES {
23 public TripleDESCryptoServiceProvider () {}
25 public override void GenerateIV ()
27 IVValue = KeyBuilder.IV (BlockSizeValue >> 3);
30 public override void GenerateKey ()
32 KeyValue = KeyBuilder.Key (KeySizeValue >> 3);
35 public override ICryptoTransform CreateDecryptor (byte[] rgbKey, byte[] rgbIV)
39 return new TripleDESTransform (this, false, rgbKey, rgbIV);
42 public override ICryptoTransform CreateEncryptor (byte[] rgbKey, byte[] rgbIV)
46 return new TripleDESTransform (this, true, rgbKey, rgbIV);
50 // TripleDES is just DES-EDE
51 internal class TripleDESTransform : SymmetricTransform {
54 private DESTransform E1;
55 private DESTransform D2;
56 private DESTransform E3;
59 private DESTransform D1;
60 private DESTransform E2;
61 private DESTransform D3;
63 public TripleDESTransform (TripleDES algo, bool encryption, byte[] key, byte[] iv) : base (algo, encryption, iv)
65 byte[] key1 = new byte [8];
66 byte[] key2 = new byte [8];
67 byte[] key3 = new byte [8];
68 DES des = DES.Create ();
69 Array.Copy (key, 0, key1, 0, 8);
70 Array.Copy (key, 8, key2, 0, 8);
72 Array.Copy (key, 0, key3, 0, 8);
74 Array.Copy (key, 16, key3, 0, 8);
76 // note: some modes (like CFB) requires encryption when decrypting
77 if ((encryption) || (algo.Mode == CipherMode.CFB)) {
78 E1 = new DESTransform (des, true, key1, iv);
79 D2 = new DESTransform (des, false, key2, iv);
80 E3 = new DESTransform (des, true, key3, iv);
83 D1 = new DESTransform (des, false, key3, iv);
84 E2 = new DESTransform (des, true, key2, iv);
85 D3 = new DESTransform (des, false, key1, iv);
89 // note: this method is garanteed to be called with a valid blocksize
90 // for both input and output
91 protected override void ECB (byte[] input, byte[] output)
93 byte[] temp = new byte [input.Length];
95 E1.ProcessBlock (input, output);
96 D2.ProcessBlock (output, temp);
97 E3.ProcessBlock (temp, output);
100 D1.ProcessBlock (input, output);
101 E2.ProcessBlock (output, temp);
102 D3.ProcessBlock (temp, output);