Mercurial > projects > dcrypt
view dcrypt/crypto/modes/CTR.d @ 10:cd376996cdb3
Renamed SymmetricCipher back to Cipher (we don't support any other kind atm, I'll deal with it when we do.). Added BlockCipherWrapper for the encryption of arbitrary streams with or without padding. Removed hashByName, and replaced it with createHash. Re-did the high-level API, and filled out Crypto. Added cipher creation via createCipher. Added dsk to the CONTRIBUTORS file for helping with the design of the high-level API.
author | Thomas Dixon <reikon@reikon.us> |
---|---|
date | Wed, 20 Aug 2008 20:08:07 -0400 |
parents | 23c62e28b3a4 |
children | 8c7f8fecdd75 |
line wrap: on
line source
/** * This file is part of the dcrypt project. * * Copyright: Copyright (C) dcrypt contributors 2008. All rights reserved. * License: MIT * Authors: Thomas Dixon */ module dcrypt.crypto.modes.CTR; import dcrypt.crypto.BlockCipher; import dcrypt.crypto.params.ParametersWithIV; /** This class implements the counter (CTR/SIC/ICM) block mode, treating the counter as a big endian integer. */ class CTR : BlockCipher { private BlockCipher m_cipher; private ubyte[] iv, counter, counterOutput; private bool initialized = false; /** * Params: * cipher = Block cipher to wrap. */ this (BlockCipher cipher) { m_cipher = cipher; } /** Returns: The underlying cipher we are wrapping. */ BlockCipher cipher() { return m_cipher; } char[] name() { return m_cipher.name~"/CTR"; } /** * Throws: dcrypt.crypto.errors.InvalidParameterError if params aren't * an instance of dcrypt.crypto.params.ParametersWithIV. */ void init(bool encrypt, CipherParameters params) { ParametersWithIV ivParams = cast(ParametersWithIV)params; if (!ivParams) throw new InvalidParameterError( name()~": Block mode requires IV (use ParametersWithIV)"); if (ivParams.iv.length != blockSize) throw new InvalidParameterError( name()~": IV must be same length as cipher block size"); m_cipher.init(true, ivParams.parameters); iv = ivParams.iv[0..blockSize]; counter = new ubyte[blockSize]; counter[] = iv; counterOutput = new ubyte[blockSize]; initialized = true; } ubyte[] process(void[] input_) { if (!initialized) throw new NotInitializedError( name()~": Block mode not initialized"); ubyte[] input = cast(ubyte[]) input_; uint len = (counter.length > input.length) ? input.length : counter.length; // Encrypt the counter counterOutput[] = m_cipher.process(counter); // XOR output with plaintext to create ciphertext for (int i = 0; i < len; i++) counterOutput[i] ^= input[i]; // Increment the counter for (int i = counter.length-1; i >= 0; i--) if (++counter[i]) break; return counterOutput[0..len]; } uint blockSize() { return m_cipher.blockSize; } void reset() { counter[] = iv; m_cipher.reset(); } }