-1

I want to implement the following function:

  • I am using the Mersenne-Twister-Algorithm (from Wikipedia) as my pseudorandom number generator.
  • It is a stream cipher
  • The pseudocode is: encrypted text = CLEARTEXT XOR STREAM; the 'stream' is defined as PSEUDORANDOM_NUMBER XOR KEY

I wrote the following function:

int encrypt(char clear[1000], char key[100], int lk/*length of the cleatext*/, int ls /*length of key*/) {
  int a, i;
  unsigned char result[1000];
  char string[1000];

  for (i = 0; i <= lk; i++) {
    if (i+1-ls >= 0) {          /*if the key is too short*/
      a = mersenne_twister();
      string[i]=key[i+1-ls]^a;      /*XOR */
    } else {
      a=mersenne_twister();
      string[i] = key[i]^a;     /*XOR */
    }
  result[i] = clear[i]^string[i];
  putchar(result[i]);
  }

  return 1;
}

But the function does not work properly; it returns (the putchar part) something that is not readable. Where is my mistake? Or is the whole code wrong?

ljedrz
  • 20,316
  • 4
  • 69
  • 97
Kossi
  • 21
  • 1
  • 4

2 Answers2

1

If you are trying to print a char xored with something else, you will really often get strange characters. For instance, xoring 'M' with 'P' will result in '\GS' (Group Separator character), which is not printable.

ljedrz
  • 20,316
  • 4
  • 69
  • 97
1

Don't print the result as a character. It's not a character: you've XOR'd a character with some pseudo-random byte. The result is a byte. It may, by chance, be printable, but, then again, it may not be. You should treat the result for what it is, a byte, and print it as such:

/* format a byte as 2 hex digits */
printf("%02X", result[i]);

I will also add a cautionary note: do not use this "cipher". The Mersenne twister is not a cryptographically secure random number generator and the resulting cipher won't be secure either.

If you want to study stream ciphers, start with the simple Vernam cipher then read about RC4. Both are easy to understand and simple to implement. As a result they are good for getting your feet wet so to speak.

Nik Bougalis
  • 10,495
  • 1
  • 21
  • 37