#include <cctype>
#include <cstring>

unsigned char hex2uchar( const char c )
{
    if ( isdigit( c ) )
    {
        return c - '0';
    }
    if ( c >= 'A' && c <= 'F' )
    {
        return c - 'A';
    }
    if ( c >= 'a' && c <= 'f' )
    {
        return c - 'a';
    }
    return 0;
}

int makeKey( const char* keyText, unsigned char key[32] )
{
    int keyLen = 16;

    int keyTextLen = strlen( keyText );

    int hex = false;

    if ( keyTextLen == 32 || keyTextLen == 48 || keyTextLen == 64 )
    {
        hex = true;
        for ( int i = 0; i < keyTextLen ; ++i )
        {
            char c = keyText[i];
            if ( !(( c >= '0' && c <= '9' ) || ( c >= 'A' && c <= 'F' ) || ( c >= 'a' && c <= 'f' ) ) )
            {
                hex = false;
                break;
            }
        }
    }

    // Figure out the key length
    if ( hex )
    {
        keyLen = keyTextLen / 2;
    }
    else
    {
        if ( keyTextLen <= 16 )
        {
            keyLen = 16;
        }
        else if ( keyTextLen <= 24 )
        {
            keyLen = 24;
        }
        else
        {
            keyLen = 32;
        }
    }

    // Copy the key
    if ( hex )
    {
        for ( int i = 0; i < keyLen; i++ )
        {
            key[i] = ( hex2uchar( keyText[i*2] ) << 4 ) + hex2uchar( keyText[i*2+1] );
        }
    }
    else
    {
        for ( int i = 0; i < keyLen; i++ )
        {
            key[i] = keyText[i%keyTextLen];
        }
    }

    return keyLen;
}

