/*
 * Softcam plugin to VDR (C++)
 *
 * This code 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.
 *
 * This code is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 * Or, point your browser to http://www.gnu.org/copyleft/gpl.html
 */

#ifndef ___CRYPTO_H
#define ___CRYPTO_H

// ----------------------------------------------------------------

#ifdef CRYPTO_DES

#define DES_LEFT    0
#define DES_RIGHT   1

#define DES_HASH    8
#define DES_PC1    16
#define DES_IP     32
#define DES_FP     64
#define DES_MOD   128

// common DES modes

#define DES_ENCRYPT   (DES_LEFT|DES_PC1|DES_IP|DES_FP)
#define DES_DECRYPT   (DES_RIGHT|DES_PC1|DES_IP|DES_FP)

#define VIA_DES       (DES_LEFT|DES_MOD)
#define VIA_DES_HASH  (DES_LEFT|DES_HASH|DES_MOD)
#define SECA_DES_ENCR  DES_ENCRYPT
#define SECA_DES_DECR  DES_DECRYPT
#define NAGRA_DES_ENCR DES_ENCRYPT
#define NAGRA_DES_DECR DES_DECRYPT

class cDes {
private:
  static const unsigned char _E[], S[][64], _P[], _PC1[], _PC2[], LS[], IP[], FP[];
  const unsigned char *PC1, *PC2;
  unsigned char E[48], P[32];
  //
  void Permute(unsigned char *data, const unsigned char *P, int n);
protected:
  virtual unsigned int Mod(unsigned int R, unsigned int key7) { return R; }
public:
  cDes(const unsigned char *pc1=0, const unsigned char *pc2=0);
  void Des(unsigned char *data, const unsigned char *key, int mode);
  };

#endif //CRYPTO_DES

// ----------------------------------------------------------------

#ifdef CRYPTO_AES

#ifndef OPENSSL_HAS_AES
#include "support/aes.h"
#else
#include <openssl/aes.h>
#endif

class cAES {
private:
  bool active;
  AES_KEY dkey, ekey;
protected:
  void SetKey(const unsigned char *key);
  void Decrypt(unsigned char *data, int len);
  int Encrypt(const unsigned char *data, int len, unsigned char *crypt);
public:
  cAES(void);
  };

#endif //CRYPTO_AES

// ----------------------------------------------------------------

#ifdef CRYPTO_TPS

class cTPS : private cAES {
private:
  bool keySet;
  static const unsigned char T1[], T2[];
protected:
  void SetV2Key(const unsigned char *key);
  int Decrypt(unsigned char *data, int len);
public:
  cTPS(void);
  };

#endif //CRYPTO_TPS

#endif //___CRYPTO_H
