/*
Code for 64 bit LFSR
Hunter Johnson
9/15/17
*/
#include
#include
#include
#include
#include
using namespace std;
/*The following struct will represent an LFSR with a 64 bit state.
The taps are represented by a 64 bit number, where the ith bit (from the right)
corresponds to p_i (in the notation of the textbook).
The uint64_t is a 64 bit unsigned integer.
There is a small chance that this code may behave unexpectedly if compiled on Windows or Mac.
Please let me know if you get issues.
It compiles and runs under clang and gcc. */
typedef struct {
uint64_t state;
uint64_t taps;
} LFSR;
int parity(uint64_t N)
{
/* Return the parity of N*/
int p = __builtin_parity(N); // parity of first 32 bits
N = __builtin_bswap64(N); //move back 32 to the front
return (p+__builtin_parity(N))%2; //overall parity
}
int read_lfsr(LFSR* L)
{
/*Return the current output bit (the rightmost bit of the state variable) */
uint64_t rightMostBit = L->state &1;
return rightMostBit;
}
void next_state(LFSR* L)
{
uint64_t next_bit = parity(L->state & L->taps);
L-> state = L->state >> 1;
L->state = L->state | (next_bit << 63);
}
void init_LFSR(LFSR* L, uint64_t initial_state, uint64_t taps)
{
/*Initialize with state and taps*/
L->state = initial_state;
L->taps = taps;
}
unsigned char get_stream_byte(LFSR* L)
{
/*Return one byte of keystream.
Note that the byte fills up from left to right.
*/
unsigned char C = 0;
int i = 7;
for(;i>=0;i--)
{
//printf("%d\n",read_lfsr(L));
C |= (read_lfsr(L)<*state = initial_state;
encrypt(pt,ct,L);
}
void get_128_keystream_bits(const char* ct, const char* kpt)
{
/*This function takes 16 bytes of ciphertext and 16 bytes of
known plaintext.
The output is a file named "key_stream.txt" that contains 128 bits
of keystream. The stream is represented in ASCII, with 128 lines, and
either a "0" or a "1" on each line.*/
FILE* ct_f = fopen(ct,"r");
FILE* fp = fopen("key_stream.txt","w");
FILE* fs = fopen("key.txt","w");
int i = 0;
for(;i<16;i++) //16 bytes
{
unsigned char ctc = getc(ct_f);
unsigned char b = ctc^kpt[i]; //the current byte
int j = 7;
for(;j>= 0;j--)
{
char current_bit = parity(b&(1 << j));
fprintf(fp, "%u\n", current_bit);
fprintf(fs, "%u", current_bit);
// int bit = parity(b & (1<*