11/22/2011

Crypto-tools: Printing Ciphertext in Chunks

Now that we have generated ciphertext, it looks pretty much like a bunch of random characters which is not easily readable. That's why it's common practice for ciphertext to be wrote grouped into small chunks of 3, 4, 5 or more characters. The function we will write now is made to do exactly that.

As usually, we will iterate through the ciphertext string and send it to the output character by character. This time, we will need an additional counter in order to know when we complete printing a single group. The function is taking two arguments: the string to be printed and the groups size.

In the beginning, we will have to check if the size is smaller than 1 - if that's the case, we will just print out the whole string, without grouping it. Else, we will start iterating through the string.

In every iteration, we check if the counter reached the group size. If that's not the case, we will just print the current character, and increase the counter and the string pointer. Otherwise, we print a single blank space and reset the counter to 0. In the end, we print a newline character and that's it.

Here's the code:
void printf_groups(char *s, int group_size) {
  int i=0;
  if (group_size<=0) {
    puts(s);
    return;
  }
  while (*s) {
    if (i<group_size) {
      putchar(*s);
      ++s;
      ++i;
    }
    else {
      putchar(' ');
      i=0;
    }
  }
  printf("\n");
}
That's it; now you can try your new printf_groups function instead of the simple printf. Notice how the ciphertext is more readable. You can use this function in some other programs, too.

Next time, I'll add the current Crypto-tools project to my dropbox, so you can download and try it. We'll see how to implement the substitution cipher, too. It's not much different from Caesar cipher, but it's a little more complicated.

Comment, share, code! See you next time!

No comments:

Post a Comment

If you have anything useful to say (ideas, suggestions, questions, business proposals, or just "Thank you!"), please feel free to comment! Also, you can use my e-mail and/or find me on Twitter!