#include "clientauthenticationresponsemessage.h"
#include <QIODevice>

extern "C" {
#include "d3des.h"
}

ClientAuthenticationResponseMessage::ClientAuthenticationResponseMessage() : ClientMessageBase()
{
}

void ClientAuthenticationResponseMessage::writeBytes( QIODevice *device ) const
{
    device->write( hash() );
}

void ClientAuthenticationResponseMessage::setChallenge( const QByteArray &challenge )
{
    m_challenge = challenge;
}

void ClientAuthenticationResponseMessage::setPassword( const QByteArray &password )
{
    m_password = password;
}

QByteArray ClientAuthenticationResponseMessage::challenge() const
{
    return m_challenge;
}

QByteArray ClientAuthenticationResponseMessage::password() const
{
    return m_password;
}

QByteArray ClientAuthenticationResponseMessage::hash() const
{
    QByteArray outputBytes = m_challenge;
    QByteArray key = m_password.leftJustified(16,'\0',true);

    unsigned char *output = (unsigned char*) outputBytes.data();
    ::deskey( (unsigned char*)key.data(), EN0);
    for (int idx = 0; idx < 16; idx += 8)
       ::des(output + idx, output + idx);
    return outputBytes;
}

QDebug operator <<( QDebug in, ClientAuthenticationResponseMessage & message )
{
        in << QString("Client authentication response message. Challenge: %1, Password: %2, Hash: %3")
                .arg( message.challenge().toHex().constData())
                .arg(message.password().constData())
                .arg(message.hash().toHex().constData());
        return in;
}

