forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLFSR.java
More file actions
78 lines (65 loc) · 2.09 KB
/
LFSR.java
File metadata and controls
78 lines (65 loc) · 2.09 KB
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
package com.thealgorithms.ciphers.a5;
import java.util.BitSet;
public class LFSR implements BaseLFSR {
private final BitSet register;
private final int length;
private final int clockBitIndex;
private final int[] tappingBitsIndices;
public LFSR( int length, int clockBitIndex, int[] tappingBitsIndices ) {
this.length = length;
this.clockBitIndex = clockBitIndex;
this.tappingBitsIndices = tappingBitsIndices;
register = new BitSet( length );
}
@Override
public void initialize( BitSet sessionKey, BitSet frameCounter ) {
register.clear();
clock( sessionKey, SESSION_KEY_LENGTH );
clock( frameCounter, FRAME_COUNTER_LENGTH );
}
private void clock( BitSet key, int keyLength ) {
// We start from reverse because LFSR 0 index is the left most bit
// while key 0 index is right most bit, so we reverse it
for ( int i = keyLength - 1; i >= 0; --i ) {
var newBit = key.get( i ) ^ xorTappingBits();
pushBit( newBit );
}
}
@Override
public boolean clock() {
return pushBit( xorTappingBits() );
}
public boolean getClockBit() {
return register.get( clockBitIndex );
}
public boolean get( int bitIndex ) {
return register.get( bitIndex );
}
public boolean getLastBit() {
return register.get( length - 1 );
}
private boolean xorTappingBits() {
boolean result = false;
for ( int i : tappingBitsIndices ) {
result ^= register.get( i );
}
return result;
}
private boolean pushBit( boolean bit ) {
boolean discardedBit = rightShift();
register.set( 0, bit );
return discardedBit;
}
private boolean rightShift() {
boolean discardedBit = get( length - 1 );
for ( int i = length - 1; i > 0; --i ) {
register.set( i, get( i - 1 ) );
}
register.set( 0, false );
return discardedBit;
}
@Override
public String toString() {
return register.toString();
}
}