summaryrefslogtreecommitdiffstatshomepage
path: root/src/mame/machine/315-5881_crypt.h
blob: 6b73ffd0700192ecc066e31a05b5ae9055de2dc7 (plain) (blame)
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#pragma once

#ifndef __SEGA315_5881_CRYPT__
#define __SEGA315_5881_CRYPT__

typedef device_delegate<UINT16 (UINT32)> sega_m2_read_delegate;

extern const device_type SEGA315_5881_CRYPT;

#define MCFG_SET_READ_CALLBACK( _class, _method) \
	sega_315_5881_crypt_device::set_read_cb(*device, sega_m2_read_delegate(&_class::_method, #_class "::" #_method, NULL, (_class *)0));


class sega_315_5881_crypt_device :  public device_t
{
public:
	// construction/destruction
	sega_315_5881_crypt_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock);


	UINT16 do_decrypt(UINT8 *&base);
	void set_addr_low(UINT16 data);
	void set_addr_high(UINT16 data);
	void set_subkey(UINT16 data);
	void set_key(UINT32 data);

	sega_m2_read_delegate m_read;

	static void set_read_cb(device_t &device,sega_m2_read_delegate readcb)
	{
		sega_315_5881_crypt_device &dev = downcast<sega_315_5881_crypt_device &>(device);
		dev.m_read = readcb;
	}

protected:
	virtual void device_start();
	virtual void device_reset();

private:

	enum {
		BUFFER_SIZE = 32768, LINE_SIZE = 512,
		FLAG_COMPRESSED = 0x10000, FLAG_LINE_SIZE_512 = 0x20000
	};

	UINT32 key;

	UINT8 *buffer, *line_buffer, *line_buffer_prev;
	UINT32 prot_cur_address;
	UINT16 subkey, dec_hist;
	UINT32 dec_header;

	bool enc_ready;

	int buffer_pos, line_buffer_pos, line_buffer_size, buffer_bit;

	struct sbox {
		UINT8 table[64];
		int inputs[6];      // positions of the inputs bits, -1 means no input except from key
		int outputs[2];     // positions of the output bits
	};

	static const sbox fn1_sboxes[4][4];
	static const sbox fn2_sboxes[4][4];

	static const int fn1_game_key_scheduling[38][2];
	static const int fn2_game_key_scheduling[34][2];
	static const int fn1_sequence_key_scheduling[20][2];
	static const int fn2_sequence_key_scheduling[16];
	static const int fn2_middle_result_scheduling[16];

	static const UINT8 trees[9][2][32];

	int feistel_function(int input, const struct sbox *sboxes, UINT32 subkeys);
	UINT16 block_decrypt(UINT32 game_key, UINT16 sequence_key, UINT16 counter, UINT16 data);

	UINT16 get_decrypted_16();
	int get_compressed_bit();

	void enc_start();
	void enc_fill();
	void line_fill();

};

#endif