/***************************************************************************
                          cssl.h  -  description
                             -------------------
    begin                : Sat Dec 7 2002
    copyright            : (C) 2002-2003 by Mathias Küster
    email                : mathen@users.berlios.de
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#ifndef CSSL_H
#define CSSL_H

/**
  *@author Mathias Küster
  */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#ifdef HAVE_SSL
#include <openssl/opensslv.h>
#include <openssl/rsa.h>
#include <openssl/rand.h>
#include <openssl/evp.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#endif

#include <dclib/dcos.h>
#include <dclib/core/cobject.h>
#include <dclib/core/cstringlist.h>

#ifdef HAVE_SSL

class DLL_EXPORT CSSLObject : public CObject {
public:
	/** */
	CSSLObject() {
		m_bHandshakeState = 0;
		m_pRSA            = 0;
	};
	/** */
	virtual ~CSSLObject() {
		if ( m_pRSA )
			RSA_free(m_pRSA);
	};

	/** */
	int m_bHandshakeState;
	/* */
	RSA * m_pRSA;
	/** */
	unsigned char m_localkey[16];
	/** */
	unsigned char m_localiv[8];
	/** */
	unsigned char m_remotekey[16];
	/** */
	unsigned char m_remoteiv[8];
};

#endif

class DLL_EXPORT CSSL : public CObject {
public:
	/** */
	CSSL();
	/** */
	virtual ~CSSL();

#ifdef HAVE_SSL
	/** */
	SSL_CTX * InitClientCTX();
	/** */
	SSL_CTX * InitServerCTX();
	/** */
	bool LoadCertificates( SSL_CTX * ctx, char * CertFile, char * KeyFile );
#endif

protected:
#ifdef HAVE_SSL
	/** */
	void InitRand();
	/** */
	void InitRandArray( unsigned char * a, int len );
	/** */
	bool GenerateRsaKey();
	/** */
	CString GetPublicRsaKey();
	/** */
	bool SetPublicKey( CSSLObject * SSLObject, CString s );
	/** */
	void InitSessionKey( CSSLObject * SSLObject );
	/** */
	CString GetSessionKey( CSSLObject * SSLObject );
	/** */
	bool SetSessionKey( CSSLObject * SSLObject, CString s );
	/** */
	CString EncryptData( CSSLObject * SSLObject, CString s );
	/** */
	CString DecryptData( CSSLObject * SSLObject, CString s );

#endif

#ifdef HAVE_SSL
	/* */
	RSA * m_pRSA;
	/** */
	int * m_pRandBuffer;
#endif
};

#endif
