comparison dcrypt/crypto/modes/CTR.d @ 12:8c7f8fecdd75

Added ManagedBlockCipher, changed Crypto to just import everything, made Hash.update() return itself (for chaining) and ditched BlockCipherWrapper.
author Thomas Dixon <reikon@reikon.us>
date Sat, 30 Aug 2008 14:38:23 -0400
parents cd376996cdb3
children 4589f8c5eb3c
comparison
equal deleted inserted replaced
11:02970e63257d 12:8c7f8fecdd75
7 */ 7 */
8 8
9 module dcrypt.crypto.modes.CTR; 9 module dcrypt.crypto.modes.CTR;
10 10
11 import dcrypt.crypto.BlockCipher; 11 import dcrypt.crypto.BlockCipher;
12 import dcrypt.crypto.params.ParametersWithIV; 12 public import dcrypt.crypto.params.ParametersWithIV;
13 13
14 14
15 /** This class implements the counter (CTR/SIC/ICM) block mode, 15 /** This class implements the counter (CTR/SIC/ICM) block mode,
16 treating the counter as a big endian integer. */ 16 treating the counter as a big endian integer. */
17 class CTR : BlockCipher { 17 class CTR : BlockCipher {
60 counterOutput = new ubyte[blockSize]; 60 counterOutput = new ubyte[blockSize];
61 61
62 initialized = true; 62 initialized = true;
63 } 63 }
64 64
65 ubyte[] process(void[] input_) { 65 uint update(void[] input_, void[] output_) {
66 if (!initialized) 66 if (!initialized)
67 throw new NotInitializedError( 67 throw new NotInitializedError(
68 name()~": Block mode not initialized"); 68 name()~": Block mode not initialized");
69 69
70 ubyte[] input = cast(ubyte[]) input_; 70 ubyte[] input = cast(ubyte[]) input_,
71 output = cast(ubyte[]) output_;
72
71 uint len = (counter.length > input.length) ? input.length : counter.length; 73 uint len = (counter.length > input.length) ? input.length : counter.length;
72 74
75 if (len > output.length)
76 throw new ShortBufferError(name()~": Output buffer too short");
77
73 // Encrypt the counter 78 // Encrypt the counter
74 counterOutput[] = m_cipher.process(counter); 79 m_cipher.update(counter, counterOutput);
75 80
76 // XOR output with plaintext to create ciphertext 81 // XOR output with plaintext to create ciphertext
77 for (int i = 0; i < len; i++) 82 for (int i = 0; i < len; i++)
78 counterOutput[i] ^= input[i]; 83 counterOutput[i] ^= input[i];
79 84
80 // Increment the counter 85 // Increment the counter
81 for (int i = counter.length-1; i >= 0; i--) 86 for (int i = counter.length-1; i >= 0; i--)
82 if (++counter[i]) break; 87 if (++counter[i]) break;
83 88
84 return counterOutput[0..len]; 89 output[0..len] = counterOutput[0..len];
90
91 return len;
85 } 92 }
86 93
87 uint blockSize() { 94 uint blockSize() {
88 return m_cipher.blockSize; 95 return m_cipher.blockSize;
89 } 96 }