Botan  1.11.15
src/lib/mac/cbc_mac/cbc_mac.cpp
Go to the documentation of this file.
00001 /*
00002 * CBC-MAC
00003 * (C) 1999-2007 Jack Lloyd
00004 *
00005 * Botan is released under the Simplified BSD License (see license.txt)
00006 */
00007 
00008 #include <botan/internal/mac_utils.h>
00009 #include <botan/cbc_mac.h>
00010 
00011 namespace Botan {
00012 
00013 CBC_MAC* CBC_MAC::make(const Spec& spec)
00014    {
00015    if(spec.arg_count() == 1)
00016       return new CBC_MAC(Algo_Registry<BlockCipher>::global_registry().make(spec.arg(0)));
00017    return nullptr;
00018    }
00019 
00020 BOTAN_REGISTER_NAMED_T(MessageAuthenticationCode, "CBC-MAC", CBC_MAC, CBC_MAC::make);
00021 
00022 /*
00023 * Update an CBC-MAC Calculation
00024 */
00025 void CBC_MAC::add_data(const byte input[], size_t length)
00026    {
00027    size_t xored = std::min(output_length() - m_position, length);
00028    xor_buf(&m_state[m_position], input, xored);
00029    m_position += xored;
00030 
00031    if(m_position < output_length())
00032       return;
00033 
00034    m_cipher->encrypt(m_state);
00035    input += xored;
00036    length -= xored;
00037    while(length >= output_length())
00038       {
00039       xor_buf(m_state, input, output_length());
00040       m_cipher->encrypt(m_state);
00041       input += output_length();
00042       length -= output_length();
00043       }
00044 
00045    xor_buf(m_state, input, length);
00046    m_position = length;
00047    }
00048 
00049 /*
00050 * Finalize an CBC-MAC Calculation
00051 */
00052 void CBC_MAC::final_result(byte mac[])
00053    {
00054    if(m_position)
00055       m_cipher->encrypt(m_state);
00056 
00057    copy_mem(mac, &m_state[0], m_state.size());
00058    zeroise(m_state);
00059    m_position = 0;
00060    }
00061 
00062 /*
00063 * CBC-MAC Key Schedule
00064 */
00065 void CBC_MAC::key_schedule(const byte key[], size_t length)
00066    {
00067    m_cipher->set_key(key, length);
00068    }
00069 
00070 /*
00071 * Clear memory of sensitive data
00072 */
00073 void CBC_MAC::clear()
00074    {
00075    m_cipher->clear();
00076    zeroise(m_state);
00077    m_position = 0;
00078    }
00079 
00080 /*
00081 * Return the name of this type
00082 */
00083 std::string CBC_MAC::name() const
00084    {
00085    return "CBC-MAC(" + m_cipher->name() + ")";
00086    }
00087 
00088 /*
00089 * Return a clone of this object
00090 */
00091 MessageAuthenticationCode* CBC_MAC::clone() const
00092    {
00093    return new CBC_MAC(m_cipher->clone());
00094    }
00095 
00096 /*
00097 * CBC-MAC Constructor
00098 */
00099 CBC_MAC::CBC_MAC(BlockCipher* cipher) :
00100    m_cipher(cipher), m_state(cipher->block_size())
00101    {
00102    }
00103 
00104 }