Skip to content

Instantly share code, notes, and snippets.

@BobBurns
Created January 9, 2016 15:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BobBurns/2c41996ac4f7643cd7aa to your computer and use it in GitHub Desktop.
Save BobBurns/2c41996ac4f7643cd7aa to your computer and use it in GitHub Desktop.
Understanding Cryptography 2.11
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STREAM (256 * 8)
/* short program to understand linear feed shift register
* and its use in stream ciphers.
*
* modified to solve problem 2.11 in Understanding Cryptography by C. Paar
* stream cipher has 6 elements and letters are represented as 5 bit values.
* plain/cipher text input: a-z = 0-25, 0-5 = 26-31 represented as 00000-11111 binary.
*/
int
main(int argc, char argv[]) {
unsigned char in_s, cs, cp, p, nbit, s[STREAM];
unsigned char input[STREAM], output[STREAM];
int i, j, k=0, stl;
in_s = 0x3f; /* initial value 111111 */
p = 0x03; /* polynomial x^6+x^5+1 */
cs = in_s; /* copy initial state */
scanf("%s",&input);
stl = strlen(input) * 5;
/* first solve key bits s[k] */
while (k < stl) {
for (j = 0;j < 6;j++,k++) {
cp = nbit = cs & p;
for (i = 1;i < 6; i++) { /* xor all bits together */
nbit ^= (cp >> i);
}
s[k] = cs & 0x01;
nbit &= 1;
cs = (cs >> 1) | (nbit << 5); /* rotate in new bit */
}
}
printf("\ncipher-text: ");
unsigned char out = 0;
k = 4;
int c=0;
/* then xor cipher/plain text with key bits and print */
for (i = 0;i < stl;i++) {
out |= s[i]<<k;
k--;
if ((i+1) % 5 == 0) {
if (input[c] < 54) /* adjust for 0-5 = 26-31 in cipher */
input[c] += 75;
output[c] = ((input[c] - 0x61) ^ out) + 0x61;
if (output[c] > 0x7a)
output[c] -= 75;
printf("%c", output[c]);
k = 4;out = 0;c++;
}
}
printf("\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment