summaryrefslogtreecommitdiffstats
path: root/Master/Kryptografie/prakt3/prakt3WS/p3/src/otp/LinReg.java
blob: 1e82b0ebd9e86e11df2668184c29f0b4ab427ad1 (plain)
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
88
89
90
91
92
93
94
95
96
97
98
99
100
package otp;

public class LinReg {
	private int config;
	private int status;
	
	public static final int bitMask = 0xff;
	public static final int bitLength = 8;
	
	public LinReg (int config, int init)
	{
		this.config = 0;
		this.status = 0;
		this.config = config & bitMask;
		this.status = init & bitMask;
		//printOut();
	}
	
	public int getNextKeyBit()
	{
		return this.getNextBit();
	}
	
	public int getNextKey()
	{
		int ret=0;
		int newBit;
		for (int i=7;i>=0;i--)
		{
			newBit = getNextBit();
			//System.out.println(i+". key bit is: "+Integer.toBinaryString(newBit));
			ret += ( newBit << i);
			//System.out.println("act key is: "+LinReg.to8BitString(ret));
		}
		//System.out.println("New key is: "+LinReg.to8BitString(ret));
		return ret & bitMask;
	}
	
	private int getNextBit()
	{
		//printOut();
		int ret=0;
		//boolean tmp=false;
		int cnt=0;
		// left shift status to get next bit at bitLength + 1;
		this.status = this.status << 1;
		//System.out.println("Left shifted status: "+Integer.toBinaryString(this.status));
		// get bit at bitLength + 1;
		ret = this.status & (~bitMask);
		//System.out.println("key bit unshifted is: "+Integer.toBinaryString(ret));
		ret >>= bitLength;
		//System.out.println("New key bit is: "+Integer.toBinaryString(ret));
		// calculate next bit from status and config
		for (int i = 7; i >= 0; i--)
		{
			// test if actual status and config bit are
			// set at position i
			//if ( (this.status & i) && (this.config & i) )
			int statusBit = ((this.status & (1<<i) ) >> i);
			int configBit = ((this.config & (1<<i) ) >> i);
			
			//System.out.println("Bit in Status: "+Integer.toBinaryString(statusBit));
			//System.out.println("Bit in Config: "+Integer.toBinaryString(configBit));
			
			if ( (statusBit & configBit) == 1 )
			{
				//System.out.println("Bit "+i+" is set in C and S");
				//tmp=!tmp;
				cnt++;
			}
		}
		if ( (cnt%2) == 1 )
		{
			this.status |= 1;
			//System.out.println("Appending 1 to status");
		}
		else
		{
			//System.out.println("Appending 0 to status");
		}
		this.status &= bitMask;
		//printOut();
		return ret;
	}
	public void printOut()
	{
		System.out.println("Config is: "+to8BitString(this.config));
		System.out.println("Status is: "+to8BitString(this.status));
	}
	
	public static final String to8BitString(int input)
	{
		String res = Integer.toBinaryString(input);
		for (int i = res.length();i<bitLength;i++)
		{
			res="0"+res;
		}
		return res;
	}
}