aboutsummaryrefslogtreecommitdiff
path: root/src/unstable/ciphermodeofb.h
blob: 19d0f837ba19aad2bd7893fa2fee89b2ef186c47 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#ifndef BU_MODE_OFB_H
#define BU_MODE_OFB_H

#include "bu/filter.h"
#include "bu/string.h"

namespace Bu
{
    /**
     * Output Feedback Mode.  This cipher mode is one of the most resiliant.
     * Instead of encrypting your data directly it encrypts a "key stream" using
     * the initialization vector, and then XORs those blocks with your stream
     * blocks.  This means that an error in your stream will still produce an
     * error in the output, but it will not propegate.  Also, with most
     * encryption schemes error correction codes on the source data will still
     * work on the encrypted data or decrypted output.
     */
    template<int iBlockSize, typename CipherType>
    class CipherModeOfb : public CipherType
    {
    public:
        CipherModeOfb(class Stream &rNext ) :
            CipherType( rNext ),
            bStart( true )
        {
            memset( aVector, 0, iBlockSize );
        }

        virtual ~CipherModeOfb()
        {
        }

        void setIv( const Bu::String &sIv )
        {
            memcpy( aVector, sIv.getStr(), iBlockSize );
        }

    protected:
        void decipher( void *pBuf )
        {
            CipherType::encipher( aVector );
            uint8_t aTmp[iBlockSize];
            memcpy( aTmp, aVector, iBlockSize );
            for( int j = 0; j < iBlockSize; j++ )
                ((uint8_t *)pBuf)[j] ^= aVector[j];
            memcpy( aVector, aTmp, iBlockSize );
        }

        void encipher( void *pBuf )
        {
            CipherType::encipher( aVector );
            uint8_t aTmp[iBlockSize];
            memcpy( aTmp, aVector, iBlockSize );
            for( int j = 0; j < iBlockSize; j++ )
                ((uint8_t *)pBuf)[j] ^= aVector[j];
            memcpy( aVector, aTmp, iBlockSize );
        }

    private:
        bool bStart;
        uint8_t aVector[iBlockSize];
    };
};

#endif