|
| 1 | +package com.thealgorithms.ciphers.a5; |
| 2 | + |
| 3 | +import java.util.BitSet; |
| 4 | + |
| 5 | +public class LFSR implements BaseLFSR { |
| 6 | + private final BitSet register; |
| 7 | + private final int length; |
| 8 | + private final int clockBitIndex; |
| 9 | + private final int[] tappingBitsIndices; |
| 10 | + |
| 11 | + public LFSR( int length, int clockBitIndex, int[] tappingBitsIndices ) { |
| 12 | + this.length = length; |
| 13 | + this.clockBitIndex = clockBitIndex; |
| 14 | + this.tappingBitsIndices = tappingBitsIndices; |
| 15 | + register = new BitSet( length ); |
| 16 | + } |
| 17 | + |
| 18 | + @Override |
| 19 | + public void initialize( BitSet sessionKey, BitSet frameCounter ) { |
| 20 | + register.clear(); |
| 21 | + clock( sessionKey, SESSION_KEY_LENGTH ); |
| 22 | + clock( frameCounter, FRAME_COUNTER_LENGTH ); |
| 23 | + } |
| 24 | + |
| 25 | + private void clock( BitSet key, int keyLength ) { |
| 26 | + // We start from reverse because LFSR 0 index is the left most bit |
| 27 | + // while key 0 index is right most bit, so we reverse it |
| 28 | + for ( int i = keyLength - 1; i >= 0; --i ) { |
| 29 | + var newBit = key.get( i ) ^ xorTappingBits(); |
| 30 | + pushBit( newBit ); |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + @Override |
| 35 | + public boolean clock() { |
| 36 | + return pushBit( xorTappingBits() ); |
| 37 | + } |
| 38 | + |
| 39 | + public boolean getClockBit() { |
| 40 | + return register.get( clockBitIndex ); |
| 41 | + } |
| 42 | + |
| 43 | + public boolean get( int bitIndex ) { |
| 44 | + return register.get( bitIndex ); |
| 45 | + } |
| 46 | + |
| 47 | + public boolean getLastBit() { |
| 48 | + return register.get( length - 1 ); |
| 49 | + } |
| 50 | + |
| 51 | + private boolean xorTappingBits() { |
| 52 | + boolean result = false; |
| 53 | + for ( int i : tappingBitsIndices ) { |
| 54 | + result ^= register.get( i ); |
| 55 | + } |
| 56 | + return result; |
| 57 | + } |
| 58 | + |
| 59 | + private boolean pushBit( boolean bit ) { |
| 60 | + boolean discardedBit = rightShift(); |
| 61 | + register.set( 0, bit ); |
| 62 | + return discardedBit; |
| 63 | + } |
| 64 | + |
| 65 | + private boolean rightShift() { |
| 66 | + boolean discardedBit = get( length - 1 ); |
| 67 | + for ( int i = length - 1; i > 0; --i ) { |
| 68 | + register.set( i, get( i - 1 ) ); |
| 69 | + } |
| 70 | + register.set( 0, false ); |
| 71 | + return discardedBit; |
| 72 | + } |
| 73 | + |
| 74 | + @Override |
| 75 | + public String toString() { |
| 76 | + return register.toString(); |
| 77 | + } |
| 78 | +} |
0 commit comments